From cbdddee116991921b8bb3a83e61da60cabaaebee Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 14:14:42 +1100 Subject: [PATCH 01/12] Add replace-certificate to give a Tentacle a new certificate without re-registering --- .../ReplaceCertificateCommandFixture.cs | 93 +++++++++++++ .../Commands/ReplaceCertificateCommand.cs | 125 ++++++++++++++++++ source/Octopus.Tentacle/Program.cs | 1 + 3 files changed, 219 insertions(+) create mode 100644 source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs create mode 100644 source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs new file mode 100644 index 000000000..3aba8ca78 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -0,0 +1,93 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Client; +using Octopus.Client.Model; +using Octopus.Client.Model.Endpoints; +using Octopus.Client.Repositories.Async; +using Octopus.Tentacle.Certificates; +using Octopus.Tentacle.Commands; +using Octopus.Tentacle.Commands.OptionSets; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Diagnostics; +using Octopus.Tentacle.Startup; + +namespace Octopus.Tentacle.Tests.Commands +{ + [TestFixture] + public class ReplaceCertificateCommandFixture : CommandFixture + { + const string ServerThumbprint = "SERVERTHUMBPRINT"; + + IWritableTentacleConfiguration configuration; + IOctopusAsyncRepository repository; + System.Security.Cryptography.X509Certificates.X509Certificate2 certificate; + + [SetUp] + public void BeforeEachTest() + { + configuration = Substitute.For(); + certificate = new CertificateGenerator(new NullLog()).GenerateNew("CN=Hello"); + configuration.GenerateNewCertificate().Returns(certificate); + + repository = Substitute.For(); + var certificateConfiguration = Substitute.For(); + certificateConfiguration.GetOctopusCertificate().Returns(Task.FromResult(new CertificateConfigurationResource { Thumbprint = ServerThumbprint })); + repository.CertificateConfiguration.Returns(certificateConfiguration); + + var client = Substitute.For(); + client.Repository.Returns(repository); + client.ForSystem().Returns(repository); + var clientInitializer = Substitute.For(); + clientInitializer.CreateClient(Arg.Any(), Arg.Any()).Returns(Task.FromResult(client)); + + var selector = Substitute.For(); + selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + + Command = new ReplaceCertificateCommand( + new Lazy(() => configuration), + clientInitializer, + new SpaceRepositoryFactory(), + Substitute.For(), + selector, + Substitute.For()); + } + + [Test] + public void ShouldOnlyChangeTheThumbprintOfAPollingWorkerAndTrustTheServer() + { + var endpoint = new PollingTentacleEndpointResource { Uri = "poll://abc123/", Thumbprint = "OLD" }; + var worker = new WorkerResource { Id = "Workers-1", Name = "MyWorker", Endpoint = endpoint, WorkerPoolIds = new ReferenceCollection("WorkerPools-1") }; + repository.Workers.FindByName("MyWorker", Arg.Any()).Returns(Task.FromResult(worker)); + + Start("--server=http://octopus.test", "--apiKey=API-KEY", "--name=MyWorker"); + + repository.Workers.Received().Modify(Arg.Is(w => w == worker + && ((PollingTentacleEndpointResource)w.Endpoint).Thumbprint == certificate.Thumbprint + && ((PollingTentacleEndpointResource)w.Endpoint).Uri == "poll://abc123/" + && w.WorkerPoolIds.Contains("WorkerPools-1")), Arg.Any()); + configuration.Received().AddOrUpdateTrustedOctopusServer(Arg.Is(s => + s.Thumbprint == ServerThumbprint + && s.CommunicationStyle == CommunicationStyle.TentacleActive + && s.Address == new Uri("https://octopus.test:10943") + && s.SubscriptionId == "poll://abc123/")); + } + + [Test] + public void ShouldRefuseAnAmbiguousNameRatherThanGuessBetweenATargetAndAWorker() + { + repository.Machines.FindByName("Shared", Arg.Any()).Returns(Task.FromResult(new MachineResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() })); + repository.Workers.FindByName("Shared", Arg.Any()).Returns(Task.FromResult(new WorkerResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() })); + + Action start = () => Start("--server=http://octopus.test", "--apiKey=API-KEY", "--name=Shared"); + + start.Should().Throw().WithMessage("*--id*"); + configuration.DidNotReceive().GenerateNewCertificate(); + } + } +} diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs new file mode 100644 index 000000000..caed425ae --- /dev/null +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -0,0 +1,125 @@ +using System; +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.Commands.OptionSets; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Startup; + +namespace Octopus.Tentacle.Commands +{ + public class ReplaceCertificateCommand : AbstractStandardCommand + { + const int DefaultServerCommsPort = 10943; + + readonly Lazy configuration; + readonly IOctopusClientInitializer octopusClientInitializer; + readonly ISpaceRepositoryFactory spaceRepositoryFactory; + readonly ISystemLog log; + readonly ApiEndpointOptions api; + string name = null!; + string id = null!; + string spaceName = null!; + string serverCommsAddress = null!; + int? serverCommsPort; + + public ReplaceCertificateCommand( + Lazy configuration, + IOctopusClientInitializer octopusClientInitializer, + ISpaceRepositoryFactory spaceRepositoryFactory, + ISystemLog log, + IApplicationInstanceSelector selector, + ILogFileOnlyLogger logFileOnlyLogger) + : base(selector, log, logFileOnlyLogger) + { + this.configuration = configuration; + this.octopusClientInitializer = octopusClientInitializer; + this.spaceRepositoryFactory = spaceRepositoryFactory; + this.log = log; + + api = AddOptionSet(new ApiEndpointOptions(Options)); + Options.Add("name=", "The name of the existing deployment target or worker in Octopus", s => name = s); + Options.Add("id=", "The ID of the existing deployment target or worker in Octopus, e.g. Machines-1 or Workers-1", s => id = s); + Options.Add("space=", "The name of the space the deployment target or worker is in. The default space will be used if omitted.", s => spaceName = s); + Options.Add("server-comms-address=", "For a polling Tentacle, the comms address on the Octopus Server; the address of the Octopus Server will be used if omitted.", s => serverCommsAddress = s); + Options.Add("server-comms-port=", "For a polling Tentacle, the comms port on the Octopus Server; the default is " + DefaultServerCommsPort + ". If specified, this will take precedence over any port number in server-comms-address.", s => serverCommsPort = int.Parse(s)); + } + + protected override void Start() + { + base.Start(); + StartAsync().GetAwaiter().GetResult(); + } + + async Task StartAsync() + { + if (string.IsNullOrWhiteSpace(name) == string.IsNullOrWhiteSpace(id)) + throw new ControlledFailureException("Please specify either --name or --id of the existing deployment target or worker."); + + using var client = await octopusClientInitializer.CreateClient(api, configuration.Value.ProxyConfiguration.UseDefaultProxy); + var repository = await spaceRepositoryFactory.CreateSpaceRepository(client, spaceName); + + var machine = await FindMachine(repository); + var server = new OctopusServerConfiguration((await client.ForSystem().CertificateConfiguration.GetOctopusCertificate()).Thumbprint); + switch (machine.Endpoint) + { + case ListeningTentacleEndpointResource: + server.CommunicationStyle = CommunicationStyle.TentaclePassive; + break; + case PollingTentacleEndpointResource polling: + server.CommunicationStyle = CommunicationStyle.TentacleActive; + server.Address = GetPollingServerAddress(); + server.SubscriptionId = polling.Uri; + break; + default: + throw new ControlledFailureException($"'{machine.Name}' uses a {machine.Endpoint.CommunicationStyle} endpoint. Only listening and polling Tentacles can have their certificate replaced."); + } + + var certificate = configuration.Value.GenerateNewCertificate(); + log.Info($"Generated a new certificate with thumbprint {certificate.Thumbprint}"); + + ((TentacleEndpointResource)machine.Endpoint).Thumbprint = certificate.Thumbprint; + await Modify(repository, machine); + log.Info($"Updated '{machine.Name}' ({machine.Id}) in Octopus to trust the new certificate"); + + configuration.Value.AddOrUpdateTrustedOctopusServer(server); + VoteForRestart(); + } + + async Task FindMachine(IOctopusSpaceAsyncRepository repository) + { + if (!string.IsNullOrWhiteSpace(id)) + return id.StartsWith("Workers-", StringComparison.OrdinalIgnoreCase) + ? await repository.Workers.Get(id, CancellationToken.None) + : await repository.Machines.Get(id, CancellationToken.None); + + var matches = new MachineBasedResource?[] { await repository.Machines.FindByName(name, CancellationToken.None), await repository.Workers.FindByName(name, CancellationToken.None) } + .OfType() + .ToArray(); + + return matches.Length switch + { + 0 => throw new ControlledFailureException($"No deployment target or worker named '{name}' was found."), + 1 => matches[0], + _ => throw new ControlledFailureException($"Both a deployment target and a worker are named '{name}'. Please specify which one with --id.") + }; + } + + static Task Modify(IOctopusSpaceAsyncRepository repository, MachineBasedResource machine) + => machine is WorkerResource worker + ? repository.Workers.Modify(worker, CancellationToken.None) + : repository.Machines.Modify((MachineResource)machine, CancellationToken.None); + + Uri GetPollingServerAddress() + { + var address = string.IsNullOrEmpty(serverCommsAddress) ? api.ServerUri : new Uri(serverCommsAddress); + var port = serverCommsPort ?? (string.IsNullOrEmpty(serverCommsAddress) ? DefaultServerCommsPort : address.Port); + return new Uri($"https://{address.Host}:{port}"); + } + } +} diff --git a/source/Octopus.Tentacle/Program.cs b/source/Octopus.Tentacle/Program.cs index 7da1fc6a2..8f89239bb 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 its existing deployment target or worker in Octopus 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"); From d6b951e95ec7b926590c8a7a476cb85c3a301cbf Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 19 Nov 2026 16:04:29 +1100 Subject: [PATCH 02/12] Test replace-certificate against the real Tentacle configuration --- .../ReplaceCertificateCommandFixture.cs | 54 ++++++++++++------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index 3aba8ca78..341ad66e3 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Threading; using System.Threading.Tasks; using FluentAssertions; @@ -16,6 +17,8 @@ using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Diagnostics; using Octopus.Tentacle.Startup; +using Octopus.Tentacle.Tests.Support; +using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Commands { @@ -24,16 +27,29 @@ public class ReplaceCertificateCommandFixture : CommandFixture(); - certificate = new CertificateGenerator(new NullLog()).GenerateNew("CN=Hello"); - configuration.GenerateNewCertificate().Returns(certificate); + var fileSystem = new OctopusPhysicalFileSystem(Substitute.For()); + temporaryDirectory = new TemporaryDirectory(fileSystem); + var configFile = Path.Combine(temporaryDirectory.DirectoryPath, "Tentacle.config"); + File.WriteAllText(configFile, ""); + var store = new XmlFileKeyValueStore(fileSystem, configFile); + + var selector = Substitute.For(); + selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, configFile, store, store)); + + configuration = new WritableTentacleConfiguration( + selector, + Substitute.For(), + new CertificateGenerator(new NullLog()), + Substitute.For(), + Substitute.For(), + Substitute.For()); repository = Substitute.For(); var certificateConfiguration = Substitute.For(); @@ -46,9 +62,6 @@ public void BeforeEachTest() var clientInitializer = Substitute.For(); clientInitializer.CreateClient(Arg.Any(), Arg.Any()).Returns(Task.FromResult(client)); - var selector = Substitute.For(); - selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, null!, null!, null!)); - Command = new ReplaceCertificateCommand( new Lazy(() => configuration), clientInitializer, @@ -58,6 +71,9 @@ public void BeforeEachTest() Substitute.For()); } + [TearDown] + public void AfterEachTest() => temporaryDirectory.Dispose(); + [Test] public void ShouldOnlyChangeTheThumbprintOfAPollingWorkerAndTrustTheServer() { @@ -67,15 +83,17 @@ public void ShouldOnlyChangeTheThumbprintOfAPollingWorkerAndTrustTheServer() Start("--server=http://octopus.test", "--apiKey=API-KEY", "--name=MyWorker"); - repository.Workers.Received().Modify(Arg.Is(w => w == worker - && ((PollingTentacleEndpointResource)w.Endpoint).Thumbprint == certificate.Thumbprint - && ((PollingTentacleEndpointResource)w.Endpoint).Uri == "poll://abc123/" - && w.WorkerPoolIds.Contains("WorkerPools-1")), Arg.Any()); - configuration.Received().AddOrUpdateTrustedOctopusServer(Arg.Is(s => - s.Thumbprint == ServerThumbprint - && s.CommunicationStyle == CommunicationStyle.TentacleActive - && s.Address == new Uri("https://octopus.test:10943") - && s.SubscriptionId == "poll://abc123/")); + var newThumbprint = configuration.TentacleCertificate!.Thumbprint; + newThumbprint.Should().NotBe("OLD"); + endpoint.Thumbprint.Should().Be(newThumbprint); + endpoint.Uri.Should().Be("poll://abc123/"); + worker.WorkerPoolIds.Should().Contain("WorkerPools-1"); + + var server = configuration.TrustedOctopusServers.Should().ContainSingle().Subject; + server.Thumbprint.Should().Be(ServerThumbprint); + server.CommunicationStyle.Should().Be(CommunicationStyle.TentacleActive); + server.Address.Should().Be(new Uri("https://octopus.test:10943")); + server.SubscriptionId.Should().Be("poll://abc123/"); } [Test] @@ -87,7 +105,7 @@ public void ShouldRefuseAnAmbiguousNameRatherThanGuessBetweenATargetAndAWorker() Action start = () => Start("--server=http://octopus.test", "--apiKey=API-KEY", "--name=Shared"); start.Should().Throw().WithMessage("*--id*"); - configuration.DidNotReceive().GenerateNewCertificate(); + configuration.TentacleCertificate.Should().BeNull(); } } } From 82322973de8874513d3cbd15b92b88eceef8eb64 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 19 Nov 2026 16:22:16 +1100 Subject: [PATCH 03/12] Build the replace-certificate test's Tentacle and Octopus per test instead of in setup --- .../ReplaceCertificateCommandFixture.cs | 131 +++++++++--------- .../Support/TentacleConfigurationBuilder.cs | 54 ++++++++ 2 files changed, 122 insertions(+), 63 deletions(-) create mode 100644 source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index 341ad66e3..41662a228 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -1,5 +1,4 @@ using System; -using System.IO; using System.Threading; using System.Threading.Tasks; using FluentAssertions; @@ -9,87 +8,39 @@ using Octopus.Client.Model; using Octopus.Client.Model.Endpoints; using Octopus.Client.Repositories.Async; -using Octopus.Tentacle.Certificates; using Octopus.Tentacle.Commands; using Octopus.Tentacle.Commands.OptionSets; using Octopus.Tentacle.Configuration; -using Octopus.Tentacle.Configuration.Instances; using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Diagnostics; +using Octopus.Tentacle.Internals.Options; using Octopus.Tentacle.Startup; using Octopus.Tentacle.Tests.Support; -using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Commands { [TestFixture] - public class ReplaceCertificateCommandFixture : CommandFixture + public class ReplaceCertificateCommandFixture { const string ServerThumbprint = "SERVERTHUMBPRINT"; - TemporaryDirectory temporaryDirectory; - WritableTentacleConfiguration configuration; - IOctopusAsyncRepository repository; - - [SetUp] - public void BeforeEachTest() - { - var fileSystem = new OctopusPhysicalFileSystem(Substitute.For()); - temporaryDirectory = new TemporaryDirectory(fileSystem); - var configFile = Path.Combine(temporaryDirectory.DirectoryPath, "Tentacle.config"); - File.WriteAllText(configFile, ""); - var store = new XmlFileKeyValueStore(fileSystem, configFile); - - var selector = Substitute.For(); - selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, configFile, store, store)); - - configuration = new WritableTentacleConfiguration( - selector, - Substitute.For(), - new CertificateGenerator(new NullLog()), - Substitute.For(), - Substitute.For(), - Substitute.For()); - - repository = Substitute.For(); - var certificateConfiguration = Substitute.For(); - certificateConfiguration.GetOctopusCertificate().Returns(Task.FromResult(new CertificateConfigurationResource { Thumbprint = ServerThumbprint })); - repository.CertificateConfiguration.Returns(certificateConfiguration); - - var client = Substitute.For(); - client.Repository.Returns(repository); - client.ForSystem().Returns(repository); - var clientInitializer = Substitute.For(); - clientInitializer.CreateClient(Arg.Any(), Arg.Any()).Returns(Task.FromResult(client)); - - Command = new ReplaceCertificateCommand( - new Lazy(() => configuration), - clientInitializer, - new SpaceRepositoryFactory(), - Substitute.For(), - selector, - Substitute.For()); - } - - [TearDown] - public void AfterEachTest() => temporaryDirectory.Dispose(); - [Test] public void ShouldOnlyChangeTheThumbprintOfAPollingWorkerAndTrustTheServer() { - var endpoint = new PollingTentacleEndpointResource { Uri = "poll://abc123/", Thumbprint = "OLD" }; - var worker = new WorkerResource { Id = "Workers-1", Name = "MyWorker", Endpoint = endpoint, WorkerPoolIds = new ReferenceCollection("WorkerPools-1") }; - repository.Workers.FindByName("MyWorker", Arg.Any()).Returns(Task.FromResult(worker)); + using var tentacle = new TentacleConfigurationBuilder().Build(); + var worker = PollingWorker("MyWorker", "poll://abc123/", "WorkerPools-1"); + var octopus = new FakeOctopus(ServerThumbprint).WithWorker(worker); - Start("--server=http://octopus.test", "--apiKey=API-KEY", "--name=MyWorker"); + Run(CreateCommand(tentacle, octopus), "--server=http://octopus.test", "--apiKey=API-KEY", "--name=MyWorker"); - var newThumbprint = configuration.TentacleCertificate!.Thumbprint; + var endpoint = (PollingTentacleEndpointResource)worker.Endpoint; + var newThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint; newThumbprint.Should().NotBe("OLD"); endpoint.Thumbprint.Should().Be(newThumbprint); endpoint.Uri.Should().Be("poll://abc123/"); worker.WorkerPoolIds.Should().Contain("WorkerPools-1"); - var server = configuration.TrustedOctopusServers.Should().ContainSingle().Subject; + var server = tentacle.Configuration.TrustedOctopusServers.Should().ContainSingle().Subject; server.Thumbprint.Should().Be(ServerThumbprint); server.CommunicationStyle.Should().Be(CommunicationStyle.TentacleActive); server.Address.Should().Be(new Uri("https://octopus.test:10943")); @@ -99,13 +50,67 @@ public void ShouldOnlyChangeTheThumbprintOfAPollingWorkerAndTrustTheServer() [Test] public void ShouldRefuseAnAmbiguousNameRatherThanGuessBetweenATargetAndAWorker() { - repository.Machines.FindByName("Shared", Arg.Any()).Returns(Task.FromResult(new MachineResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() })); - repository.Workers.FindByName("Shared", Arg.Any()).Returns(Task.FromResult(new WorkerResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() })); + using var tentacle = new TentacleConfigurationBuilder().Build(); + var octopus = new FakeOctopus(ServerThumbprint) + .WithMachine(new MachineResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() }) + .WithWorker(new WorkerResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() }); - Action start = () => Start("--server=http://octopus.test", "--apiKey=API-KEY", "--name=Shared"); + Action run = () => Run(CreateCommand(tentacle, octopus), "--server=http://octopus.test", "--apiKey=API-KEY", "--name=Shared"); - start.Should().Throw().WithMessage("*--id*"); - configuration.TentacleCertificate.Should().BeNull(); + run.Should().Throw().WithMessage("*--id*"); + tentacle.Configuration.TentacleCertificate.Should().BeNull(); + } + + static WorkerResource PollingWorker(string name, string subscription, string pool) + => new() + { + Id = "Workers-1", + Name = name, + Endpoint = new PollingTentacleEndpointResource { Uri = subscription, Thumbprint = "OLD" }, + WorkerPoolIds = new ReferenceCollection(pool) + }; + + static ReplaceCertificateCommand CreateCommand(TemporaryTentacleConfiguration tentacle, FakeOctopus octopus) + => new( + new Lazy(() => tentacle.Configuration), + octopus.ClientInitializer, + new SpaceRepositoryFactory(), + Substitute.For(), + tentacle.Selector, + Substitute.For()); + + static void Run(ReplaceCertificateCommand command, params string[] args) + => command.Start(args, Substitute.For(), new OptionSet()); + + class FakeOctopus + { + readonly IOctopusAsyncRepository repository = Substitute.For(); + + public FakeOctopus(string serverThumbprint) + { + var certificateConfiguration = Substitute.For(); + certificateConfiguration.GetOctopusCertificate().Returns(Task.FromResult(new CertificateConfigurationResource { Thumbprint = serverThumbprint })); + repository.CertificateConfiguration.Returns(certificateConfiguration); + + var client = Substitute.For(); + client.Repository.Returns(repository); + client.ForSystem().Returns(repository); + ClientInitializer.CreateClient(Arg.Any(), Arg.Any()).Returns(Task.FromResult(client)); + } + + public IOctopusClientInitializer ClientInitializer { get; } = Substitute.For(); + + public FakeOctopus WithWorker(WorkerResource worker) + { + repository.Workers.FindByName(worker.Name, Arg.Any()).Returns(Task.FromResult(worker)); + return this; + } + + public FakeOctopus WithMachine(MachineResource machine) + { + repository.Machines.FindByName(machine.Name, Arg.Any()).Returns(Task.FromResult(machine)); + return this; + } } } } diff --git a/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs new file mode 100644 index 000000000..6d57f5b09 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs @@ -0,0 +1,54 @@ +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 + { + 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, ""); + 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(); + } +} From addd71e4220127da2eb541fddc7ee8842789a1e5 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 19 Nov 2026 16:30:25 +1100 Subject: [PATCH 04/12] Mark arrange, act and assert in the replace-certificate tests --- .../Commands/ReplaceCertificateCommandFixture.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index 41662a228..4b57bca5a 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -27,19 +27,21 @@ public class ReplaceCertificateCommandFixture [Test] public void ShouldOnlyChangeTheThumbprintOfAPollingWorkerAndTrustTheServer() { + // Arrange using var tentacle = new TentacleConfigurationBuilder().Build(); var worker = PollingWorker("MyWorker", "poll://abc123/", "WorkerPools-1"); var octopus = new FakeOctopus(ServerThumbprint).WithWorker(worker); + // Act Run(CreateCommand(tentacle, octopus), "--server=http://octopus.test", "--apiKey=API-KEY", "--name=MyWorker"); + // Assert var endpoint = (PollingTentacleEndpointResource)worker.Endpoint; var newThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint; newThumbprint.Should().NotBe("OLD"); endpoint.Thumbprint.Should().Be(newThumbprint); endpoint.Uri.Should().Be("poll://abc123/"); worker.WorkerPoolIds.Should().Contain("WorkerPools-1"); - var server = tentacle.Configuration.TrustedOctopusServers.Should().ContainSingle().Subject; server.Thumbprint.Should().Be(ServerThumbprint); server.CommunicationStyle.Should().Be(CommunicationStyle.TentacleActive); @@ -50,13 +52,16 @@ public void ShouldOnlyChangeTheThumbprintOfAPollingWorkerAndTrustTheServer() [Test] public void ShouldRefuseAnAmbiguousNameRatherThanGuessBetweenATargetAndAWorker() { + // Arrange using var tentacle = new TentacleConfigurationBuilder().Build(); var octopus = new FakeOctopus(ServerThumbprint) .WithMachine(new MachineResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() }) .WithWorker(new WorkerResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() }); + // Act Action run = () => Run(CreateCommand(tentacle, octopus), "--server=http://octopus.test", "--apiKey=API-KEY", "--name=Shared"); + // Assert run.Should().Throw().WithMessage("*--id*"); tentacle.Configuration.TentacleCertificate.Should().BeNull(); } From e5acf4accecc3fc4ada76b39898e7cd87144c4fe Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 19 Nov 2026 16:31:06 +1100 Subject: [PATCH 05/12] Name the polling test after the subscription it protects --- .../Commands/ReplaceCertificateCommandFixture.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index 4b57bca5a..f63be9c36 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -25,7 +25,7 @@ public class ReplaceCertificateCommandFixture const string ServerThumbprint = "SERVERTHUMBPRINT"; [Test] - public void ShouldOnlyChangeTheThumbprintOfAPollingWorkerAndTrustTheServer() + public void ShouldGiveAPollingWorkerANewThumbprintAndKeepItsSubscription() { // Arrange using var tentacle = new TentacleConfigurationBuilder().Build(); From 217dfc7ad58c1806d40230cd7f06a63f90da4106 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 19 Nov 2026 16:33:14 +1100 Subject: [PATCH 06/12] Split replace-certificate tests into one behaviour each --- .../ReplaceCertificateCommandFixture.cs | 58 ++++++++++++++----- 1 file changed, 44 insertions(+), 14 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index f63be9c36..8dd474946 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -25,28 +25,54 @@ public class ReplaceCertificateCommandFixture const string ServerThumbprint = "SERVERTHUMBPRINT"; [Test] - public void ShouldGiveAPollingWorkerANewThumbprintAndKeepItsSubscription() + public void ShouldSaveTheNewThumbprintOnTheWorkerFoundByName() { // Arrange using var tentacle = new TentacleConfigurationBuilder().Build(); - var worker = PollingWorker("MyWorker", "poll://abc123/", "WorkerPools-1"); + var worker = PollingWorker("MyWorker", "poll://abc123/"); var octopus = new FakeOctopus(ServerThumbprint).WithWorker(worker); // Act - Run(CreateCommand(tentacle, octopus), "--server=http://octopus.test", "--apiKey=API-KEY", "--name=MyWorker"); + ReplaceCertificate(tentacle, octopus, "MyWorker"); // Assert - var endpoint = (PollingTentacleEndpointResource)worker.Endpoint; var newThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint; newThumbprint.Should().NotBe("OLD"); - endpoint.Thumbprint.Should().Be(newThumbprint); - endpoint.Uri.Should().Be("poll://abc123/"); - worker.WorkerPoolIds.Should().Contain("WorkerPools-1"); + worker.Endpoint.Should().BeOfType().Which.Thumbprint.Should().Be(newThumbprint); + octopus.Workers.Received().Modify(worker, Arg.Any()); + } + + [Test] + public void WhenPollingTheSubscriptionIdDoesNotChange() + { + // Arrange + using var tentacle = new TentacleConfigurationBuilder().Build(); + var worker = PollingWorker("MyWorker", "poll://abc123/"); + var octopus = new FakeOctopus(ServerThumbprint).WithWorker(worker); + + // Act + ReplaceCertificate(tentacle, octopus, "MyWorker"); + + // Assert + ((PollingTentacleEndpointResource)worker.Endpoint).Uri.Should().Be("poll://abc123/"); + tentacle.Configuration.TrustedOctopusServers.Should().ContainSingle().Which.SubscriptionId.Should().Be("poll://abc123/"); + } + + [Test] + public void WhenPollingTheServerIsTrustedAtItsCommsAddress() + { + // Arrange + using var tentacle = new TentacleConfigurationBuilder().Build(); + var octopus = new FakeOctopus(ServerThumbprint).WithWorker(PollingWorker("MyWorker", "poll://abc123/")); + + // Act + ReplaceCertificate(tentacle, octopus, "MyWorker"); + + // Assert var server = tentacle.Configuration.TrustedOctopusServers.Should().ContainSingle().Subject; server.Thumbprint.Should().Be(ServerThumbprint); server.CommunicationStyle.Should().Be(CommunicationStyle.TentacleActive); server.Address.Should().Be(new Uri("https://octopus.test:10943")); - server.SubscriptionId.Should().Be("poll://abc123/"); } [Test] @@ -59,20 +85,19 @@ public void ShouldRefuseAnAmbiguousNameRatherThanGuessBetweenATargetAndAWorker() .WithWorker(new WorkerResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() }); // Act - Action run = () => Run(CreateCommand(tentacle, octopus), "--server=http://octopus.test", "--apiKey=API-KEY", "--name=Shared"); + Action run = () => ReplaceCertificate(tentacle, octopus, "Shared"); // Assert run.Should().Throw().WithMessage("*--id*"); tentacle.Configuration.TentacleCertificate.Should().BeNull(); } - static WorkerResource PollingWorker(string name, string subscription, string pool) + static WorkerResource PollingWorker(string name, string subscription) => new() { Id = "Workers-1", Name = name, - Endpoint = new PollingTentacleEndpointResource { Uri = subscription, Thumbprint = "OLD" }, - WorkerPoolIds = new ReferenceCollection(pool) + Endpoint = new PollingTentacleEndpointResource { Uri = subscription, Thumbprint = "OLD" } }; static ReplaceCertificateCommand CreateCommand(TemporaryTentacleConfiguration tentacle, FakeOctopus octopus) @@ -84,8 +109,11 @@ static ReplaceCertificateCommand CreateCommand(TemporaryTentacleConfiguration te tentacle.Selector, Substitute.For()); - static void Run(ReplaceCertificateCommand command, params string[] args) - => command.Start(args, Substitute.For(), new OptionSet()); + static void ReplaceCertificate(TemporaryTentacleConfiguration tentacle, FakeOctopus octopus, string name) + => CreateCommand(tentacle, octopus).Start( + new[] { "--server=http://octopus.test", "--apiKey=API-KEY", $"--name={name}" }, + Substitute.For(), + new OptionSet()); class FakeOctopus { @@ -105,6 +133,8 @@ public FakeOctopus(string serverThumbprint) public IOctopusClientInitializer ClientInitializer { get; } = Substitute.For(); + public IWorkerRepository Workers => repository.Workers; + public FakeOctopus WithWorker(WorkerResource worker) { repository.Workers.FindByName(worker.Name, Arg.Any()).Returns(Task.FromResult(worker)); From bc8a84f7c6ccc3d6dd5237f801d7b022316ab267 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 19 Nov 2026 16:36:55 +1100 Subject: [PATCH 07/12] Keep the existing trust in replace-certificate instead of rewriting it --- .../ReplaceCertificateCommandFixture.cs | 33 +++---------------- .../Commands/ReplaceCertificateCommand.cs | 31 ++--------------- 2 files changed, 6 insertions(+), 58 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index 8dd474946..5fee97d0e 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -22,15 +22,13 @@ namespace Octopus.Tentacle.Tests.Commands [TestFixture] public class ReplaceCertificateCommandFixture { - const string ServerThumbprint = "SERVERTHUMBPRINT"; - [Test] public void ShouldSaveTheNewThumbprintOnTheWorkerFoundByName() { // Arrange using var tentacle = new TentacleConfigurationBuilder().Build(); var worker = PollingWorker("MyWorker", "poll://abc123/"); - var octopus = new FakeOctopus(ServerThumbprint).WithWorker(worker); + var octopus = new FakeOctopus().WithWorker(worker); // Act ReplaceCertificate(tentacle, octopus, "MyWorker"); @@ -48,31 +46,13 @@ public void WhenPollingTheSubscriptionIdDoesNotChange() // Arrange using var tentacle = new TentacleConfigurationBuilder().Build(); var worker = PollingWorker("MyWorker", "poll://abc123/"); - var octopus = new FakeOctopus(ServerThumbprint).WithWorker(worker); + var octopus = new FakeOctopus().WithWorker(worker); // Act ReplaceCertificate(tentacle, octopus, "MyWorker"); // Assert ((PollingTentacleEndpointResource)worker.Endpoint).Uri.Should().Be("poll://abc123/"); - tentacle.Configuration.TrustedOctopusServers.Should().ContainSingle().Which.SubscriptionId.Should().Be("poll://abc123/"); - } - - [Test] - public void WhenPollingTheServerIsTrustedAtItsCommsAddress() - { - // Arrange - using var tentacle = new TentacleConfigurationBuilder().Build(); - var octopus = new FakeOctopus(ServerThumbprint).WithWorker(PollingWorker("MyWorker", "poll://abc123/")); - - // Act - ReplaceCertificate(tentacle, octopus, "MyWorker"); - - // Assert - var server = tentacle.Configuration.TrustedOctopusServers.Should().ContainSingle().Subject; - server.Thumbprint.Should().Be(ServerThumbprint); - server.CommunicationStyle.Should().Be(CommunicationStyle.TentacleActive); - server.Address.Should().Be(new Uri("https://octopus.test:10943")); } [Test] @@ -80,7 +60,7 @@ public void ShouldRefuseAnAmbiguousNameRatherThanGuessBetweenATargetAndAWorker() { // Arrange using var tentacle = new TentacleConfigurationBuilder().Build(); - var octopus = new FakeOctopus(ServerThumbprint) + var octopus = new FakeOctopus() .WithMachine(new MachineResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() }) .WithWorker(new WorkerResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() }); @@ -119,15 +99,10 @@ class FakeOctopus { readonly IOctopusAsyncRepository repository = Substitute.For(); - public FakeOctopus(string serverThumbprint) + public FakeOctopus() { - var certificateConfiguration = Substitute.For(); - certificateConfiguration.GetOctopusCertificate().Returns(Task.FromResult(new CertificateConfigurationResource { Thumbprint = serverThumbprint })); - repository.CertificateConfiguration.Returns(certificateConfiguration); - var client = Substitute.For(); client.Repository.Returns(repository); - client.ForSystem().Returns(repository); ClientInitializer.CreateClient(Arg.Any(), Arg.Any()).Returns(Task.FromResult(client)); } diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs index caed425ae..596419241 100644 --- a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -15,8 +15,6 @@ namespace Octopus.Tentacle.Commands { public class ReplaceCertificateCommand : AbstractStandardCommand { - const int DefaultServerCommsPort = 10943; - readonly Lazy configuration; readonly IOctopusClientInitializer octopusClientInitializer; readonly ISpaceRepositoryFactory spaceRepositoryFactory; @@ -25,8 +23,6 @@ public class ReplaceCertificateCommand : AbstractStandardCommand string name = null!; string id = null!; string spaceName = null!; - string serverCommsAddress = null!; - int? serverCommsPort; public ReplaceCertificateCommand( Lazy configuration, @@ -46,8 +42,6 @@ public ReplaceCertificateCommand( Options.Add("name=", "The name of the existing deployment target or worker in Octopus", s => name = s); Options.Add("id=", "The ID of the existing deployment target or worker in Octopus, e.g. Machines-1 or Workers-1", s => id = s); Options.Add("space=", "The name of the space the deployment target or worker is in. The default space will be used if omitted.", s => spaceName = s); - Options.Add("server-comms-address=", "For a polling Tentacle, the comms address on the Octopus Server; the address of the Octopus Server will be used if omitted.", s => serverCommsAddress = s); - Options.Add("server-comms-port=", "For a polling Tentacle, the comms port on the Octopus Server; the default is " + DefaultServerCommsPort + ". If specified, this will take precedence over any port number in server-comms-address.", s => serverCommsPort = int.Parse(s)); } protected override void Start() @@ -65,20 +59,8 @@ async Task StartAsync() var repository = await spaceRepositoryFactory.CreateSpaceRepository(client, spaceName); var machine = await FindMachine(repository); - var server = new OctopusServerConfiguration((await client.ForSystem().CertificateConfiguration.GetOctopusCertificate()).Thumbprint); - switch (machine.Endpoint) - { - case ListeningTentacleEndpointResource: - server.CommunicationStyle = CommunicationStyle.TentaclePassive; - break; - case PollingTentacleEndpointResource polling: - server.CommunicationStyle = CommunicationStyle.TentacleActive; - server.Address = GetPollingServerAddress(); - server.SubscriptionId = polling.Uri; - break; - default: - throw new ControlledFailureException($"'{machine.Name}' uses a {machine.Endpoint.CommunicationStyle} endpoint. Only listening and polling Tentacles can have their certificate replaced."); - } + if (machine.Endpoint is not (ListeningTentacleEndpointResource or PollingTentacleEndpointResource)) + throw new ControlledFailureException($"'{machine.Name}' uses a {machine.Endpoint.CommunicationStyle} endpoint. Only listening and polling Tentacles can have their certificate replaced."); var certificate = configuration.Value.GenerateNewCertificate(); log.Info($"Generated a new certificate with thumbprint {certificate.Thumbprint}"); @@ -86,8 +68,6 @@ async Task StartAsync() ((TentacleEndpointResource)machine.Endpoint).Thumbprint = certificate.Thumbprint; await Modify(repository, machine); log.Info($"Updated '{machine.Name}' ({machine.Id}) in Octopus to trust the new certificate"); - - configuration.Value.AddOrUpdateTrustedOctopusServer(server); VoteForRestart(); } @@ -114,12 +94,5 @@ static Task Modify(IOctopusSpaceAsyncRepository repository, MachineBasedResource => machine is WorkerResource worker ? repository.Workers.Modify(worker, CancellationToken.None) : repository.Machines.Modify((MachineResource)machine, CancellationToken.None); - - Uri GetPollingServerAddress() - { - var address = string.IsNullOrEmpty(serverCommsAddress) ? api.ServerUri : new Uri(serverCommsAddress); - var port = serverCommsPort ?? (string.IsNullOrEmpty(serverCommsAddress) ? DefaultServerCommsPort : address.Port); - return new Uri($"https://{address.Host}:{port}"); - } } } From 61d5d5cb6675d9e3d515141fd5c0df454f095273 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 19 Nov 2026 16:40:09 +1100 Subject: [PATCH 08/12] Test finding the worker by id --- .../ReplaceCertificateCommandFixture.cs | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index 5fee97d0e..12324e61f 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -31,7 +31,7 @@ public void ShouldSaveTheNewThumbprintOnTheWorkerFoundByName() var octopus = new FakeOctopus().WithWorker(worker); // Act - ReplaceCertificate(tentacle, octopus, "MyWorker"); + ReplaceCertificate(tentacle, octopus, "--name=MyWorker"); // Assert var newThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint; @@ -40,6 +40,22 @@ public void ShouldSaveTheNewThumbprintOnTheWorkerFoundByName() octopus.Workers.Received().Modify(worker, Arg.Any()); } + [Test] + public void ShouldSaveTheNewThumbprintOnTheWorkerFoundById() + { + // Arrange + using var tentacle = new TentacleConfigurationBuilder().Build(); + var worker = PollingWorker("MyWorker", "poll://abc123/"); + var octopus = new FakeOctopus().WithWorker(worker); + + // Act + ReplaceCertificate(tentacle, octopus, "--id=Workers-1"); + + // Assert + ((PollingTentacleEndpointResource)worker.Endpoint).Thumbprint.Should().Be(tentacle.Configuration.TentacleCertificate!.Thumbprint); + octopus.Workers.Received().Modify(worker, Arg.Any()); + } + [Test] public void WhenPollingTheSubscriptionIdDoesNotChange() { @@ -49,7 +65,7 @@ public void WhenPollingTheSubscriptionIdDoesNotChange() var octopus = new FakeOctopus().WithWorker(worker); // Act - ReplaceCertificate(tentacle, octopus, "MyWorker"); + ReplaceCertificate(tentacle, octopus, "--name=MyWorker"); // Assert ((PollingTentacleEndpointResource)worker.Endpoint).Uri.Should().Be("poll://abc123/"); @@ -65,7 +81,7 @@ public void ShouldRefuseAnAmbiguousNameRatherThanGuessBetweenATargetAndAWorker() .WithWorker(new WorkerResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() }); // Act - Action run = () => ReplaceCertificate(tentacle, octopus, "Shared"); + Action run = () => ReplaceCertificate(tentacle, octopus, "--name=Shared"); // Assert run.Should().Throw().WithMessage("*--id*"); @@ -89,9 +105,9 @@ static ReplaceCertificateCommand CreateCommand(TemporaryTentacleConfiguration te tentacle.Selector, Substitute.For()); - static void ReplaceCertificate(TemporaryTentacleConfiguration tentacle, FakeOctopus octopus, string name) + static void ReplaceCertificate(TemporaryTentacleConfiguration tentacle, FakeOctopus octopus, string machineSelector) => CreateCommand(tentacle, octopus).Start( - new[] { "--server=http://octopus.test", "--apiKey=API-KEY", $"--name={name}" }, + new[] { "--server=http://octopus.test", "--apiKey=API-KEY", machineSelector }, Substitute.For(), new OptionSet()); @@ -113,6 +129,7 @@ public FakeOctopus() public FakeOctopus WithWorker(WorkerResource worker) { repository.Workers.FindByName(worker.Name, Arg.Any()).Returns(Task.FromResult(worker)); + repository.Workers.Get(worker.Id, Arg.Any()).Returns(Task.FromResult(worker)); return this; } From 63d73bb52fef6b710fd932475d8c893a296699b8 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 19 Nov 2026 16:42:45 +1100 Subject: [PATCH 09/12] Look up --id in both targets and workers --- .../Commands/ReplaceCertificateCommand.cs | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs index 596419241..a53bf646f 100644 --- a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -3,6 +3,7 @@ using System.Threading; using System.Threading.Tasks; using Octopus.Client; +using Octopus.Client.Exceptions; using Octopus.Client.Model; using Octopus.Client.Model.Endpoints; using Octopus.Tentacle.Commands.OptionSets; @@ -73,23 +74,32 @@ async Task StartAsync() async Task FindMachine(IOctopusSpaceAsyncRepository repository) { - if (!string.IsNullOrWhiteSpace(id)) - return id.StartsWith("Workers-", StringComparison.OrdinalIgnoreCase) - ? await repository.Workers.Get(id, CancellationToken.None) - : await repository.Machines.Get(id, CancellationToken.None); - - var matches = new MachineBasedResource?[] { await repository.Machines.FindByName(name, CancellationToken.None), await repository.Workers.FindByName(name, CancellationToken.None) } + var matches = (string.IsNullOrWhiteSpace(id) + ? new MachineBasedResource?[] { await repository.Machines.FindByName(name, CancellationToken.None), await repository.Workers.FindByName(name, CancellationToken.None) } + : new MachineBasedResource?[] { await GetOrNull(() => repository.Machines.Get(id, CancellationToken.None)), await GetOrNull(() => repository.Workers.Get(id, CancellationToken.None)) }) .OfType() .ToArray(); return matches.Length switch { - 0 => throw new ControlledFailureException($"No deployment target or worker named '{name}' was found."), + 0 => throw new ControlledFailureException($"No deployment target or worker '{name ?? id}' was found."), 1 => matches[0], - _ => throw new ControlledFailureException($"Both a deployment target and a worker are named '{name}'. Please specify which one with --id.") + _ => throw new ControlledFailureException($"Both a deployment target and a worker match '{name ?? id}'. Please specify which one with --id.") }; } + static async Task GetOrNull(Func> get) where T : class + { + try + { + return await get(); + } + catch (OctopusResourceNotFoundException) + { + return null; + } + } + static Task Modify(IOctopusSpaceAsyncRepository repository, MachineBasedResource machine) => machine is WorkerResource worker ? repository.Workers.Modify(worker, CancellationToken.None) From e5edf0953c1fc4d3b687ffeae30e00d6a73c3309 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Fri, 20 Nov 2026 13:50:57 +1100 Subject: [PATCH 10/12] replace-certificate: update every registration with the old thumbprint in all spaces Finds targets and workers by the plaintext thumbprint instead of --name/--id, uses the polling proxy like deregister-from, and saves the new certificate before updating Octopus. --old-thumbprint finishes a run that failed part way through. --- .../ReplaceCertificateCommandFixture.cs | 159 ++++++++++-------- .../Commands/StubTentacleConfiguration.cs | 1 + .../Support/TentacleConfigurationBuilder.cs | 10 +- .../Commands/ReplaceCertificateCommand.cs | 92 +++++----- .../Configuration/ITentacleConfiguration.cs | 5 + .../Configuration/TentacleConfiguration.cs | 2 + source/Octopus.Tentacle/Program.cs | 2 +- 7 files changed, 156 insertions(+), 115 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index 12324e61f..f838e876f 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -1,13 +1,16 @@ 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.Client.Repositories.Async; +using Octopus.Tentacle.Certificates; using Octopus.Tentacle.Commands; using Octopus.Tentacle.Commands.OptionSets; using Octopus.Tentacle.Configuration; @@ -23,119 +26,137 @@ namespace Octopus.Tentacle.Tests.Commands public class ReplaceCertificateCommandFixture { [Test] - public void ShouldSaveTheNewThumbprintOnTheWorkerFoundByName() + public void ShouldUpdateEveryRegistrationWithTheOldThumbprintInEverySpace() { // Arrange - using var tentacle = new TentacleConfigurationBuilder().Build(); - var worker = PollingWorker("MyWorker", "poll://abc123/"); - var octopus = new FakeOctopus().WithWorker(worker); + 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, "--name=MyWorker"); + ReplaceCertificate(tentacle, octopus); // Assert var newThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint; newThumbprint.Should().NotBe("OLD"); - worker.Endpoint.Should().BeOfType().Which.Thumbprint.Should().Be(newThumbprint); - octopus.Workers.Received().Modify(worker, Arg.Any()); + ((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 ShouldSaveTheNewThumbprintOnTheWorkerFoundById() + public void WhenAnUpdateFailsRerunningWithTheOldThumbprintFinishesWithTheSameCertificate() { // Arrange - using var tentacle = new TentacleConfigurationBuilder().Build(); - var worker = PollingWorker("MyWorker", "poll://abc123/"); - var octopus = new FakeOctopus().WithWorker(worker); + 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, "--id=Workers-1"); + ReplaceCertificate(tentacle, octopus, "--old-thumbprint=OLD"); // Assert - ((PollingTentacleEndpointResource)worker.Endpoint).Thumbprint.Should().Be(tentacle.Configuration.TentacleCertificate!.Thumbprint); - octopus.Workers.Received().Modify(worker, Arg.Any()); + tentacle.Configuration.TentacleCertificate!.Thumbprint.Should().Be(savedThumbprint); + ((TentacleEndpointResource)first.Endpoint).Thumbprint.Should().Be(savedThumbprint); + ((TentacleEndpointResource)second.Endpoint).Thumbprint.Should().Be(savedThumbprint); } [Test] - public void WhenPollingTheSubscriptionIdDoesNotChange() + public void WhenNothingMatchesTheCertificateIsNotReplaced() { // Arrange - using var tentacle = new TentacleConfigurationBuilder().Build(); - var worker = PollingWorker("MyWorker", "poll://abc123/"); - var octopus = new FakeOctopus().WithWorker(worker); + using var tentacle = new TentacleConfigurationBuilder().WithCertificateThumbprint("OLD").Build(); + var octopus = new FakeOctopus(); + octopus.Space("Spaces-1"); // Act - ReplaceCertificate(tentacle, octopus, "--name=MyWorker"); + Action run = () => ReplaceCertificate(tentacle, octopus); // Assert - ((PollingTentacleEndpointResource)worker.Endpoint).Uri.Should().Be("poll://abc123/"); + run.Should().Throw().WithMessage("*OLD*"); + tentacle.Configuration.TentacleCertificateThumbprint.Should().Be("OLD"); } - [Test] - public void ShouldRefuseAnAmbiguousNameRatherThanGuessBetweenATargetAndAWorker() + 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 { - // Arrange - using var tentacle = new TentacleConfigurationBuilder().Build(); - var octopus = new FakeOctopus() - .WithMachine(new MachineResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() }) - .WithWorker(new WorkerResource { Name = "Shared", Endpoint = new ListeningTentacleEndpointResource() }); + readonly IOctopusAsyncClient client = Substitute.For(); + readonly List spaces = new(); - // Act - Action run = () => ReplaceCertificate(tentacle, octopus, "--name=Shared"); + 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); + } - // Assert - run.Should().Throw().WithMessage("*--id*"); - tentacle.Configuration.TentacleCertificate.Should().BeNull(); - } + public IOctopusClientInitializer ClientInitializer { get; } = Substitute.For(); - static WorkerResource PollingWorker(string name, string subscription) - => new() + public FakeSpace Space(string id) { - Id = "Workers-1", - Name = name, - Endpoint = new PollingTentacleEndpointResource { Uri = subscription, Thumbprint = "OLD" } - }; - - static ReplaceCertificateCommand CreateCommand(TemporaryTentacleConfiguration tentacle, FakeOctopus octopus) - => new( - new Lazy(() => tentacle.Configuration), - octopus.ClientInitializer, - new SpaceRepositoryFactory(), - Substitute.For(), - tentacle.Selector, - Substitute.For()); - - static void ReplaceCertificate(TemporaryTentacleConfiguration tentacle, FakeOctopus octopus, string machineSelector) - => CreateCommand(tentacle, octopus).Start( - new[] { "--server=http://octopus.test", "--apiKey=API-KEY", machineSelector }, - Substitute.For(), - new OptionSet()); + var space = new SpaceResource { Id = id }; + spaces.Add(space); + var repository = Substitute.For(); + client.ForSpace(space).Returns(repository); + return new FakeSpace(repository); + } + } - class FakeOctopus + class FakeSpace { - readonly IOctopusAsyncRepository repository = Substitute.For(); + readonly IOctopusSpaceAsyncRepository repository; + readonly List machines = new(); + readonly List workers = new(); - public FakeOctopus() + public FakeSpace(IOctopusSpaceAsyncRepository repository) { - var client = Substitute.For(); - client.Repository.Returns(repository); - ClientInitializer.CreateClient(Arg.Any(), Arg.Any()).Returns(Task.FromResult(client)); + 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 IOctopusClientInitializer ClientInitializer { get; } = Substitute.For(); - - public IWorkerRepository Workers => repository.Workers; + public Octopus.Client.Repositories.Async.IMachineRepository Machines => repository.Machines; + public Octopus.Client.Repositories.Async.IWorkerRepository Workers => repository.Workers; - public FakeOctopus WithWorker(WorkerResource worker) + public FakeSpace WithMachine(MachineResource machine) { - repository.Workers.FindByName(worker.Name, Arg.Any()).Returns(Task.FromResult(worker)); - repository.Workers.Get(worker.Id, Arg.Any()).Returns(Task.FromResult(worker)); + machines.Add(machine); return this; } - public FakeOctopus WithMachine(MachineResource machine) + public FakeSpace WithWorker(WorkerResource worker) { - repository.Machines.FindByName(machine.Name, Arg.Any()).Returns(Task.FromResult(machine)); + 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 index 6d57f5b09..c4c93919c 100644 --- a/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs +++ b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs @@ -12,12 +12,20 @@ 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, ""); + File.WriteAllText(configFile, $"{settings}"); var store = new XmlFileKeyValueStore(fileSystem, configFile); var selector = Substitute.For(); diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs index a53bf646f..74583b3b4 100644 --- a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -1,15 +1,17 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Octopus.Client; -using Octopus.Client.Exceptions; 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 @@ -17,32 +19,31 @@ namespace Octopus.Tentacle.Commands public class ReplaceCertificateCommand : AbstractStandardCommand { readonly Lazy configuration; + readonly Lazy certificateGenerator; readonly IOctopusClientInitializer octopusClientInitializer; - readonly ISpaceRepositoryFactory spaceRepositoryFactory; + readonly IProxyConfigParser proxyConfig; readonly ISystemLog log; readonly ApiEndpointOptions api; - string name = null!; - string id = null!; - string spaceName = null!; + string oldThumbprintOption = null!; public ReplaceCertificateCommand( Lazy configuration, + Lazy certificateGenerator, IOctopusClientInitializer octopusClientInitializer, - ISpaceRepositoryFactory spaceRepositoryFactory, + IProxyConfigParser proxyConfig, ISystemLog log, IApplicationInstanceSelector selector, ILogFileOnlyLogger logFileOnlyLogger) : base(selector, log, logFileOnlyLogger) { this.configuration = configuration; + this.certificateGenerator = certificateGenerator; this.octopusClientInitializer = octopusClientInitializer; - this.spaceRepositoryFactory = spaceRepositoryFactory; + this.proxyConfig = proxyConfig; this.log = log; api = AddOptionSet(new ApiEndpointOptions(Options)); - Options.Add("name=", "The name of the existing deployment target or worker in Octopus", s => name = s); - Options.Add("id=", "The ID of the existing deployment target or worker in Octopus, e.g. Machines-1 or Workers-1", s => id = s); - Options.Add("space=", "The name of the space the deployment target or worker is in. The default space will be used if omitted.", s => spaceName = s); + Options.Add("old-thumbprint=", "Finish a replacement that failed part way through: updates the deployment targets and workers still using this thumbprint to trust the certificate already saved, without creating another.", s => oldThumbprintOption = s); } protected override void Start() @@ -53,51 +54,54 @@ protected override void Start() async Task StartAsync() { - if (string.IsNullOrWhiteSpace(name) == string.IsNullOrWhiteSpace(id)) - throw new ControlledFailureException("Please specify either --name or --id of the existing deployment target or worker."); + var config = configuration.Value; + var resuming = !string.IsNullOrWhiteSpace(oldThumbprintOption); + var oldThumbprint = resuming ? oldThumbprintOption : config.TentacleCertificateThumbprint; + if (string.IsNullOrWhiteSpace(oldThumbprint)) + { + throw new ControlledFailureException("This Tentacle has no certificate thumbprint in its configuration. Please pass the thumbprint Octopus has for it with --old-thumbprint."); + } - using var client = await octopusClientInitializer.CreateClient(api, configuration.Value.ProxyConfiguration.UseDefaultProxy); - var repository = await spaceRepositoryFactory.CreateSpaceRepository(client, spaceName); + 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."); + } - var machine = await FindMachine(repository); - if (machine.Endpoint is not (ListeningTentacleEndpointResource or PollingTentacleEndpointResource)) - throw new ControlledFailureException($"'{machine.Name}' uses a {machine.Endpoint.CommunicationStyle} endpoint. Only listening and polling Tentacles can have their certificate replaced."); + if (!resuming) + { + var certificate = certificateGenerator.Value.GenerateNew(CertificateExpectations.TentacleCertificateFullName); + config.ImportCertificate(certificate); + log.Info($"Replaced certificate {oldThumbprint} with {certificate.Thumbprint}. If updating Octopus fails, re-run this command with --old-thumbprint {oldThumbprint}"); + } - var certificate = configuration.Value.GenerateNewCertificate(); - log.Info($"Generated a new certificate with thumbprint {certificate.Thumbprint}"); + 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"); + } - ((TentacleEndpointResource)machine.Endpoint).Thumbprint = certificate.Thumbprint; - await Modify(repository, machine); - log.Info($"Updated '{machine.Name}' ({machine.Id}) in Octopus to trust the new certificate"); VoteForRestart(); } - async Task FindMachine(IOctopusSpaceAsyncRepository repository) + static async Task> FindRegistrations(IOctopusAsyncClient client, string thumbprint) { - var matches = (string.IsNullOrWhiteSpace(id) - ? new MachineBasedResource?[] { await repository.Machines.FindByName(name, CancellationToken.None), await repository.Workers.FindByName(name, CancellationToken.None) } - : new MachineBasedResource?[] { await GetOrNull(() => repository.Machines.Get(id, CancellationToken.None)), await GetOrNull(() => repository.Workers.Get(id, CancellationToken.None)) }) - .OfType() - .ToArray(); + var users = client.ForSystem().Users; + var spaces = await users.GetSpaces(await users.GetCurrent()); - return matches.Length switch + var registrations = new List<(IOctopusSpaceAsyncRepository, MachineBasedResource)>(); + foreach (var space in spaces) { - 0 => throw new ControlledFailureException($"No deployment target or worker '{name ?? id}' was found."), - 1 => matches[0], - _ => throw new ControlledFailureException($"Both a deployment target and a worker match '{name ?? id}'. Please specify which one with --id.") - }; - } - - static async Task GetOrNull(Func> get) where T : class - { - try - { - return await get(); - } - catch (OctopusResourceNotFoundException) - { - return null; + 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) 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 8f89239bb..f4c4d5f50 100644 --- a/source/Octopus.Tentacle/Program.cs +++ b/source/Octopus.Tentacle/Program.cs @@ -86,7 +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 its existing deployment target or worker in Octopus to trust it"); + 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"); From 97e163027f633e39f983a4129d8086e1741bd4f5 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Fri, 20 Nov 2026 13:58:16 +1100 Subject: [PATCH 11/12] Rename --old-thumbprint to --keep-certificate-and-update-thumbprint and refuse to run without a current certificate --- .../Commands/ReplaceCertificateCommandFixture.cs | 4 ++-- .../Commands/ReplaceCertificateCommand.cs | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index f838e876f..2176e12b2 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -50,7 +50,7 @@ public void ShouldUpdateEveryRegistrationWithTheOldThumbprintInEverySpace() } [Test] - public void WhenAnUpdateFailsRerunningWithTheOldThumbprintFinishesWithTheSameCertificate() + public void WhenAnUpdateFailsRerunningWithKeepCertificateFinishesWithTheSameCertificate() { // Arrange using var tentacle = new TentacleConfigurationBuilder().WithCertificateThumbprint("OLD").Build(); @@ -72,7 +72,7 @@ public void WhenAnUpdateFailsRerunningWithTheOldThumbprintFinishesWithTheSameCer var savedThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint; // Act - ReplaceCertificate(tentacle, octopus, "--old-thumbprint=OLD"); + ReplaceCertificate(tentacle, octopus, "--keep-certificate-and-update-thumbprint=OLD"); // Assert tentacle.Configuration.TentacleCertificate!.Thumbprint.Should().Be(savedThumbprint); diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs index 74583b3b4..1cae41f4f 100644 --- a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -24,7 +24,7 @@ public class ReplaceCertificateCommand : AbstractStandardCommand readonly IProxyConfigParser proxyConfig; readonly ISystemLog log; readonly ApiEndpointOptions api; - string oldThumbprintOption = null!; + string keepCertificateAndUpdateThumbprint = null!; public ReplaceCertificateCommand( Lazy configuration, @@ -43,7 +43,7 @@ public ReplaceCertificateCommand( this.log = log; api = AddOptionSet(new ApiEndpointOptions(Options)); - Options.Add("old-thumbprint=", "Finish a replacement that failed part way through: updates the deployment targets and workers still using this thumbprint to trust the certificate already saved, without creating another.", s => oldThumbprintOption = s); + Options.Add("keep-certificate-and-update-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. Only needed if a previous run did not complete; that run prints the exact thumbprint to pass.", s => keepCertificateAndUpdateThumbprint = s); } protected override void Start() @@ -55,11 +55,11 @@ protected override void Start() async Task StartAsync() { var config = configuration.Value; - var resuming = !string.IsNullOrWhiteSpace(oldThumbprintOption); - var oldThumbprint = resuming ? oldThumbprintOption : config.TentacleCertificateThumbprint; - if (string.IsNullOrWhiteSpace(oldThumbprint)) + var keepCurrentCertificate = !string.IsNullOrWhiteSpace(keepCertificateAndUpdateThumbprint); + var oldThumbprint = keepCurrentCertificate ? keepCertificateAndUpdateThumbprint : config.TentacleCertificateThumbprint; + if (string.IsNullOrWhiteSpace(oldThumbprint) || string.IsNullOrWhiteSpace(config.TentacleCertificateThumbprint)) { - throw new ControlledFailureException("This Tentacle has no certificate thumbprint in its configuration. Please pass the thumbprint Octopus has for it with --old-thumbprint."); + 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)); @@ -69,11 +69,11 @@ async Task StartAsync() throw new ControlledFailureException($"No deployment target or worker with thumbprint {oldThumbprint} was found in any space this API key can access."); } - if (!resuming) + if (!keepCurrentCertificate) { var certificate = certificateGenerator.Value.GenerateNew(CertificateExpectations.TentacleCertificateFullName); config.ImportCertificate(certificate); - log.Info($"Replaced certificate {oldThumbprint} with {certificate.Thumbprint}. If updating Octopus fails, re-run this command with --old-thumbprint {oldThumbprint}"); + log.Info($"Replaced certificate {oldThumbprint} with {certificate.Thumbprint}. If this does not complete, re-run this command with --keep-certificate-and-update-thumbprint {oldThumbprint}"); } foreach (var (repository, machine) in registrations) From 3cccacad86b28b94c27d7b918ea40f16272a7204 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Fri, 20 Nov 2026 13:59:48 +1100 Subject: [PATCH 12/12] Rename to --apply-current-cert-to-tentacles-with-thumbprint --- .../Commands/ReplaceCertificateCommandFixture.cs | 4 ++-- .../Commands/ReplaceCertificateCommand.cs | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index 2176e12b2..80720309d 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -50,7 +50,7 @@ public void ShouldUpdateEveryRegistrationWithTheOldThumbprintInEverySpace() } [Test] - public void WhenAnUpdateFailsRerunningWithKeepCertificateFinishesWithTheSameCertificate() + public void WhenAnUpdateFailsRerunningWithApplyCurrentCertFinishesWithTheSameCertificate() { // Arrange using var tentacle = new TentacleConfigurationBuilder().WithCertificateThumbprint("OLD").Build(); @@ -72,7 +72,7 @@ public void WhenAnUpdateFailsRerunningWithKeepCertificateFinishesWithTheSameCert var savedThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint; // Act - ReplaceCertificate(tentacle, octopus, "--keep-certificate-and-update-thumbprint=OLD"); + ReplaceCertificate(tentacle, octopus, "--apply-current-cert-to-tentacles-with-thumbprint=OLD"); // Assert tentacle.Configuration.TentacleCertificate!.Thumbprint.Should().Be(savedThumbprint); diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs index 1cae41f4f..768938a07 100644 --- a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -24,7 +24,7 @@ public class ReplaceCertificateCommand : AbstractStandardCommand readonly IProxyConfigParser proxyConfig; readonly ISystemLog log; readonly ApiEndpointOptions api; - string keepCertificateAndUpdateThumbprint = null!; + string applyCurrentCertToTentaclesWithThumbprint = null!; public ReplaceCertificateCommand( Lazy configuration, @@ -43,7 +43,7 @@ public ReplaceCertificateCommand( this.log = log; api = AddOptionSet(new ApiEndpointOptions(Options)); - Options.Add("keep-certificate-and-update-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. Only needed if a previous run did not complete; that run prints the exact thumbprint to pass.", s => keepCertificateAndUpdateThumbprint = s); + 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() @@ -55,8 +55,8 @@ protected override void Start() async Task StartAsync() { var config = configuration.Value; - var keepCurrentCertificate = !string.IsNullOrWhiteSpace(keepCertificateAndUpdateThumbprint); - var oldThumbprint = keepCurrentCertificate ? keepCertificateAndUpdateThumbprint : config.TentacleCertificateThumbprint; + 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."); @@ -73,7 +73,7 @@ async Task StartAsync() { 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 --keep-certificate-and-update-thumbprint {oldThumbprint}"); + 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)