Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using Octopus.Client;
using Octopus.Client.Model;
using Octopus.Client.Model.Endpoints;
using Octopus.Tentacle.Certificates;
using Octopus.Tentacle.Commands;
using Octopus.Tentacle.Commands.OptionSets;
using Octopus.Tentacle.Configuration;
using Octopus.Tentacle.Core.Diagnostics;
using Octopus.Tentacle.Diagnostics;
using Octopus.Tentacle.Internals.Options;
using Octopus.Tentacle.Startup;
using Octopus.Tentacle.Tests.Support;

namespace Octopus.Tentacle.Tests.Commands
{
[TestFixture]
public class ReplaceCertificateCommandFixture
Comment thread
LukeButters marked this conversation as resolved.
Resolved
{
[Test]
public void ShouldUpdateEveryRegistrationWithTheOldThumbprintInEverySpace()
{
// Arrange
using var tentacle = new TentacleConfigurationBuilder().WithCertificateThumbprint("OLD").Build();
var target = new MachineResource { Id = "Machines-1", Endpoint = new ListeningTentacleEndpointResource { Thumbprint = "OLD" } };
var worker = new WorkerResource { Id = "Workers-1", Endpoint = new PollingTentacleEndpointResource { Uri = "poll://abc123/", Thumbprint = "OLD" } };
var octopus = new FakeOctopus();
var spaceA = octopus.Space("Spaces-1").WithMachine(target);
var spaceB = octopus.Space("Spaces-2").WithWorker(worker);

// Act
ReplaceCertificate(tentacle, octopus);

// Assert
var newThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint;
newThumbprint.Should().NotBe("OLD");
((TentacleEndpointResource)target.Endpoint).Thumbprint.Should().Be(newThumbprint);
((PollingTentacleEndpointResource)worker.Endpoint).Thumbprint.Should().Be(newThumbprint);
((PollingTentacleEndpointResource)worker.Endpoint).Uri.Should().Be("poll://abc123/");
spaceA.Machines.Received().Modify(target, Arg.Any<CancellationToken>());
spaceB.Workers.Received().Modify(worker, Arg.Any<CancellationToken>());
}

[Test]
public void WhenAnUpdateFailsRerunningWithApplyCurrentCertFinishesWithTheSameCertificate()
{
// Arrange
using var tentacle = new TentacleConfigurationBuilder().WithCertificateThumbprint("OLD").Build();
var first = new MachineResource { Id = "Machines-1", Endpoint = new ListeningTentacleEndpointResource { Thumbprint = "OLD" } };
var second = new MachineResource { Id = "Machines-2", Endpoint = new ListeningTentacleEndpointResource { Thumbprint = "OLD" } };
var octopus = new FakeOctopus();
var space = octopus.Space("Spaces-1").WithMachine(first).WithMachine(second);
var octopusIsDown = true;
space.Machines.Modify(second, Arg.Any<CancellationToken>()).Returns(_ =>
{
if (!octopusIsDown)
return Task.FromResult(second);
octopusIsDown = false;
((TentacleEndpointResource)second.Endpoint).Thumbprint = "OLD";
throw new Exception("Octopus is down");
});
Action run = () => ReplaceCertificate(tentacle, octopus);
run.Should().Throw<Exception>().WithMessage("Octopus is down");
var savedThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint;

// Act
ReplaceCertificate(tentacle, octopus, "--apply-current-cert-to-tentacles-with-thumbprint=OLD");

// Assert
tentacle.Configuration.TentacleCertificate!.Thumbprint.Should().Be(savedThumbprint);
((TentacleEndpointResource)first.Endpoint).Thumbprint.Should().Be(savedThumbprint);
((TentacleEndpointResource)second.Endpoint).Thumbprint.Should().Be(savedThumbprint);
}

[Test]
public void WhenNothingMatchesTheCertificateIsNotReplaced()
{
// Arrange
using var tentacle = new TentacleConfigurationBuilder().WithCertificateThumbprint("OLD").Build();
var octopus = new FakeOctopus();
octopus.Space("Spaces-1");

// Act
Action run = () => ReplaceCertificate(tentacle, octopus);

// Assert
run.Should().Throw<ControlledFailureException>().WithMessage("*OLD*");
tentacle.Configuration.TentacleCertificateThumbprint.Should().Be("OLD");
}

static void ReplaceCertificate(TemporaryTentacleConfiguration tentacle, FakeOctopus octopus, params string[] args)
=> new ReplaceCertificateCommand(
new Lazy<IWritableTentacleConfiguration>(() => tentacle.Configuration),
new Lazy<ICertificateGenerator>(() => new CertificateGenerator(new NullLog())),
octopus.ClientInitializer,
Substitute.For<IProxyConfigParser>(),
Substitute.For<ISystemLog>(),
tentacle.Selector,
Substitute.For<ILogFileOnlyLogger>())
.Start(new[] { "--server=http://octopus.test", "--apiKey=API-KEY" }.Concat(args).ToArray(), Substitute.For<ICommandRuntime>(), new OptionSet());

class FakeOctopus
{
readonly IOctopusAsyncClient client = Substitute.For<IOctopusAsyncClient>();
readonly List<SpaceResource> spaces = new();

public FakeOctopus()
{
var user = new UserResource();
client.ForSystem().Users.GetCurrent().Returns(user);
client.ForSystem().Users.GetSpaces(user).Returns(_ => spaces.ToArray());
ClientInitializer.CreateClient(Arg.Any<ApiEndpointOptions>(), Arg.Any<System.Net.IWebProxy?>()).Returns(client);
}

public IOctopusClientInitializer ClientInitializer { get; } = Substitute.For<IOctopusClientInitializer>();

public FakeSpace Space(string id)
{
var space = new SpaceResource { Id = id };
spaces.Add(space);
var repository = Substitute.For<IOctopusSpaceAsyncRepository>();
client.ForSpace(space).Returns(repository);
return new FakeSpace(repository);
}
}

class FakeSpace
{
readonly IOctopusSpaceAsyncRepository repository;
readonly List<MachineResource> machines = new();
readonly List<WorkerResource> workers = new();

public FakeSpace(IOctopusSpaceAsyncRepository repository)
{
this.repository = repository;
repository.Machines.FindByThumbprint(Arg.Any<string>()).Returns(c => machines.FindAll(m => ((TentacleEndpointResource)m.Endpoint).Thumbprint == c.Arg<string>()));
repository.Workers.FindByThumbprint(Arg.Any<string>()).Returns(c => workers.FindAll(w => ((TentacleEndpointResource)w.Endpoint).Thumbprint == c.Arg<string>()));
}

public Octopus.Client.Repositories.Async.IMachineRepository Machines => repository.Machines;
public Octopus.Client.Repositories.Async.IWorkerRepository Workers => repository.Workers;

public FakeSpace WithMachine(MachineResource machine)
{
machines.Add(machine);
return this;
}

public FakeSpace WithWorker(WorkerResource worker)
{
workers.Add(worker);
return this;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public IEnumerable<string> TrustedOctopusThumbprints
public string PackagesDirectory { get; private set; } = null!;
public string LogsDirectory { get; private set; } = null!;
public X509Certificate2 TentacleCertificate { get; set; } = null!;
public string? TentacleCertificateThumbprint => TentacleCertificate?.Thumbprint;
public string? ListenIpAddress { get; set; } = null!;
public bool NoListen { get; set; }
public OctopusServerConfiguration LastReceivedHandshake { get; set; } = null!;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System;
using System.IO;
using NSubstitute;
using Octopus.Tentacle.Certificates;
using Octopus.Tentacle.Configuration;
using Octopus.Tentacle.Configuration.Instances;
using Octopus.Tentacle.Core.Diagnostics;
using Octopus.Tentacle.Diagnostics;
using Octopus.Tentacle.Util;

namespace Octopus.Tentacle.Tests.Support
{
class TentacleConfigurationBuilder
{
string settings = "";

public TentacleConfigurationBuilder WithCertificateThumbprint(string thumbprint)
{
settings += $"<set key=\"Tentacle.CertificateThumbprint\">{thumbprint}</set>";
return this;
}

public TemporaryTentacleConfiguration Build()
{
var fileSystem = new OctopusPhysicalFileSystem(Substitute.For<ISystemLog>());
var directory = new TemporaryDirectory(fileSystem);
var configFile = Path.Combine(directory.DirectoryPath, "Tentacle.config");
File.WriteAllText(configFile, $"<?xml version=\"1.0\" encoding=\"utf-8\"?><octopus-settings>{settings}</octopus-settings>");
var store = new XmlFileKeyValueStore(fileSystem, configFile);

var selector = Substitute.For<IApplicationInstanceSelector>();
selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, configFile, store, store));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overtime we might improve this. I think tentacle is a PITA since it uses /etc/octopus which can only be changed by setting env vars but we don't want to set env vars in a test


var configuration = new WritableTentacleConfiguration(
selector,
Substitute.For<IHomeConfiguration>(),
new CertificateGenerator(new NullLog()),
Substitute.For<IProxyConfiguration>(),
Substitute.For<IPollingProxyConfiguration>(),
Substitute.For<ISystemLog>());

return new TemporaryTentacleConfiguration(directory, configuration, selector);
}
}

class TemporaryTentacleConfiguration : IDisposable
{
readonly TemporaryDirectory directory;

public TemporaryTentacleConfiguration(TemporaryDirectory directory, WritableTentacleConfiguration configuration, IApplicationInstanceSelector selector)
{
this.directory = directory;
Configuration = configuration;
Selector = selector;
}

public WritableTentacleConfiguration Configuration { get; }
public IApplicationInstanceSelector Selector { get; }

public void Dispose() => directory.Dispose();
}
}
112 changes: 112 additions & 0 deletions source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Octopus.Client;
using Octopus.Client.Model;
using Octopus.Client.Model.Endpoints;
using Octopus.Tentacle.Certificates;
using Octopus.Tentacle.Commands.OptionSets;
using Octopus.Tentacle.Configuration;
using Octopus.Tentacle.Configuration.Instances;
using Octopus.Tentacle.Core.Diagnostics;
using Octopus.Tentacle.Security;
using Octopus.Tentacle.Startup;

namespace Octopus.Tentacle.Commands
{
public class ReplaceCertificateCommand : AbstractStandardCommand
{
readonly Lazy<IWritableTentacleConfiguration> configuration;
readonly Lazy<ICertificateGenerator> certificateGenerator;
readonly IOctopusClientInitializer octopusClientInitializer;
readonly IProxyConfigParser proxyConfig;
readonly ISystemLog log;
readonly ApiEndpointOptions api;
string applyCurrentCertToTentaclesWithThumbprint = null!;

public ReplaceCertificateCommand(
Lazy<IWritableTentacleConfiguration> configuration,
Lazy<ICertificateGenerator> certificateGenerator,
IOctopusClientInitializer octopusClientInitializer,
IProxyConfigParser proxyConfig,
ISystemLog log,
IApplicationInstanceSelector selector,
ILogFileOnlyLogger logFileOnlyLogger)
: base(selector, log, logFileOnlyLogger)
{
this.configuration = configuration;
this.certificateGenerator = certificateGenerator;
this.octopusClientInitializer = octopusClientInitializer;
this.proxyConfig = proxyConfig;
this.log = log;

api = AddOptionSet(new ApiEndpointOptions(Options));
Options.Add("apply-current-cert-to-tentacles-with-thumbprint=", "Does not create a new certificate. Instead, updates every deployment target and worker in Octopus that has this thumbprint to trust this Tentacle's current certificate.", s => applyCurrentCertToTentaclesWithThumbprint = s);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if the command fails, the user will have to re-run with this.

we also log:

log.Info($"Replaced certificate {oldThumbprint} with {certificate.Thumbprint}. If this does not complete, re-run this command with --apply-current-cert-to-tentacles-with-thumbprint {oldThumbprint}");

}

protected override void Start()
{
base.Start();
StartAsync().GetAwaiter().GetResult();
}

async Task StartAsync()
{
var config = configuration.Value;
var keepCurrentCertificate = !string.IsNullOrWhiteSpace(applyCurrentCertToTentaclesWithThumbprint);
var oldThumbprint = keepCurrentCertificate ? applyCurrentCertToTentaclesWithThumbprint : config.TentacleCertificateThumbprint;
if (string.IsNullOrWhiteSpace(oldThumbprint) || string.IsNullOrWhiteSpace(config.TentacleCertificateThumbprint))
{
throw new ControlledFailureException("This Tentacle has no certificate thumbprint in its configuration, so its registrations in Octopus cannot be found.");
}

using var client = await octopusClientInitializer.CreateClient(api, proxyConfig.ParseToWebProxy(config.PollingProxyConfiguration));
var registrations = await FindRegistrations(client, oldThumbprint!);
if (registrations.Count == 0)
{
throw new ControlledFailureException($"No deployment target or worker with thumbprint {oldThumbprint} was found in any space this API key can access.");
}

if (!keepCurrentCertificate)
{
var certificate = certificateGenerator.Value.GenerateNew(CertificateExpectations.TentacleCertificateFullName);
config.ImportCertificate(certificate);
log.Info($"Replaced certificate {oldThumbprint} with {certificate.Thumbprint}. If this does not complete, re-run this command with --apply-current-cert-to-tentacles-with-thumbprint {oldThumbprint}");
}

foreach (var (repository, machine) in registrations)
{
((TentacleEndpointResource)machine.Endpoint).Thumbprint = config.TentacleCertificateThumbprint;
await Modify(repository, machine);
log.Info($"Updated '{machine.Name}' ({machine.Id}) in Octopus to trust the new certificate");
}

VoteForRestart();
}

static async Task<List<(IOctopusSpaceAsyncRepository Repository, MachineBasedResource Machine)>> FindRegistrations(IOctopusAsyncClient client, string thumbprint)
{
var users = client.ForSystem().Users;
var spaces = await users.GetSpaces(await users.GetCurrent());

var registrations = new List<(IOctopusSpaceAsyncRepository, MachineBasedResource)>();
foreach (var space in spaces)
{
var repository = client.ForSpace(space);
var machines = (await repository.Machines.FindByThumbprint(thumbprint)).Cast<MachineBasedResource>()
.Concat(await repository.Workers.FindByThumbprint(thumbprint))
.Where(m => m.Endpoint is ListeningTentacleEndpointResource or PollingTentacleEndpointResource);
registrations.AddRange(machines.Select(m => (repository, m)));
}

return registrations;
}

static Task Modify(IOctopusSpaceAsyncRepository repository, MachineBasedResource machine)
=> machine is WorkerResource worker
? repository.Workers.Modify(worker, CancellationToken.None)
: repository.Machines.Modify((MachineResource)machine, CancellationToken.None);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ public interface ITentacleConfiguration
/// </summary>
X509Certificate2? TentacleCertificate { get; }

/// <summary>
/// The thumbprint of the Tentacle certificate. Stored unencrypted, so it can be read even when the certificate cannot.
/// </summary>
string? TentacleCertificateThumbprint { get; }

/// <summary>
/// Gets the IP address to listen on.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ public string PackagesDirectory
get { return Path.Combine(ApplicationDirectory, "Packages"); }
}

public string? TentacleCertificateThumbprint => settings.Get(CertificateThumbprintSettingName);

public X509Certificate2? TentacleCertificate
{
get
Expand Down
1 change: 1 addition & 0 deletions source/Octopus.Tentacle/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ public override IContainer BuildContainer(StartUpInstanceRequest startUpInstance
builder.RegisterCommand<ProxyConfigurationCommand>("proxy", "Configure the HTTP proxy used by Octopus");
builder.RegisterCommand<PollingProxyConfigurationCommand>("polling-proxy", "Configure the HTTP proxy used by polling Tentacles to reach the Octopus Server");
builder.RegisterCommand<ServerCommsCommand>("server-comms", "Configure how the Tentacle communicates with an Octopus Server");
builder.RegisterCommand<ReplaceCertificateCommand>("replace-certificate", "Creates and installs a new certificate for this Tentacle and updates every deployment target and worker in Octopus registered with the old certificate to trust it");
builder.RegisterCommand<ImportCertificateCommand>("import-certificate", "Replace the certificate that Tentacle uses to authenticate itself");
builder.RegisterCommand<PollCommand>("poll-server", "Configures an Octopus Server that this Tentacle will poll");
builder.RegisterCommand<ClearTrustedServersCommand>("clear-trusted-servers", "Clears trusted servers in the Tentacle Configuration");
Expand Down