diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs new file mode 100644 index 000000000..80720309d --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -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 + { + [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()); + spaceB.Workers.Received().Modify(worker, Arg.Any()); + } + + [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()).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().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().WithMessage("*OLD*"); + tentacle.Configuration.TentacleCertificateThumbprint.Should().Be("OLD"); + } + + static void ReplaceCertificate(TemporaryTentacleConfiguration tentacle, FakeOctopus octopus, params string[] args) + => new ReplaceCertificateCommand( + new Lazy(() => tentacle.Configuration), + new Lazy(() => new CertificateGenerator(new NullLog())), + octopus.ClientInitializer, + Substitute.For(), + Substitute.For(), + tentacle.Selector, + Substitute.For()) + .Start(new[] { "--server=http://octopus.test", "--apiKey=API-KEY" }.Concat(args).ToArray(), Substitute.For(), new OptionSet()); + + class FakeOctopus + { + readonly IOctopusAsyncClient client = Substitute.For(); + readonly List 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(), Arg.Any()).Returns(client); + } + + public IOctopusClientInitializer ClientInitializer { get; } = Substitute.For(); + + public FakeSpace Space(string id) + { + var space = new SpaceResource { Id = id }; + spaces.Add(space); + var repository = Substitute.For(); + client.ForSpace(space).Returns(repository); + return new FakeSpace(repository); + } + } + + class FakeSpace + { + readonly IOctopusSpaceAsyncRepository repository; + readonly List machines = new(); + readonly List workers = new(); + + public FakeSpace(IOctopusSpaceAsyncRepository repository) + { + this.repository = repository; + repository.Machines.FindByThumbprint(Arg.Any()).Returns(c => machines.FindAll(m => ((TentacleEndpointResource)m.Endpoint).Thumbprint == c.Arg())); + repository.Workers.FindByThumbprint(Arg.Any()).Returns(c => workers.FindAll(w => ((TentacleEndpointResource)w.Endpoint).Thumbprint == c.Arg())); + } + + 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; + } + } + } +} diff --git a/source/Octopus.Tentacle.Tests/Commands/StubTentacleConfiguration.cs b/source/Octopus.Tentacle.Tests/Commands/StubTentacleConfiguration.cs index 25e0a2e9d..c60c71e3e 100644 --- a/source/Octopus.Tentacle.Tests/Commands/StubTentacleConfiguration.cs +++ b/source/Octopus.Tentacle.Tests/Commands/StubTentacleConfiguration.cs @@ -31,6 +31,7 @@ public IEnumerable 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!; diff --git a/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs new file mode 100644 index 000000000..c4c93919c --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs @@ -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 += $"{thumbprint}"; + return this; + } + + public TemporaryTentacleConfiguration Build() + { + var fileSystem = new OctopusPhysicalFileSystem(Substitute.For()); + var directory = new TemporaryDirectory(fileSystem); + var configFile = Path.Combine(directory.DirectoryPath, "Tentacle.config"); + File.WriteAllText(configFile, $"{settings}"); + var store = new XmlFileKeyValueStore(fileSystem, configFile); + + var selector = Substitute.For(); + selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, configFile, store, store)); + + var configuration = new WritableTentacleConfiguration( + selector, + Substitute.For(), + new CertificateGenerator(new NullLog()), + Substitute.For(), + Substitute.For(), + Substitute.For()); + + 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(); + } +} diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs new file mode 100644 index 000000000..768938a07 --- /dev/null +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -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 configuration; + readonly Lazy certificateGenerator; + readonly IOctopusClientInitializer octopusClientInitializer; + readonly IProxyConfigParser proxyConfig; + readonly ISystemLog log; + readonly ApiEndpointOptions api; + string applyCurrentCertToTentaclesWithThumbprint = null!; + + public ReplaceCertificateCommand( + Lazy configuration, + Lazy 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); + } + + 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> 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() + .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); + } +} diff --git a/source/Octopus.Tentacle/Configuration/ITentacleConfiguration.cs b/source/Octopus.Tentacle/Configuration/ITentacleConfiguration.cs index c256eb946..534b8a956 100644 --- a/source/Octopus.Tentacle/Configuration/ITentacleConfiguration.cs +++ b/source/Octopus.Tentacle/Configuration/ITentacleConfiguration.cs @@ -47,6 +47,11 @@ public interface ITentacleConfiguration /// X509Certificate2? TentacleCertificate { get; } + /// + /// The thumbprint of the Tentacle certificate. Stored unencrypted, so it can be read even when the certificate cannot. + /// + string? TentacleCertificateThumbprint { get; } + /// /// Gets the IP address to listen on. /// diff --git a/source/Octopus.Tentacle/Configuration/TentacleConfiguration.cs b/source/Octopus.Tentacle/Configuration/TentacleConfiguration.cs index 91b74a57f..3965b467d 100644 --- a/source/Octopus.Tentacle/Configuration/TentacleConfiguration.cs +++ b/source/Octopus.Tentacle/Configuration/TentacleConfiguration.cs @@ -126,6 +126,8 @@ public string PackagesDirectory get { return Path.Combine(ApplicationDirectory, "Packages"); } } + public string? TentacleCertificateThumbprint => settings.Get(CertificateThumbprintSettingName); + public X509Certificate2? TentacleCertificate { get diff --git a/source/Octopus.Tentacle/Program.cs b/source/Octopus.Tentacle/Program.cs index 7da1fc6a2..f4c4d5f50 100644 --- a/source/Octopus.Tentacle/Program.cs +++ b/source/Octopus.Tentacle/Program.cs @@ -86,6 +86,7 @@ public override IContainer BuildContainer(StartUpInstanceRequest startUpInstance builder.RegisterCommand("proxy", "Configure the HTTP proxy used by Octopus"); builder.RegisterCommand("polling-proxy", "Configure the HTTP proxy used by polling Tentacles to reach the Octopus Server"); builder.RegisterCommand("server-comms", "Configure how the Tentacle communicates with an Octopus Server"); + builder.RegisterCommand("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("import-certificate", "Replace the certificate that Tentacle uses to authenticate itself"); builder.RegisterCommand("poll-server", "Configures an Octopus Server that this Tentacle will poll"); builder.RegisterCommand("clear-trusted-servers", "Clears trusted servers in the Tentacle Configuration");