Repository navigation
Add replace-certificate command #1355
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
cbdddee
d6b951e
8232297
addd71e
e5acf4a
217dfc7
bc8a84f
61d5d5c
63d73bb
e5edf09
97e1630
3cccaca
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using FluentAssertions; | ||
| using NSubstitute; | ||
| using NSubstitute.ExceptionExtensions; | ||
| using NUnit.Framework; | ||
| using Octopus.Client; | ||
| using Octopus.Client.Model; | ||
| using Octopus.Client.Model.Endpoints; | ||
| using Octopus.Tentacle.Certificates; | ||
| using Octopus.Tentacle.Commands; | ||
| using Octopus.Tentacle.Commands.OptionSets; | ||
| using Octopus.Tentacle.Configuration; | ||
| using Octopus.Tentacle.Core.Diagnostics; | ||
| using Octopus.Tentacle.Diagnostics; | ||
| using Octopus.Tentacle.Internals.Options; | ||
| using Octopus.Tentacle.Startup; | ||
| using Octopus.Tentacle.Tests.Support; | ||
|
|
||
| namespace Octopus.Tentacle.Tests.Commands | ||
| { | ||
| [TestFixture] | ||
| public class ReplaceCertificateCommandFixture | ||
| { | ||
| [Test] | ||
| public void ShouldUpdateEveryRegistrationWithTheOldThumbprintInEverySpace() | ||
| { | ||
| // Arrange | ||
| using var tentacle = new TentacleConfigurationBuilder().WithCertificateThumbprint("OLD").Build(); | ||
| var target = new MachineResource { Id = "Machines-1", Endpoint = new ListeningTentacleEndpointResource { Thumbprint = "OLD" } }; | ||
| var worker = new WorkerResource { Id = "Workers-1", Endpoint = new PollingTentacleEndpointResource { Uri = "poll://abc123/", Thumbprint = "OLD" } }; | ||
| var octopus = new FakeOctopus(); | ||
| var spaceA = octopus.Space("Spaces-1").WithMachine(target); | ||
| var spaceB = octopus.Space("Spaces-2").WithWorker(worker); | ||
|
|
||
| // Act | ||
| ReplaceCertificate(tentacle, octopus); | ||
|
|
||
| // Assert | ||
| var newThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint; | ||
| newThumbprint.Should().NotBe("OLD"); | ||
| ((TentacleEndpointResource)target.Endpoint).Thumbprint.Should().Be(newThumbprint); | ||
| ((PollingTentacleEndpointResource)worker.Endpoint).Thumbprint.Should().Be(newThumbprint); | ||
| ((PollingTentacleEndpointResource)worker.Endpoint).Uri.Should().Be("poll://abc123/"); | ||
| spaceA.Machines.Received().Modify(target, Arg.Any<CancellationToken>()); | ||
| spaceB.Workers.Received().Modify(worker, Arg.Any<CancellationToken>()); | ||
| } | ||
|
|
||
| [Test] | ||
| public void WhenAnUpdateFailsRerunningWithApplyCurrentCertFinishesWithTheSameCertificate() | ||
| { | ||
| // Arrange | ||
| using var tentacle = new TentacleConfigurationBuilder().WithCertificateThumbprint("OLD").Build(); | ||
| var first = new MachineResource { Id = "Machines-1", Endpoint = new ListeningTentacleEndpointResource { Thumbprint = "OLD" } }; | ||
| var second = new MachineResource { Id = "Machines-2", Endpoint = new ListeningTentacleEndpointResource { Thumbprint = "OLD" } }; | ||
| var octopus = new FakeOctopus(); | ||
| var space = octopus.Space("Spaces-1").WithMachine(first).WithMachine(second); | ||
| var octopusIsDown = true; | ||
| space.Machines.Modify(second, Arg.Any<CancellationToken>()).Returns(_ => | ||
| { | ||
| if (!octopusIsDown) | ||
| return Task.FromResult(second); | ||
| octopusIsDown = false; | ||
| ((TentacleEndpointResource)second.Endpoint).Thumbprint = "OLD"; | ||
| throw new Exception("Octopus is down"); | ||
| }); | ||
| Action run = () => ReplaceCertificate(tentacle, octopus); | ||
| run.Should().Throw<Exception>().WithMessage("Octopus is down"); | ||
| var savedThumbprint = tentacle.Configuration.TentacleCertificate!.Thumbprint; | ||
|
|
||
| // Act | ||
| ReplaceCertificate(tentacle, octopus, "--apply-current-cert-to-tentacles-with-thumbprint=OLD"); | ||
|
|
||
| // Assert | ||
| tentacle.Configuration.TentacleCertificate!.Thumbprint.Should().Be(savedThumbprint); | ||
| ((TentacleEndpointResource)first.Endpoint).Thumbprint.Should().Be(savedThumbprint); | ||
| ((TentacleEndpointResource)second.Endpoint).Thumbprint.Should().Be(savedThumbprint); | ||
| } | ||
|
|
||
| [Test] | ||
| public void WhenNothingMatchesTheCertificateIsNotReplaced() | ||
| { | ||
| // Arrange | ||
| using var tentacle = new TentacleConfigurationBuilder().WithCertificateThumbprint("OLD").Build(); | ||
| var octopus = new FakeOctopus(); | ||
| octopus.Space("Spaces-1"); | ||
|
|
||
| // Act | ||
| Action run = () => ReplaceCertificate(tentacle, octopus); | ||
|
|
||
| // Assert | ||
| run.Should().Throw<ControlledFailureException>().WithMessage("*OLD*"); | ||
| tentacle.Configuration.TentacleCertificateThumbprint.Should().Be("OLD"); | ||
| } | ||
|
|
||
| static void ReplaceCertificate(TemporaryTentacleConfiguration tentacle, FakeOctopus octopus, params string[] args) | ||
| => new ReplaceCertificateCommand( | ||
| new Lazy<IWritableTentacleConfiguration>(() => tentacle.Configuration), | ||
| new Lazy<ICertificateGenerator>(() => new CertificateGenerator(new NullLog())), | ||
| octopus.ClientInitializer, | ||
| Substitute.For<IProxyConfigParser>(), | ||
| Substitute.For<ISystemLog>(), | ||
| tentacle.Selector, | ||
| Substitute.For<ILogFileOnlyLogger>()) | ||
| .Start(new[] { "--server=http://octopus.test", "--apiKey=API-KEY" }.Concat(args).ToArray(), Substitute.For<ICommandRuntime>(), new OptionSet()); | ||
|
|
||
| class FakeOctopus | ||
| { | ||
| readonly IOctopusAsyncClient client = Substitute.For<IOctopusAsyncClient>(); | ||
| readonly List<SpaceResource> spaces = new(); | ||
|
|
||
| public FakeOctopus() | ||
| { | ||
| var user = new UserResource(); | ||
| client.ForSystem().Users.GetCurrent().Returns(user); | ||
| client.ForSystem().Users.GetSpaces(user).Returns(_ => spaces.ToArray()); | ||
| ClientInitializer.CreateClient(Arg.Any<ApiEndpointOptions>(), Arg.Any<System.Net.IWebProxy?>()).Returns(client); | ||
| } | ||
|
|
||
| public IOctopusClientInitializer ClientInitializer { get; } = Substitute.For<IOctopusClientInitializer>(); | ||
|
|
||
| public FakeSpace Space(string id) | ||
| { | ||
| var space = new SpaceResource { Id = id }; | ||
| spaces.Add(space); | ||
| var repository = Substitute.For<IOctopusSpaceAsyncRepository>(); | ||
| client.ForSpace(space).Returns(repository); | ||
| return new FakeSpace(repository); | ||
| } | ||
| } | ||
|
|
||
| class FakeSpace | ||
| { | ||
| readonly IOctopusSpaceAsyncRepository repository; | ||
| readonly List<MachineResource> machines = new(); | ||
| readonly List<WorkerResource> workers = new(); | ||
|
|
||
| public FakeSpace(IOctopusSpaceAsyncRepository repository) | ||
| { | ||
| this.repository = repository; | ||
| repository.Machines.FindByThumbprint(Arg.Any<string>()).Returns(c => machines.FindAll(m => ((TentacleEndpointResource)m.Endpoint).Thumbprint == c.Arg<string>())); | ||
| repository.Workers.FindByThumbprint(Arg.Any<string>()).Returns(c => workers.FindAll(w => ((TentacleEndpointResource)w.Endpoint).Thumbprint == c.Arg<string>())); | ||
| } | ||
|
|
||
| public Octopus.Client.Repositories.Async.IMachineRepository Machines => repository.Machines; | ||
| public Octopus.Client.Repositories.Async.IWorkerRepository Workers => repository.Workers; | ||
|
|
||
| public FakeSpace WithMachine(MachineResource machine) | ||
| { | ||
| machines.Add(machine); | ||
| return this; | ||
| } | ||
|
|
||
| public FakeSpace WithWorker(WorkerResource worker) | ||
| { | ||
| workers.Add(worker); | ||
| return this; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| using System; | ||
| using System.IO; | ||
| using NSubstitute; | ||
| using Octopus.Tentacle.Certificates; | ||
| using Octopus.Tentacle.Configuration; | ||
| using Octopus.Tentacle.Configuration.Instances; | ||
| using Octopus.Tentacle.Core.Diagnostics; | ||
| using Octopus.Tentacle.Diagnostics; | ||
| using Octopus.Tentacle.Util; | ||
|
|
||
| namespace Octopus.Tentacle.Tests.Support | ||
| { | ||
| class TentacleConfigurationBuilder | ||
| { | ||
| string settings = ""; | ||
|
|
||
| public TentacleConfigurationBuilder WithCertificateThumbprint(string thumbprint) | ||
| { | ||
| settings += $"<set key=\"Tentacle.CertificateThumbprint\">{thumbprint}</set>"; | ||
| return this; | ||
| } | ||
|
|
||
| public TemporaryTentacleConfiguration Build() | ||
| { | ||
| var fileSystem = new OctopusPhysicalFileSystem(Substitute.For<ISystemLog>()); | ||
| var directory = new TemporaryDirectory(fileSystem); | ||
| var configFile = Path.Combine(directory.DirectoryPath, "Tentacle.config"); | ||
| File.WriteAllText(configFile, $"<?xml version=\"1.0\" encoding=\"utf-8\"?><octopus-settings>{settings}</octopus-settings>"); | ||
| var store = new XmlFileKeyValueStore(fileSystem, configFile); | ||
|
|
||
| var selector = Substitute.For<IApplicationInstanceSelector>(); | ||
| selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, configFile, store, store)); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Overtime we might improve this. I think tentacle is a PITA since it uses /etc/octopus which can only be changed by setting env vars but we don't want to set env vars in a test |
||
|
|
||
| var configuration = new WritableTentacleConfiguration( | ||
| selector, | ||
| Substitute.For<IHomeConfiguration>(), | ||
| new CertificateGenerator(new NullLog()), | ||
| Substitute.For<IProxyConfiguration>(), | ||
| Substitute.For<IPollingProxyConfiguration>(), | ||
| Substitute.For<ISystemLog>()); | ||
|
|
||
| return new TemporaryTentacleConfiguration(directory, configuration, selector); | ||
| } | ||
| } | ||
|
|
||
| class TemporaryTentacleConfiguration : IDisposable | ||
| { | ||
| readonly TemporaryDirectory directory; | ||
|
|
||
| public TemporaryTentacleConfiguration(TemporaryDirectory directory, WritableTentacleConfiguration configuration, IApplicationInstanceSelector selector) | ||
| { | ||
| this.directory = directory; | ||
| Configuration = configuration; | ||
| Selector = selector; | ||
| } | ||
|
|
||
| public WritableTentacleConfiguration Configuration { get; } | ||
| public IApplicationInstanceSelector Selector { get; } | ||
|
|
||
| public void Dispose() => directory.Dispose(); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Octopus.Client; | ||
| using Octopus.Client.Model; | ||
| using Octopus.Client.Model.Endpoints; | ||
| using Octopus.Tentacle.Certificates; | ||
| using Octopus.Tentacle.Commands.OptionSets; | ||
| using Octopus.Tentacle.Configuration; | ||
| using Octopus.Tentacle.Configuration.Instances; | ||
| using Octopus.Tentacle.Core.Diagnostics; | ||
| using Octopus.Tentacle.Security; | ||
| using Octopus.Tentacle.Startup; | ||
|
|
||
| namespace Octopus.Tentacle.Commands | ||
| { | ||
| public class ReplaceCertificateCommand : AbstractStandardCommand | ||
| { | ||
| readonly Lazy<IWritableTentacleConfiguration> configuration; | ||
| readonly Lazy<ICertificateGenerator> certificateGenerator; | ||
| readonly IOctopusClientInitializer octopusClientInitializer; | ||
| readonly IProxyConfigParser proxyConfig; | ||
| readonly ISystemLog log; | ||
| readonly ApiEndpointOptions api; | ||
| string applyCurrentCertToTentaclesWithThumbprint = null!; | ||
|
|
||
| public ReplaceCertificateCommand( | ||
| Lazy<IWritableTentacleConfiguration> configuration, | ||
| Lazy<ICertificateGenerator> certificateGenerator, | ||
| IOctopusClientInitializer octopusClientInitializer, | ||
| IProxyConfigParser proxyConfig, | ||
| ISystemLog log, | ||
| IApplicationInstanceSelector selector, | ||
| ILogFileOnlyLogger logFileOnlyLogger) | ||
| : base(selector, log, logFileOnlyLogger) | ||
| { | ||
| this.configuration = configuration; | ||
| this.certificateGenerator = certificateGenerator; | ||
| this.octopusClientInitializer = octopusClientInitializer; | ||
| this.proxyConfig = proxyConfig; | ||
| this.log = log; | ||
|
|
||
| api = AddOptionSet(new ApiEndpointOptions(Options)); | ||
| Options.Add("apply-current-cert-to-tentacles-with-thumbprint=", "Does not create a new certificate. Instead, updates every deployment target and worker in Octopus that has this thumbprint to trust this Tentacle's current certificate.", s => applyCurrentCertToTentaclesWithThumbprint = s); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if the command fails, the user will have to re-run with this. we also log: |
||
| } | ||
|
|
||
| protected override void Start() | ||
| { | ||
| base.Start(); | ||
| StartAsync().GetAwaiter().GetResult(); | ||
| } | ||
|
|
||
| async Task StartAsync() | ||
| { | ||
| var config = configuration.Value; | ||
| var keepCurrentCertificate = !string.IsNullOrWhiteSpace(applyCurrentCertToTentaclesWithThumbprint); | ||
| var oldThumbprint = keepCurrentCertificate ? applyCurrentCertToTentaclesWithThumbprint : config.TentacleCertificateThumbprint; | ||
| if (string.IsNullOrWhiteSpace(oldThumbprint) || string.IsNullOrWhiteSpace(config.TentacleCertificateThumbprint)) | ||
| { | ||
| throw new ControlledFailureException("This Tentacle has no certificate thumbprint in its configuration, so its registrations in Octopus cannot be found."); | ||
| } | ||
|
|
||
| using var client = await octopusClientInitializer.CreateClient(api, proxyConfig.ParseToWebProxy(config.PollingProxyConfiguration)); | ||
| var registrations = await FindRegistrations(client, oldThumbprint!); | ||
| if (registrations.Count == 0) | ||
| { | ||
| throw new ControlledFailureException($"No deployment target or worker with thumbprint {oldThumbprint} was found in any space this API key can access."); | ||
| } | ||
|
|
||
| if (!keepCurrentCertificate) | ||
| { | ||
| var certificate = certificateGenerator.Value.GenerateNew(CertificateExpectations.TentacleCertificateFullName); | ||
| config.ImportCertificate(certificate); | ||
| log.Info($"Replaced certificate {oldThumbprint} with {certificate.Thumbprint}. If this does not complete, re-run this command with --apply-current-cert-to-tentacles-with-thumbprint {oldThumbprint}"); | ||
| } | ||
|
|
||
| foreach (var (repository, machine) in registrations) | ||
| { | ||
| ((TentacleEndpointResource)machine.Endpoint).Thumbprint = config.TentacleCertificateThumbprint; | ||
| await Modify(repository, machine); | ||
| log.Info($"Updated '{machine.Name}' ({machine.Id}) in Octopus to trust the new certificate"); | ||
| } | ||
|
|
||
| VoteForRestart(); | ||
| } | ||
|
|
||
| static async Task<List<(IOctopusSpaceAsyncRepository Repository, MachineBasedResource Machine)>> FindRegistrations(IOctopusAsyncClient client, string thumbprint) | ||
| { | ||
| var users = client.ForSystem().Users; | ||
| var spaces = await users.GetSpaces(await users.GetCurrent()); | ||
|
|
||
| var registrations = new List<(IOctopusSpaceAsyncRepository, MachineBasedResource)>(); | ||
| foreach (var space in spaces) | ||
| { | ||
| var repository = client.ForSpace(space); | ||
| var machines = (await repository.Machines.FindByThumbprint(thumbprint)).Cast<MachineBasedResource>() | ||
| .Concat(await repository.Workers.FindByThumbprint(thumbprint)) | ||
| .Where(m => m.Endpoint is ListeningTentacleEndpointResource or PollingTentacleEndpointResource); | ||
| registrations.AddRange(machines.Select(m => (repository, m))); | ||
| } | ||
|
|
||
| return registrations; | ||
| } | ||
|
|
||
| static Task Modify(IOctopusSpaceAsyncRepository repository, MachineBasedResource machine) | ||
| => machine is WorkerResource worker | ||
| ? repository.Workers.Modify(worker, CancellationToken.None) | ||
| : repository.Machines.Modify((MachineResource)machine, CancellationToken.None); | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.