From 21f349c89f2e3fc01a5c3d17c3cbcf34de9f0140 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 09:54:49 +1100 Subject: [PATCH 001/124] Stop deriving Linux Tentacle's config encryption key from /etc/machine-id --- docker/linux/Dockerfile | 6 +- docker/linux/scripts/configure-and-run.sh | 7 + docker/readme.md | 11 + .../test-scripts/test-linux-package.sh | 44 ++++ .../Util/EnvironmentVariables.cs | 1 + .../Util/FileSystem/IOctopusFileSystem.cs | 4 + .../Util/OctopusPhysicalFileSystem.cs | 80 +++++++ source/Octopus.Tentacle.Core/Util/UnixFile.cs | 16 ++ .../Support/SharedTentacleCryptoState.cs | 33 ++- .../Support/TentacleBuilder.cs | 2 + .../TentacleCommandLineTests.cs | 5 + .../Commands/CreateInstanceCommandFixture.cs | 37 +++ .../ProxyConfigurationCommandFixture.cs | 7 +- .../Commands/RunAgentCommandFixture.cs | 19 +- .../ApplicationInstanceSelectorFixture.cs | 19 ++ .../LegacyCiphertextCompatibilityFixture.cs | 121 ++++++++++ .../Crypto/LegacySchemeEncryption.cs | 38 +++ .../LinuxConfigurationFileSecurityFixture.cs | 92 ++++++++ .../Crypto/LinuxGeneratedMachineKeyFixture.cs | 17 +- .../Crypto/LinuxMachineKeyEncryptorFixture.cs | 85 +++---- .../TentacleConfigurationUpgradeFixture.cs | 205 ++++++++++++++++ .../XmlFileKeyValueStoreFixture.cs | 15 +- ...XmlFileKeyValueStoreReEncryptionFixture.cs | 77 ++++++ .../Support/TestMachineKeyEncryptor.cs | 44 ++++ .../Commands/CreateInstanceCommand.cs | 7 +- .../Commands/RunAgentCommand.cs | 7 +- .../UpgradeConfigurationEncryptionCommand.cs | 49 ++++ .../Configuration/ConfigurationModule.cs | 3 +- .../Crypto/ICryptoKeyNixSource.cs | 2 + .../Crypto/IMachineKeyEncryptor.cs | 4 +- .../Crypto/LinuxGeneratedMachineKey.cs | 132 +++++++++-- .../Configuration/Crypto/LinuxMachineIdKey.cs | 5 + .../Crypto/LinuxMachineKeyEncryptor.cs | 219 +++++++++++++++--- .../Crypto/MachineKeyEncryptor.cs | 56 ++--- .../FlatDictionaryKeyValueStore.cs | 40 +++- .../HierarchicalDictionaryKeyValueStore.cs | 15 +- .../ApplicationInstanceConfiguration.cs | 7 +- .../Instances/ApplicationInstanceSelector.cs | 43 +++- .../JsonHierarchicalKeyValueStore.cs | 2 +- .../TentacleConfigurationUpgrade.cs | 194 ++++++++++++++++ .../WindowsMachineKeyEncryptor.cs | 5 +- .../Configuration/XmlFileKeyValueStore.cs | 26 ++- .../Configuration/XmlKeyValueStore.cs | 3 +- .../Crypto/KubernetesMachineKeyEncryptor.cs | 3 + .../RetryingKubernetesPhysicalFileSystem.cs | 5 + source/Octopus.Tentacle/Program.cs | 1 + .../Startup/ServiceCommand.cs | 8 +- testing/README.md | 10 +- .../build-and-test-linux-docker-image.sh | 7 + .../test-config-encryption-upgrade.sh | 49 ++++ testing/run-linux-unit-tests-in-docker.sh | 35 +++ 51 files changed, 1730 insertions(+), 192 deletions(-) create mode 100644 source/Octopus.Tentacle.Core/Util/UnixFile.cs create mode 100644 source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs create mode 100644 source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs create mode 100644 source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacySchemeEncryption.cs create mode 100644 source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs create mode 100644 source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs create mode 100644 source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs create mode 100644 source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs create mode 100644 source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs create mode 100644 source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs create mode 100755 testing/docker-linux/test-config-encryption-upgrade.sh create mode 100755 testing/run-linux-unit-tests-in-docker.sh diff --git a/docker/linux/Dockerfile b/docker/linux/Dockerfile index af8d4322c..61680c1fa 100644 --- a/docker/linux/Dockerfile +++ b/docker/linux/Dockerfile @@ -50,7 +50,11 @@ RUN apt-get update && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* && \ ln -s /opt/octopus/tentacle/Tentacle /usr/bin/tentacle - + +# dbus and systemd, pulled in by install-docker.sh, generate a machine-id at build time that every container from this +# image would share. Both copies must be emptied, as each tool restores the other's. +RUN truncate -s 0 /etc/machine-id && rm -f /var/lib/dbus/machine-id + WORKDIR / # We know this won't reduce the image size at all. It's just to make the filesystem a little tidier. diff --git a/docker/linux/scripts/configure-and-run.sh b/docker/linux/scripts/configure-and-run.sh index 075879110..1462129c5 100644 --- a/docker/linux/scripts/configure-and-run.sh +++ b/docker/linux/scripts/configure-and-run.sh @@ -1,6 +1,13 @@ #!/bin/bash set -eu +# A path on the same device as / lives in the container's own layer and is lost when the container is re-created. +is_persisted() { mkdir -p "$1" && [ "$(stat -c %d "$1")" != "$(stat -c %d /)" ]; } +if is_persisted /etc/octopus && ! is_persisted /var/octopus/tentacle/keys; then + echo "/etc/octopus is persisted but /var/octopus/tentacle/keys is not. The configuration cannot be decrypted without its key once this container is re-created. Mount /var/octopus/tentacle/keys on a volume too." >&2 + exit 1 +fi + /scripts/configure-tentacle.sh # Clear sensitive env variables that should not be inherited by the tentacle process or any forked child processes diff --git a/docker/readme.md b/docker/readme.md index 5a899b3d6..41dda7e9b 100644 --- a/docker/readme.md +++ b/docker/readme.md @@ -68,6 +68,17 @@ It is recommended that you run this using something like docker compose, so that - **CustomPublicHostName**: If `PublicHostNameConfiguration` is set to `Custom`, the host name that the Octopus Server should use to communicate with the Tentacle. +### Volumes + +Mount these to keep the Tentacle's identity when the container is re-created: + +| Path | Contains | +| --- | --- | +| `/etc/octopus` | Configuration, including the certificate | +| `/var/octopus/tentacle/keys` | Key that encrypts the configuration | + +Mount both or neither: the configuration can't be decrypted without its key. Configuration persisted by an earlier image can't be upgraded; start on new volumes. + ### Ports - **10933**: Port Tentacle will be listening on. diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh index 0cb9ed86b..77bc67d3e 100644 --- a/linux-packages/test-scripts/test-linux-package.sh +++ b/linux-packages/test-scripts/test-linux-package.sh @@ -56,5 +56,49 @@ fi echo "The installed Tentacle version matches the expected one." echo "" +# A new certificate must be encrypted with the instance's generated key, not one derived from /etc/machine-id. +INSTANCE_NAME="package-test" +CONFIGURATION_FILE="/etc/octopus/$INSTANCE_NAME/tentacle.config" +MACHINE_KEY_FILE="/var/octopus/tentacle/keys/$INSTANCE_NAME/config-encryption.key" + +mkdir -p "$(dirname "$CONFIGURATION_FILE")" +Tentacle create-instance --instance "$INSTANCE_NAME" --config "$CONFIGURATION_FILE" +Tentacle new-certificate --instance "$INSTANCE_NAME" + +if ! grep -qF 'key="Tentacle.Certificate">$OctopusMachineKeyV1$' "$CONFIGURATION_FILE"; then + echo "The Tentacle certificate in $CONFIGURATION_FILE was not encrypted with the versioned machine key scheme." + exit 1 +fi +echo "The Tentacle certificate is encrypted with the key generated for this machine." + +MACHINE_KEY_MODE=$(stat -c %a "$MACHINE_KEY_FILE") +if [[ "$MACHINE_KEY_MODE" != "600" ]]; then + echo "$MACHINE_KEY_FILE has permissions $MACHINE_KEY_MODE but only its owner should be able to read or write it (600)." + exit 1 +fi +echo "The machine key file can only be read by its owner." + +# A numeric uid stands in for the service user, as minimal images may not have useradd. +SERVICE_USER_ID=4321 +chown "$SERVICE_USER_ID" "$CONFIGURATION_FILE" +Tentacle upgrade-configuration-encryption --instance "$INSTANCE_NAME" + +for KEY_PATH in "$MACHINE_KEY_FILE" "$(dirname "$MACHINE_KEY_FILE")"; do + KEY_PATH_OWNER=$(stat -c %u "$KEY_PATH") + if [[ "$KEY_PATH_OWNER" != "$SERVICE_USER_ID" ]]; then + echo "$KEY_PATH is owned by uid $KEY_PATH_OWNER but the configuration is owned by uid $SERVICE_USER_ID, so the service could not read its key." + exit 1 + fi +done +echo "The machine key was given to the owner of the configuration." + +THUMBPRINT=$(Tentacle show-thumbprint --instance "$INSTANCE_NAME") +if [[ -z "$THUMBPRINT" ]] || ! grep -qF "key=\"Tentacle.CertificateThumbprint\">$THUMBPRINT<" "$CONFIGURATION_FILE"; then + echo "'Tentacle show-thumbprint' reported '$THUMBPRINT', which is not the thumbprint recorded in $CONFIGURATION_FILE." + exit 1 +fi +echo "The certificate decrypts in a new process and matches the recorded thumbprint." +echo "" + echo "All tests passed." echo "" diff --git a/source/Octopus.Tentacle.Core/Util/EnvironmentVariables.cs b/source/Octopus.Tentacle.Core/Util/EnvironmentVariables.cs index 2b5f83a59..616441848 100644 --- a/source/Octopus.Tentacle.Core/Util/EnvironmentVariables.cs +++ b/source/Octopus.Tentacle.Core/Util/EnvironmentVariables.cs @@ -27,6 +27,7 @@ public static class EnvironmentVariables public const string TentacleTcpKeepAliveEnabled = "TentacleTcpKeepAliveEnabled"; public const string TentacleEnableDataStreamLengthChecks = "TentacleEnableDataStreamLengthChecks"; public const string TentacleMachineConfigurationHomeDirectory = "TentacleMachineConfigurationHomeDirectory"; + public const string TentacleConfigurationKeysDirectory = "TentacleConfigurationKeysDirectory"; public const string TentaclePollingConnectionCount = "TentaclePollingConnectionCount"; public const string TentaclePowerShellStartupTimeout = "TentaclePowerShellStartupTimeout"; public const string NfsWatchdogDirectory = "watchdog_directory"; diff --git a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs index 95cb08cc7..20a63e78c 100644 --- a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs @@ -36,6 +36,10 @@ public interface IOctopusFileSystem void WriteAllBytes(string filePath, byte[] data); void WriteAllText(string filePath, string contents); + + // Returns false, leaving the existing file untouched, if another process created it first. + bool AtomicCreateFileWithUserReadWriteAccessOnly(string filePath, byte[] contents); + string ReadAllText(string scriptFile); string[] ReadAllLines(string scriptFile); } diff --git a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs index 0cc039524..a4fd34f6e 100644 --- a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs @@ -250,6 +250,86 @@ public void WriteAllText(string path, string contents) File.WriteAllText(path, contents); } +#if NETFRAMEWORK + public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) + { + var temporaryPath = TemporaryPathBeside(path); + try + { + File.WriteAllBytes(temporaryPath, contents); + try + { + // MoveFile never replaces an existing file. + File.Move(temporaryPath, path); + return true; + } + catch (IOException) when (File.Exists(path)) + { + return false; + } + } + finally + { + DeleteIfExists(temporaryPath); + } + } +#else + public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) + { + var temporaryPath = TemporaryPathBeside(path); + try + { + CreateFileWithUserReadWriteAccessOnly(temporaryPath, contents); + + // File.Move(overwrite: false) checks then renames, so on Unix two racing processes could each keep their own file. + if (!OperatingSystem.IsWindows() && UnixFile.TryLinkWithoutReplacing(temporaryPath, path)) + { + return true; + } + if (File.Exists(path)) + { + return false; + } + + File.Move(temporaryPath, path, overwrite: false); + return true; + } + catch (IOException) when (File.Exists(path)) + { + return false; + } + finally + { + DeleteIfExists(temporaryPath); + } + } + + static void CreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) + { + var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None }; + if (!OperatingSystem.IsWindows()) + { + options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + } + + using var stream = new FileStream(path, options); + stream.Write(contents, 0, contents.Length); + stream.Flush(flushToDisk: true); + } +#endif + + static void DeleteIfExists(string path) + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + + // In the same directory, so it is on the same file system and can be moved into place atomically. + static string TemporaryPathBeside(string path) + => path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + public void EnsureDirectoryExists(string directoryPath) { if (!DirectoryExists(directoryPath)) diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs new file mode 100644 index 000000000..040ea8d90 --- /dev/null +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -0,0 +1,16 @@ +#if !NETFRAMEWORK +using System.Runtime.InteropServices; + +namespace Octopus.Tentacle.Core.Util +{ + static class UnixFile + { + // Unlike rename(2), link(2) never replaces an existing file. + public static bool TryLinkWithoutReplacing(string existingPath, string newPath) + => link(existingPath, newPath) == 0; + + [DllImport("libc", SetLastError = true)] + static extern int link(string oldpath, string newpath); + } +} +#endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs index 9f9f08c19..502d3dcc2 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs @@ -6,6 +6,7 @@ using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Diagnostics; using Octopus.Tentacle.Security.Certificates; +using Octopus.Tentacle.Util; using Serilog; namespace Octopus.Tentacle.Tests.Integration.Support @@ -30,18 +31,16 @@ public static void Initialize(ILogger logger) { var log = new SystemLog(); - // Stored the way import-certificate stores it: encrypted with the machine key, which - // creates the fallback key if it is needed and does not exist yet. + CreateTheFallbackKeyEarlierVersionsShare(log); + + // Encoded the way import-certificate stores it, then loaded the way a Tentacle loads it + // at startup, which adds it to the store. var pfxPath = TestCertificates.TentaclePfxPath; var certificate = CertificateEncoder.FromPfxFile(pfxPath, string.Empty, log); var encoded = CertificateEncoder.ToBase64String(certificate); - var encrypted = MachineKeyEncryptor.Current.Encrypt(encoded); - - // Loaded the way a Tentacle loads it at startup, which adds it to the store. - var decrypted = MachineKeyEncryptor.Current.Decrypt(encrypted); var loaded = TentacleConfiguration.LoadTentacleCertificate( TestThumbprint, - decrypted, + encoded, log); var comparison = StringComparison.OrdinalIgnoreCase; @@ -59,6 +58,26 @@ public static void Initialize(ILogger logger) Environment.UserName); } + // Earlier versions create it on first use when /etc/machine-id is unusable, and the + // compatibility tests start several of them at once. + static void CreateTheFallbackKeyEarlierVersionsShare(SystemLog log) + { + if (CommonTestUtils.PlatformDetection.IsRunningOnWindows) + { + return; + } + + var fileSystem = new OctopusPhysicalFileSystem(log); + try + { + new LinuxMachineIdKey(fileSystem).Load(); + } + catch (InvalidOperationException) + { + new LinuxGeneratedMachineKey(log, fileSystem, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost).CreateIfMissing(); + } + } + // A Tentacle only reuses the stored certificate when it comes back with its private key. // Otherwise it adds it to the store again, which is the concurrent write this avoids. static void VerifyTheStoreHoldsTheCertificateWithItsPrivateKey() diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs index 20a6f0b7a..3f7924426 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs @@ -322,6 +322,8 @@ protected void ConfigureTentacleMachineConfigurationHomeDirectory() WithRunTentacleEnvironmentVariable(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, directory); } + + WithRunTentacleEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory, Path.Combine(HomeDirectory.DirectoryPath, "keys")); } async Task SetEnvironmentVariablesForService(string instanceName, TemporaryDirectory tempDirectory, ILogger logger, CancellationToken cancellationToken) diff --git a/source/Octopus.Tentacle.Tests.Integration/TentacleCommandLineTests.cs b/source/Octopus.Tentacle.Tests.Integration/TentacleCommandLineTests.cs index 1efc9c236..96389ff5f 100644 --- a/source/Octopus.Tentacle.Tests.Integration/TentacleCommandLineTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/TentacleCommandLineTests.cs @@ -725,6 +725,11 @@ FileVersionInfo GetVersionInfo(TentacleConfigurationTestCase tentacleConfigurati environmentVariablesToRunTentacleWith.Add(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, tempDirectory.DirectoryPath); } + if (!environmentVariablesToRunTentacleWith.ContainsKey(EnvironmentVariables.TentacleConfigurationKeysDirectory)) + { + environmentVariablesToRunTentacleWith.Add(EnvironmentVariables.TentacleConfigurationKeysDirectory, Path.Combine(tempDirectory.DirectoryPath, "keys")); + } + var tentacleExe = TentacleExeFinder.FindTentacleExe(tentacleConfigurationTestCase.TentacleRuntime); var output = new StringBuilder(); var errorOut = new StringBuilder(); diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs new file mode 100644 index 000000000..2b94a7b9c --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs @@ -0,0 +1,37 @@ +using System; +using System.IO; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Commands; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Startup; +using Octopus.Tentacle.Tests.Support.TestAttributes; + +namespace Octopus.Tentacle.Tests.Commands +{ + [TestFixture] + [LinuxTest] + public class CreateInstanceCommandFixture : CommandFixture + { + readonly ITentacleConfigurationUpgrade configurationUpgrade = Substitute.For(); + + [SetUp] + public override void SetUp() + { + base.SetUp(); + Command = new CreateInstanceCommand(Substitute.For(), Substitute.For(), new Lazy(() => configurationUpgrade)); + } + + [Test] + public void ANamedInstanceFailsWhenItsKeyCannotBeCreated() + { + configurationUpgrade.When(u => u.CreateKey()).Do(_ => throw new IOException("Permission denied")); + + Action start = () => Start("--instance=Tentacle", "--config=/etc/octopus/tentacle.config"); + + start.Should().Throw(); + } + } +} diff --git a/source/Octopus.Tentacle.Tests/Commands/ProxyConfigurationCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ProxyConfigurationCommandFixture.cs index bb6d86510..aa7973bb7 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ProxyConfigurationCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ProxyConfigurationCommandFixture.cs @@ -7,6 +7,7 @@ using Octopus.Tentacle.Configuration.Instances; using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Startup; +using Octopus.Tentacle.Tests.Support; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Commands @@ -48,7 +49,7 @@ public void TearDownAfterEachTest() [Test] public void ToggleTheProxy() { - var config = new Lazy(() => new WritableProxyConfiguration(new XmlFileKeyValueStore(octopusFileSystem, configFile))); + var config = new Lazy(() => new WritableProxyConfiguration(new XmlFileKeyValueStore(octopusFileSystem, configFile, encryptor: TestMachineKeyEncryptor.Current))); const string expectedProxyHost = "127.0.0.1"; const string expectedUsername = "yoda"; const string expectedPassword = "do or do not, there is no try"; @@ -85,7 +86,7 @@ void DisableTheProxy() [Test] public void TurnOnDefaultProxy() { - var config = new Lazy(() => new WritableProxyConfiguration(new XmlFileKeyValueStore(octopusFileSystem, configFile))); + var config = new Lazy(() => new WritableProxyConfiguration(new XmlFileKeyValueStore(octopusFileSystem, configFile, encryptor: TestMachineKeyEncryptor.Current))); Command = new ProxyConfigurationCommand(config, applicationInstanceSelector, Substitute.For(), Substitute.For()); EnableTheDefaultProxy(); @@ -98,7 +99,7 @@ public void TurnOnDefaultProxy() [Test] public void UseACustomHostAndIgnoreHttpAndPort() { - var config = new Lazy(() => new WritableProxyConfiguration(new XmlFileKeyValueStore(octopusFileSystem, configFile))); + var config = new Lazy(() => new WritableProxyConfiguration(new XmlFileKeyValueStore(octopusFileSystem, configFile, encryptor: TestMachineKeyEncryptor.Current))); Command = new ProxyConfigurationCommand(config, applicationInstanceSelector, Substitute.For(), Substitute.For()); EnableAnIncorrectlySuppliedProxyHost(); diff --git a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs index 29c667efa..bd43cb327 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs @@ -29,6 +29,7 @@ public class RunAgentCommandFixture : CommandFixture IHomeConfiguration home = null!; IApplicationInstanceSelector selector = null!; IBackgroundTask[] backgroundTasks = null!; + ITentacleConfigurationUpgrade configurationUpgrade = null!; [SetUp] public override void SetUp() @@ -41,6 +42,7 @@ public override void SetUp() tentacleConfiguration.TentacleCertificate.Returns(certificate); home = Substitute.For(); sleep = Substitute.For(); + configurationUpgrade = Substitute.For(); backgroundTasks = new[] { @@ -60,11 +62,26 @@ public override void SetUp() Substitute.For(), new AppVersion(GetType().Assembly), Substitute.For(), - backgroundTasks.Select(bt => new Lazy(() => bt)).ToList()); + backgroundTasks.Select(bt => new Lazy(() => bt)).ToList(), + new Lazy(() => configurationUpgrade)); selector.Current.Returns(new ApplicationInstanceConfiguration("MyTentacle", null, null, null)); } + [Test] + public void WhenCommandIsStartedThenTheConfigurationIsUpgradedBeforeHalibutStarts() + { + // Act + Start(); + + // Assert + Received.InOrder(() => + { + configurationUpgrade.Run(); + halibut.Start(); + }); + } + [Test] public void WhenCommandIsStartedThenBackgroundServicesAreStarted() { diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs index 4ce170ef8..d297785c5 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs @@ -92,6 +92,25 @@ public void GivenConfigurationInstanceExists_WhenRequestingConfigurationInstance mock.Current.ConfigurationPath.Should().Be(filePath); } + [Test] + public void GivenARegisteredInstanceUsesTheConfiguration_WhenRequestingConfigurationInstance_ThenItUsesThatInstancesKey() + { + if (PlatformDetection.IsRunningOnWindows) + Assert.Ignore("Configuration encryption keys are Linux only"); + + var filePath = "/etc/octopus/tentacle.config"; + var mock = CreateApplicationInstanceSelector(new StartUpConfigFileInstanceRequest(filePath)); + octopusFileSystem.FileExists(filePath).Returns(true); + octopusFileSystem.GetFullPath(Arg.Any()).Returns(c => c.Arg()); + applicationInstanceStore.ListInstances().Returns(new[] + { + new ApplicationInstanceRecord("Other", "/etc/octopus/other.config"), + new ApplicationInstanceRecord("Registered", filePath) + }); + + mock.Current.KeyFilePath.Should().Be(LinuxGeneratedMachineKey.KeyFilePathFor("Registered")); + } + [Test] public void GivenConfigurationInstanceDoesNotExists_WhenRequestingConfigurationInstance_ThenThrows() { diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs new file mode 100644 index 000000000..8eb4b7406 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs @@ -0,0 +1,121 @@ +#if !NETFRAMEWORK +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Kubernetes; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Tests.Configuration.Crypto +{ + // The ciphertext below was captured from the encryptor as it was before the versioned format (commit 7b1504e), which + // used a fixed IV and so is deterministic. Do not regenerate it with the current code: that would only prove the + // current code agrees with itself. + [TestFixture] + public class LegacyCiphertextCompatibilityFixture + { + const string MachineId = "816490f117f14c7a8fa2697781ed795b"; + const string GeneratedKeyFileContents = "MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=.ZmVkY2JhOTg3NjU0MzIxMA=="; + + const string ShortText = "FooBar"; + const string SerialisedBool = "true"; + const string SerialisedInt = "123"; + const string UnicodeText = "pässwörd 🐙 with spaces & symbols!"; + static readonly string CertificateSizedText = Convert.ToBase64String(Enumerable.Range(0, 300).Select(i => (byte)(i * 7)).ToArray()); + + public static IEnumerable WrittenWithTheMachineIdKey() + { + yield return new TestCaseData(ShortText, "yspqcK7xCvd5c+1OSB7kxw==").SetName("{m}(machine-id, short text)"); + yield return new TestCaseData(SerialisedBool, "lfWdFxOQukFHfUs767dBOA==").SetName("{m}(machine-id, serialised bool)"); + yield return new TestCaseData(SerialisedInt, "c5E+1E8Q73XGrrSEWenz/A==").SetName("{m}(machine-id, serialised int)"); + yield return new TestCaseData(UnicodeText, "nMmwC8Uzkg/bEwaDChRL86dTMzY4gCyveDi0qCjOWNENjQzd3wYS8lJwMeGXNdEy").SetName("{m}(machine-id, unicode)"); + yield return new TestCaseData(CertificateSizedText, + "2qbSDqJXa0/Bz1SzohM21m3dg3mIPBjj4mgbfve/WW1cZFNAgccjx+Hot6Qp8/TC8Su4rLS8yp6i+WY4J8x7ga6DbFVD4pQkjy8ag37nxwBos4llfCRhRqV0LZWol2U66+znAfTscepLI1nVWgtJtloYLGky/6QDjvMQQG9S/MmQsBzANfI3lQG8ftYK/ilU6xX7eJwvWViEG3HI/3loc7k9jbJT13JF4f8NpI3yEH4Q4VCWY9j3z+ZK/2kImeqRDfv9cl4roUdtBQ4I333taVovDwILKqq2a6QPRZiAVJ34in2CrrJv2dTWgaQHsU74upUlKiKrZs6LgpZVP7y+5W/o52te+dvwCBVBqFmxFUmpk/1gAMUiqZ0fEXrz8GlyS4dcIXlFUwUXcdUb1E2ldqDMRr2zDHP0ATwdBcKm9yM4sJKrGhrSksl7U7chM4CpRVTUf1tWvU3SjcQ00haPM+RZP2pWDnkDZhkrDRfpQke/qFL8wG9RySpzWDF+zsN0yUxZJgqUvy9cHb/yHphxTqyEmmoGcAuzOaA9a2yYGPs=") + .SetName("{m}(machine-id, certificate-sized)"); + } + + public static IEnumerable WrittenWithTheGeneratedKey() + { + yield return new TestCaseData(ShortText, "sU7FAsi9LrgjCISbdFN4Kg==").SetName("{m}(generated, short text)"); + yield return new TestCaseData(SerialisedBool, "ks2Nbbl8OonD1r2CFim+VA==").SetName("{m}(generated, serialised bool)"); + yield return new TestCaseData(SerialisedInt, "QL+mcAjSyVWEsVPlQeNvqA==").SetName("{m}(generated, serialised int)"); + yield return new TestCaseData(UnicodeText, "cVzJO4WpcDeZTWcG91jyln6rFJvjf08RkpiAb+FUMcOnzT8uB5emsPmEKS8vyg+p").SetName("{m}(generated, unicode)"); + yield return new TestCaseData(CertificateSizedText, + "NhUpBIgpSxmvYSXfn+cn5lKK5xB1LDf0NdKogqm1MAn4XQ8p84KJwVzEevn/T7Glk9Lirqa/RtUM9HuEEadDZ6XKhbnBdUJGLx1CFfHHw/3L3IProqBX/mD+W0SVIvnI54iq5PFdwtSSOH3a6PC+DT92rmXjy4/YoNzuGKkNcMoP/GG3g6URPHGdMq3NMs7t3wD7k8MbvU96F5qlTdqiwgILViruLJGZhECb99GmTdJ/PjCeFE87+up+vZllk1WVboGAIn6Vf+1Pgd7tDHgczDHZvgKIeP1k5gwH9dXzSd/OweG7eW7Yux0HIcI1oPMDcjx57ldDzYwhgIX5jPkMGFP3J4guwCIaSQTEyMLP85ZervJ0uWlAq/rlIK71dQ5c6wvFIVKkKeSo+qWReMRi9G4rMaelnagNTwUqBBfy+nff+tbvPrLV+CmKDCEgA+g1d7kF7+y/kBJ4NaZOpo6jBUVds/sV7ieVZhcUmHN2eML4/Zur5KyHvHsDnOWU3jgBxQ6oJJQB4yePmWivAXWlE4ISpIvM5i76XYqLbEJ+lbQ=") + .SetName("{m}(generated, certificate-sized)"); + } + + + FakeKeyFiles files; + + [SetUp] + public void SetUp() + { + Environment.SetEnvironmentVariable(KubernetesConfig.NamespaceVariableName, null); + files = new FakeKeyFiles(); + files.Contents[LinuxGeneratedMachineKey.LegacyKeyFilePath] = GeneratedKeyFileContents; + } + + [TearDown] + public void TearDown() + { + Environment.SetEnvironmentVariable(KubernetesConfig.NamespaceVariableName, null); + } + + IMachineKeyEncryptor CreateEncryptorAsComposedInProduction(bool machineIdPresent) + { + var fileSystem = files.CreateFileSystem(); + fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(machineIdPresent); + fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { MachineId }); + + return MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, LinuxGeneratedMachineKey.KeyFilePathFor("Tentacle")); + } + + [TestCaseSource(nameof(WrittenWithTheMachineIdKey))] + public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string plaintext, string legacyCiphertext) + { + // Arrange + files.Contents.Remove(LinuxGeneratedMachineKey.LegacyKeyFilePath); + var encryptor = CreateEncryptorAsComposedInProduction(machineIdPresent: true); + + // Act + var decrypted = encryptor.Decrypt(legacyCiphertext); + + // Assert + decrypted.Should().Be(plaintext); + } + + [TestCaseSource(nameof(WrittenWithTheGeneratedKey))] + public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plaintext, string legacyCiphertext) + { + // Arrange + var encryptor = CreateEncryptorAsComposedInProduction(machineIdPresent: false); + + // Act + var decrypted = encryptor.Decrypt(legacyCiphertext); + + // Assert + decrypted.Should().Be(plaintext); + } + + class FakeKeyFiles + { + public Dictionary Contents { get; } = new(); + + public IOctopusFileSystem CreateFileSystem() + { + var fileSystem = Substitute.For(); + fileSystem.FileExists(Arg.Any()).Returns(ci => Contents.ContainsKey(ci.ArgAt(0))); + fileSystem.ReadAllText(Arg.Any()).Returns(ci => Contents[ci.ArgAt(0)]); + fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(Arg.Any(), Arg.Any()).Returns(ci => Contents.TryAdd(ci.ArgAt(0), Encoding.ASCII.GetString(ci.ArgAt(1)))); + return fileSystem; + } + } + } +} +#endif diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacySchemeEncryption.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacySchemeEncryption.cs new file mode 100644 index 000000000..af82a4898 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacySchemeEncryption.cs @@ -0,0 +1,38 @@ +using System; +using System.Security.Cryptography; +using System.Text; +using Octopus.Tentacle.Configuration.Crypto; + +namespace Octopus.Tentacle.Tests.Configuration.Crypto +{ + public class LegacySchemeEncryptor : IMachineKeyEncryptor + { + readonly ICryptoKeyNixSource keySource; + + public LegacySchemeEncryptor(ICryptoKeyNixSource keySource) + { + this.keySource = keySource; + } + + public string Encrypt(string raw) + { + var plaintext = Encoding.UTF8.GetBytes(raw); + var (key, iv) = keySource.Load(); + using var aes = Aes.Create(); + using var encryptor = aes.CreateEncryptor(key, iv); + return Convert.ToBase64String(encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length)); + } + + public string Decrypt(string encrypted) + { + var (key, iv) = keySource.Load(); + using var aes = Aes.Create(); + using var decryptor = aes.CreateDecryptor(key, iv); + var payload = Convert.FromBase64String(encrypted); + return Encoding.UTF8.GetString(decryptor.TransformFinalBlock(payload, 0, payload.Length)); + } + + public bool RequiresReEncryption(string encrypted) + => false; + } +} diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs new file mode 100644 index 000000000..2bfdd0dc1 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs @@ -0,0 +1,92 @@ +#if !NETFRAMEWORK +using System; +using System.IO; +using System.Linq; +using System.Runtime.Versioning; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Tests.Support.TestAttributes; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Tests.Configuration.Crypto +{ + [TestFixture] + [LinuxTest] + [SupportedOSPlatform("linux")] + public class LinuxConfigurationFileSecurityFixture + { + const UnixFileMode OwnerReadWrite = UnixFileMode.UserRead | UnixFileMode.UserWrite; + + string directory; + string keyFilePath; + ISystemLog log; + OctopusPhysicalFileSystem fileSystem; + + [SetUp] + public void SetUp() + { + directory = Path.Combine(Path.GetTempPath(), "octopus-config-encryption-key-" + Guid.NewGuid()); + keyFilePath = Path.Combine(directory, LinuxGeneratedMachineKey.KeyFileName); + log = Substitute.For(); + fileSystem = new OctopusPhysicalFileSystem(log); + } + + [TearDown] + public void TearDown() + { + if (Directory.Exists(directory)) + { + Directory.Delete(directory, recursive: true); + } + } + + [Test] + public void WhenTheKeyIsCreatedThenOnlyItsOwnerCanReadIt() + { + // Arrange + var keySource = new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath); + + // Act + keySource.CreateIfMissing(); + var (key, iv) = keySource.Load(); + + // Assert + File.Exists(keyFilePath).Should().BeTrue("the directory is created on demand, as it always was"); + File.GetUnixFileMode(keyFilePath).Should().Be(OwnerReadWrite); + File.ReadAllText(keyFilePath).Should().Be(Convert.ToBase64String(key) + "." + Convert.ToBase64String(iv)); + Directory.GetFiles(directory).Should().ContainSingle("the temporary file the key is written to first is not left behind"); + } + + [Test] + public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() + { + // Arrange + const int racers = 32; + using var start = new ManualResetEventSlim(false); + var loads = Enumerable.Range(0, racers) + .Select(_ => Task.Run(() => + { + start.Wait(); + var keySource = new LinuxGeneratedMachineKey(log, new OctopusPhysicalFileSystem(log), keyFilePath); + keySource.CreateIfMissing(); + return keySource.Load().Key; + })) + .ToArray(); + + // Act + start.Set(); + var keys = await Task.WhenAll(loads); + + // Assert + var onDisk = Convert.FromBase64String(File.ReadAllText(keyFilePath).Split('.')[0]); + keys.Should().AllSatisfy(k => k.Should().Equal(onDisk)); + Directory.GetFiles(directory).Should().ContainSingle("no racer's temporary file is left behind"); + } + } +} +#endif diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs index 6b3896983..4bf67d003 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs @@ -49,5 +49,20 @@ public void GivenMachineIdFileIsValidLength_ThenReturnsKeys() key.Should().NotBeEmpty(); iv.Should().NotBeEmpty(); } + + [Test] + public void KeyFileIsKeptPerInstanceOutsideTheConfigurationDirectory() + { + LinuxGeneratedMachineKey.KeyFilePathFor("Tentacle").Should().Be("/var/octopus/tentacle/keys/Tentacle/config-encryption.key"); + } + + [TestCase("")] + [TestCase("..")] + [TestCase("../etc")] + [TestCase("a\\b")] + public void InstanceNamesThatAreNotASingleDirectoryNameAreRejected(string instanceName) + { + Assert.Throws(() => LinuxGeneratedMachineKey.KeyFilePathFor(instanceName)); + } } -} \ No newline at end of file +} diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs index 53dc2154b..4516297a7 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs @@ -1,86 +1,53 @@ -using System; +#if !NETFRAMEWORK +using System; using System.Security.Cryptography; using FluentAssertions; using NSubstitute; using NUnit.Framework; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Tests.Support; namespace Octopus.Tentacle.Tests.Configuration.Crypto { [TestFixture] public class LinuxMachineKeyEncryptorFixture { - readonly InMemoryCryptoKeyNixSource validKey = new InMemoryCryptoKeyNixSource(); readonly ISystemLog systemLog = Substitute.For(); - - [Test] - public void GivenValidKeysAvailable_ThenEncryptsAndDecrypts() - { - var lme = new LinuxMachineKeyEncryptor(systemLog,new[] { validKey }); - - var encrypted = lme.Encrypt("FooBar"); - var decrypted = lme.Decrypt(encrypted); + readonly InMemoryCryptoKeyNixSource generatedKey = new(); - Assert.AreNotEqual(encrypted, "FooBar"); - Assert.AreEqual(decrypted, "FooBar"); - } + LinuxMachineKeyEncryptor CreateEncryptor(params ICryptoKeyNixSource[] legacyKeySources) + => new(systemLog, generatedKey, legacyKeySources); [Test] - public void GivenCorruptKeyProvided_ThenThrowsException() + public void WhenAValueIsEncryptedThenItIsVersionedAndDecrypts() { - var lme = new LinuxMachineKeyEncryptor(systemLog, new []{DodgyKey()}); - - Assert.Throws(() => lme.Encrypt("FooBar")); - } - - [Test] - public void GivenCorruptKeyProvided_WhenFallbackKeyAvailable_ThenEncrypts() - { - var lme = new LinuxMachineKeyEncryptor(systemLog, new []{DodgyKey(), validKey}); + // Arrange + var encryptor = CreateEncryptor(); - var roundTrip = lme.Decrypt(lme.Encrypt("FooBar")); + // Act + var encrypted = encryptor.Encrypt("FooBar"); - roundTrip.Should().Be("FooBar"); + // Assert + encrypted.Should().StartWith(LinuxMachineKeyEncryptor.ProtectedValuePrefix); + encryptor.RequiresReEncryption(encrypted).Should().BeFalse(); + encryptor.Decrypt(encrypted).Should().Be("FooBar"); } [Test] - public void GenMultipleKeys_FirstSuccessfulKeyIsUsed() + public void WhenACurrentValueWasEncryptedWithAnotherKeyThenALegacyKeyIsNotTried() { - var firstDodgyKey = DodgyKey(); - var lastDodgyKey = DodgyKey(); - - var lme = new LinuxMachineKeyEncryptor(systemLog, new []{firstDodgyKey, validKey, lastDodgyKey}); - - lme.Encrypt("FooBar").Should().NotBeEmpty(); - firstDodgyKey.Received(1).Load(); - lastDodgyKey.Received(0).Load(); - } + // Arrange + var otherKey = new InMemoryCryptoKeyNixSource(); + var encryptedWithOtherKey = new LinuxMachineKeyEncryptor(systemLog, otherKey, Array.Empty()).Encrypt("FooBar"); + var encryptor = CreateEncryptor(otherKey); - static ICryptoKeyNixSource DodgyKey() - { - var dodgyKey = Substitute.For(); - dodgyKey.Load().Returns(callInfo => (new byte[] {77}, new byte[]{43, 11})); - return dodgyKey; - } + // Act + Action decrypt = () => encryptor.Decrypt(encryptedWithOtherKey); - class InMemoryCryptoKeyNixSource : ICryptoKeyNixSource - { - readonly byte[] key; - readonly byte[] iv; - public InMemoryCryptoKeyNixSource() - { - var d = Aes.Create(); - d.GenerateIV(); - d.GenerateKey(); - key = d.Key; - iv = d.IV; - } - - public (byte[] Key, byte[] IV) Load() - { - return (key, iv); - } + // Assert + decrypt.Should().Throw(); } } -} \ No newline at end of file +} +#endif diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs new file mode 100644 index 000000000..5173f7fe1 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs @@ -0,0 +1,205 @@ +#if NET +using System; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Xml.Linq; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Commands; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Internals.Options; +using Octopus.Tentacle.Startup; +using Octopus.Tentacle.Tests.Support; +using Octopus.Tentacle.Tests.Support.TestAttributes; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Tests.Configuration +{ + [TestFixture] + [LinuxTest] + public class TentacleConfigurationUpgradeFixture + { + const string Certificate = "MIIC...the certificate..."; + + string directory; + string configurationFile; + ISystemLog log; + OctopusPhysicalFileSystem fileSystem; + + [SetUp] + public void SetUp() + { + directory = Path.Combine(Path.GetTempPath(), "octopus-config-upgrade-" + Guid.NewGuid()); + Directory.CreateDirectory(directory); + configurationFile = Path.Combine(directory, "tentacle.config"); + log = Substitute.For(); + fileSystem = new OctopusPhysicalFileSystem(log); + fileSystem.OverwriteFile(configurationFile, @""); + } + + [TearDown] + public void TearDown() + { + Directory.Delete(directory, recursive: true); + } + + [Test] + public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted() + { + // Arrange + var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName); + var store = CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + RawCertificate().Should().NotStartWith(LinuxMachineKeyEncryptor.ProtectedValuePrefix, "without a key, values are written the way earlier versions wrote them"); + + // Act + CreateUpgrade(store, keyFilePath).Run(); + + // Assert + File.Exists(keyFilePath).Should().BeTrue(); + RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.ProtectedValuePrefix); + CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); + log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); + } + + [Test] + public void WhenOnlyTheKeyIsPreparedThenItIsCreatedAndValuesStayLegacy() + { + // Arrange + var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName); + var store = CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + var legacyValue = RawCertificate(); + + // Act + CreateUpgrade(store, keyFilePath).PrepareKey(); + + // Assert + File.Exists(keyFilePath).Should().BeTrue(); + RawCertificate().Should().Be(legacyValue); + log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); + } + + [Test] + public void WhenTheKeyCannotBeCreatedThenTentacleKeepsWorkingOnTheLegacyKey() + { + // Arrange + var keyFilePath = Path.Combine(configurationFile, "not-a-directory", LinuxGeneratedMachineKey.KeyFileName); + var store = CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + var legacyValue = RawCertificate(); + + // Act + CreateUpgrade(store, keyFilePath).Run(); + store.Set(ProxyConfiguration.ProxyPasswordSettingName, "secret", ProtectionLevel.MachineKey); + + // Assert + log.Received().Warn(Arg.Any(), Arg.Any()); + RawCertificate().Should().Be(legacyValue); + var reloaded = CreateStore(keyFilePath); + reloaded.Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); + reloaded.Get(ProxyConfiguration.ProxyPasswordSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be("secret"); + } + + [Test] + public void WhenTheConfigurationIsNotInTheRegistryThenNoKeyIsCreatedAndValuesStayLegacy() + { + // Arrange + var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName); + var store = CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + var legacyValue = RawCertificate(); + + // Act + CreateUpgrade(store, keyFilePath: null, instanceName: null).Run(); + + // Assert + File.Exists(keyFilePath).Should().BeFalse(); + RawCertificate().Should().Be(legacyValue); + log.Received(1).Warn(Arg.Any()); + } + + [Test] + public void UpgradeConfigurationEncryptionCreatesTheKeyAndReEncryptsLegacyValues() + { + // Arrange + var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName); + var store = CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + + // Act + StartUpgradeCommand(store, keyFilePath); + + // Assert + File.Exists(keyFilePath).Should().BeTrue(); + RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.ProtectedValuePrefix); + CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); + } + + [Test] + public void UpgradeConfigurationEncryptionFailsForAConfigurationNotInTheRegistry() + { + // Arrange + var store = CreateStore(Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName)); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + var legacyValue = RawCertificate(); + + // Act + Action start = () => StartUpgradeCommand(store, keyFilePath: null, instanceName: null); + + // Assert + start.Should().Throw().WithMessage("*create-instance --instance*"); + RawCertificate().Should().Be(legacyValue); + } + + [Test] + public void AValueProtectedWithTheKeyIsNeverRewrittenWithALegacyKey() + { + // Arrange + var keyFilePath = Path.Combine(directory, "my-key", LinuxGeneratedMachineKey.KeyFileName); + new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath).CreateIfMissing(); + CreateStore(keyFilePath).Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + var protectedValue = RawCertificate(); + var storeWithoutKey = CreateStore(Path.Combine(directory, "missing", LinuxGeneratedMachineKey.KeyFileName)); + + // Act + Action set = () => storeWithoutKey.Set(TentacleConfiguration.CertificateSettingName, "another certificate", ProtectionLevel.MachineKey); + + // Assert + set.Should().Throw(); + RawCertificate().Should().Be(protectedValue); + } + + readonly InMemoryCryptoKeyNixSource legacyKey = new(); + + XmlFileKeyValueStore CreateStore(string keyFilePath) + => new(fileSystem, configurationFile, encryptor: new LinuxMachineKeyEncryptor(log, new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath), new[] { legacyKey })); + + TentacleConfigurationUpgrade CreateUpgrade(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle") + => new(CreateSelector(store, keyFilePath, instanceName), fileSystem, log); + + void StartUpgradeCommand(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle") + { + var selector = CreateSelector(store, keyFilePath, instanceName); + var upgrade = new TentacleConfigurationUpgrade(selector, fileSystem, log); + var command = new UpgradeConfigurationEncryptionCommand(new Lazy(() => upgrade), selector, log, Substitute.For()); + command.Start(new string[0], Substitute.For(), new OptionSet()); + } + + IApplicationInstanceSelector CreateSelector(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName) + { + var selector = Substitute.For(); + selector.Current.Returns(new ApplicationInstanceConfiguration(instanceName, configurationFile, store, store, keyFilePath)); + return selector; + } + + string RawCertificate() + => XDocument.Load(configurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; + } +} +#endif diff --git a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreFixture.cs index 51498aa75..5a76890a1 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreFixture.cs @@ -14,6 +14,7 @@ using Octopus.Tentacle.Configuration; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Tests.Support; using Octopus.Tentacle.Util; using Formatting = System.Xml.Formatting; @@ -48,7 +49,7 @@ public void WritesSortedXmlUsingCorrectTypes() var fileSystem = new OctopusPhysicalFileSystem(Substitute.For()); fileSystem.OverwriteFile(configurationFile, @""); - var settings = new XmlFileKeyValueStore(fileSystem, configurationFile); + var settings = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: TestMachineKeyEncryptor.Current); settings.Set("group1.setting2", 123); settings.Set("group1.setting1", true); settings.Set("group2.setting3", "a string"); @@ -76,7 +77,7 @@ public void ReturnsNiceExceptionOnInvalidData() var fileSystem = new OctopusPhysicalFileSystem(Substitute.For()); fileSystem.OverwriteFile(configurationFile, @""); - var settings = new XmlFileKeyValueStore(fileSystem, configurationFile); + var settings = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: TestMachineKeyEncryptor.Current); settings.Set("Int.Setting", "NotAnInt"); settings.Set("Bool.Setting", "NotABool"); settings.Set("Encrypted.Int.Setting", "NotAnInt", ProtectionLevel.MachineKey); @@ -84,7 +85,7 @@ public void ReturnsNiceExceptionOnInvalidData() settings.Save(); - var reloadedSettings = new XmlFileKeyValueStore(fileSystem, configurationFile); + var reloadedSettings = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: TestMachineKeyEncryptor.Current); reloadedSettings.Invoking(x => x.Get("Int.Setting", 1)) .Should() @@ -145,7 +146,7 @@ protected override IKeyValueStore SetupKeyValueStore() settings.Set("group5.setting6", null, ProtectionLevel.MachineKey); settings.Save(); - return new XmlFileKeyValueStore(fileSystem, configurationFile); + return new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: TestMachineKeyEncryptor.Current); } /// @@ -175,7 +176,7 @@ void SetInternal(string name, } if (protectionLevel == ProtectionLevel.MachineKey) - value = MachineKeyEncryptor.Current.Encrypt(value); + value = TestMachineKeyEncryptor.Current.Encrypt(value); Write(name, value); Save(); @@ -243,7 +244,7 @@ protected IKeyValueStore SetupData() EncryptedValue = GenerateValue(); - var settings = new XmlFileKeyValueStore(FileSystem, ConfigurationFile); + var settings = new XmlFileKeyValueStore(FileSystem, ConfigurationFile, encryptor: TestMachineKeyEncryptor.Current); settings.Set("group1.setting2", 123); settings.Set("group1.setting1", true); settings.Set("group2.setting3", "a string"); @@ -290,7 +291,7 @@ class XmlRoundTripTestsWithReReadFromFile : XmlRoundTripTestBase protected override IKeyValueStore SetupKeyValueStore() { SetupData(); - return new XmlFileKeyValueStore(FileSystem, ConfigurationFile); + return new XmlFileKeyValueStore(FileSystem, ConfigurationFile, encryptor: TestMachineKeyEncryptor.Current); } } } diff --git a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs new file mode 100644 index 000000000..a5e58c5df --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs @@ -0,0 +1,77 @@ +#if !NETFRAMEWORK +using System; +using System.IO; +using System.Linq; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Tests.Configuration.Crypto; +using Octopus.Tentacle.Tests.Support; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Tests.Configuration +{ + [TestFixture] + public class XmlFileKeyValueStoreReEncryptionFixture + { + string configurationFile; + OctopusPhysicalFileSystem fileSystem; + InMemoryCryptoKeyNixSource legacyKey; + LinuxMachineKeyEncryptor encryptor; + XmlFileKeyValueStore legacyStore; + XmlFileKeyValueStore store; + + [SetUp] + public void SetUp() + { + configurationFile = Path.GetTempFileName(); + fileSystem = new OctopusPhysicalFileSystem(Substitute.For()); + fileSystem.OverwriteFile(configurationFile, @""); + + legacyKey = new InMemoryCryptoKeyNixSource(); + encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), new InMemoryCryptoKeyNixSource(), new[] { legacyKey }); + + // Writes what an earlier version would have left in the file... + legacyStore = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: new LegacySchemeEncryptor(legacyKey)); + // ...and this is the store the upgraded Tentacle opens it with. + store = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: encryptor); + } + + [TearDown] + public void TearDown() + { + File.Delete(configurationFile); + } + + [Test] + public void WhenSerialisedValuesAreReEncryptedThenTypedReadsStillWork() + { + // Arrange + var names = new[] { "a.bool", "an.int", "an.enum", "an.object" }; + var configurationObject = new MyObject { IntField = 10, BooleanField = true, EnumField = SomeEnum.SomeOtherEnumValue, ArrayField = new[] { new MyNestedObject { Id = 1 } } }; + legacyStore.Set("a.bool", true, ProtectionLevel.MachineKey); + legacyStore.Set("an.int", 123, ProtectionLevel.MachineKey); + legacyStore.Set("an.enum", SomeEnum.SomeOtherEnumValue, ProtectionLevel.MachineKey); + legacyStore.Set("an.object", configurationObject, ProtectionLevel.MachineKey); + + // Act + var reEncrypted = names.Select(store.ReEncryptIfLegacy).ToArray(); + + // Assert + reEncrypted.Should().AllBeEquivalentTo(true); + var reloaded = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: encryptor); + reloaded.Get("a.bool", false, ProtectionLevel.MachineKey).Should().BeTrue(); + reloaded.Get("an.int", 0, ProtectionLevel.MachineKey).Should().Be(123); + reloaded.Get("an.enum", SomeEnum.SomeEnumValue, ProtectionLevel.MachineKey).Should().Be(SomeEnum.SomeOtherEnumValue); + var nested = reloaded.Get("an.object", null, ProtectionLevel.MachineKey); + nested.IntField.Should().Be(10); + nested.BooleanField.Should().BeTrue(); + nested.EnumField.Should().Be(SomeEnum.SomeOtherEnumValue); + nested.ArrayField.Single().Id.Should().Be(1); + } + } +} +#endif diff --git a/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs b/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs new file mode 100644 index 000000000..79adeab1e --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs @@ -0,0 +1,44 @@ +using System; +using System.Security.Cryptography; +using NSubstitute; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Core.Diagnostics; +using PlatformDetection = Octopus.Tentacle.Util.PlatformDetection; + +namespace Octopus.Tentacle.Tests.Support +{ + // On Linux, production generates a key beside the configuration file, which tests must neither depend on nor create; + // an in-memory key stands in for it. + public static class TestMachineKeyEncryptor + { + public static readonly IMachineKeyEncryptor Current = PlatformDetection.IsRunningOnWindows + ? new WindowsMachineKeyEncryptor() + : new LinuxMachineKeyEncryptor(Substitute.For(), new InMemoryCryptoKeyNixSource(), Array.Empty()); + } + + public class InMemoryCryptoKeyNixSource : ICryptoKeyNixSource + { + public InMemoryCryptoKeyNixSource() + { + using var aes = Aes.Create(); + aes.GenerateIV(); + aes.GenerateKey(); + Key = aes.Key; + IV = aes.IV; + } + + public byte[] Key { get; } + public byte[] IV { get; } + + public (byte[] Key, byte[] IV) Load() + { + return (Key, IV); + } + + public (byte[] Key, byte[] IV)? TryLoad() + { + return Load(); + } + } +} diff --git a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs index b990a3b61..fa38b0e87 100644 --- a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs +++ b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs @@ -1,4 +1,5 @@ using System; +using Octopus.Tentacle.Configuration; using Octopus.Tentacle.Configuration.Instances; using Octopus.Tentacle.Startup; @@ -7,13 +8,15 @@ namespace Octopus.Tentacle.Commands public class CreateInstanceCommand : AbstractCommand { readonly IApplicationInstanceManager instanceManager; + readonly Lazy configurationUpgrade; string instanceName = null!; string config = null!; string home = null!; - public CreateInstanceCommand(IApplicationInstanceManager instanceManager, ILogFileOnlyLogger logFileOnlyLogger) : base(logFileOnlyLogger) + public CreateInstanceCommand(IApplicationInstanceManager instanceManager, ILogFileOnlyLogger logFileOnlyLogger, Lazy configurationUpgrade) : base(logFileOnlyLogger) { this.instanceManager = instanceManager; + this.configurationUpgrade = configurationUpgrade; Options.Add("instance=", "Name of the instance to create", v => instanceName = v); Options.Add("config=", "Path to configuration file to create", v => config = v); Options.Add("home=", "[Optional] Path to the home directory - defaults to the same directory as the config file", v => home = v); @@ -29,6 +32,8 @@ protected override void Start() { instanceManager.CreateInstance(instanceName, config, home); } + + configurationUpgrade.Value.CreateKey(); } } } diff --git a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs index 4947e3c37..3c282dcca 100644 --- a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs +++ b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs @@ -27,6 +27,7 @@ public class RunAgentCommand : AbstractStandardCommand readonly Lazy home; readonly Lazy proxyConfiguration; readonly Lazy proxyInitializer; + readonly Lazy configurationUpgrade; readonly ISleep sleep; readonly ISystemLog log; @@ -51,12 +52,14 @@ public RunAgentCommand( IWindowsLocalAdminRightsChecker windowsLocalAdminRightsChecker, AppVersion appVersion, ILogFileOnlyLogger logFileOnlyLogger, - IEnumerable> backgroundTasks) : base(selector, log, logFileOnlyLogger) + IEnumerable> backgroundTasks, + Lazy configurationUpgrade) : base(selector, log, logFileOnlyLogger) { this.halibut = halibut; this.configuration = configuration; this.home = home; this.proxyConfiguration = proxyConfiguration; + this.configurationUpgrade = configurationUpgrade; this.sleep = sleep; this.log = log; this.selector = selector; @@ -98,6 +101,8 @@ protected override void Start() return; } + configurationUpgrade.Value.Run(); + var currentPath = typeof(RunAgentCommand).Assembly.FullLocalPath(); var exePath = PlatformDetection.IsRunningOnWindows ? Path.ChangeExtension(currentPath, "exe") diff --git a/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs b/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs new file mode 100644 index 000000000..ef2b9e5f0 --- /dev/null +++ b/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs @@ -0,0 +1,49 @@ +using System; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Startup; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Commands +{ + public class UpgradeConfigurationEncryptionCommand : AbstractStandardCommand + { + readonly Lazy configurationUpgrade; + readonly IApplicationInstanceSelector instanceSelector; + readonly ISystemLog log; + + public UpgradeConfigurationEncryptionCommand( + Lazy configurationUpgrade, + IApplicationInstanceSelector instanceSelector, + ISystemLog log, + ILogFileOnlyLogger logFileOnlyLogger) + : base(instanceSelector, log, logFileOnlyLogger) + { + this.configurationUpgrade = configurationUpgrade; + this.instanceSelector = instanceSelector; + this.log = log; + } + + protected override void Start() + { + base.Start(); + + var instance = instanceSelector.Current; + if (PlatformDetection.IsRunningOnWindows || !(instance.WritableConfiguration is XmlFileKeyValueStore)) + { + log.Info("Configuration encryption keys only apply to Linux Tentacles with a configuration file; nothing to do."); + return; + } + + if (instance.KeyFilePath == null) + { + throw new ControlledFailureException($"The configuration `{instance.ConfigurationPath}` is not in the instance registry, so it has no encryption key of its own. " + + $"Register it with `create-instance --instance --config {instance.ConfigurationPath}`, then run this command again."); + } + + configurationUpgrade.Value.RunOrThrow(); + log.Info($"The configuration is protected with the encryption key `{instance.KeyFilePath}`."); + } + } +} diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs b/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs index b32d21c6e..edd1872ed 100644 --- a/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs +++ b/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs @@ -97,7 +97,8 @@ protected override void Load(ContainerBuilder builder) builder.RegisterType().As(); builder.RegisterType().As(); builder.RegisterType().As().SingleInstance(); - + builder.RegisterType().As().SingleInstance(); + //Even though these are Kubernetes types, we need to include them in this module as they are used lazily in the base types builder.RegisterType().SingleInstance(); builder.RegisterType().As().SingleInstance(); diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs b/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs index 0cd958ea2..43c5d891c 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs @@ -5,5 +5,7 @@ namespace Octopus.Tentacle.Configuration.Crypto public interface ICryptoKeyNixSource { (byte[] Key, byte[] IV) Load(); + + (byte[] Key, byte[] IV)? TryLoad(); } } \ No newline at end of file diff --git a/source/Octopus.Tentacle/Configuration/Crypto/IMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/IMachineKeyEncryptor.cs index ef4b932aa..f3ebdb4d5 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/IMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/IMachineKeyEncryptor.cs @@ -6,5 +6,7 @@ public interface IMachineKeyEncryptor { string Encrypt(string raw); string Decrypt(string encrypted); + + bool RequiresReEncryption(string encrypted); } -} \ No newline at end of file +} diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs index 838a4e973..438483cf9 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs @@ -1,65 +1,147 @@ using System; -using System.IO; using System.Security.Cryptography; +using System.Text; using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Configuration.Crypto { - public class LinuxGeneratedMachineKey: ICryptoKeyNixSource + // The legacy machinekey file was world-readable, so it is only ever read to decrypt what earlier versions wrote and is + // never adopted as the current key. Both files are base64(key).base64(iv); the IV is only used by the legacy scheme. + public class LinuxGeneratedMachineKey : ICryptoKeyNixSource { + public const string KeyFileName = "config-encryption.key"; + public const string LegacyKeyFileName = "machinekey"; + + public const string LegacyKeyFilePath = "/etc/octopus/" + LegacyKeyFileName; + + // Kept apart from /etc/octopus so that a copy of the configuration does not also carry the key that decrypts it. + public const string DefaultKeysDirectory = "/var/octopus/tentacle/keys"; + + static string KeysDirectory + => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory) is { Length: > 0 } directory ? directory : DefaultKeysDirectory; + readonly ISystemLog log; readonly IOctopusFileSystem fileSystem; + (byte[] Key, byte[] IV)? loaded; - static string FileName => - KubernetesSupportDetection.IsRunningAsKubernetesAgent - //if we are running in K8S, we want to save the machine key to the home directory, which is likely on a network drives - ? Path.Combine(Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleHome)!, "machinekey") - : "/etc/octopus/machinekey"; - - public LinuxGeneratedMachineKey(ISystemLog log, IOctopusFileSystem fileSystem) + public LinuxGeneratedMachineKey(ISystemLog log, IOctopusFileSystem fileSystem, string keyFilePath) { this.log = log; this.fileSystem = fileSystem; + KeyFilePath = keyFilePath; + } + + public string KeyFilePath { get; } + + public string KeyDirectory => LinuxDirectoryOf(KeyFilePath); + + public static string KeyFilePathFor(string instanceName) + { + if (string.IsNullOrWhiteSpace(instanceName) + || instanceName.IndexOfAny(new[] { '/', '\\', '\0' }) >= 0 + || instanceName == "." + || instanceName == "..") + { + throw new ArgumentException($"The instance name `{instanceName}` cannot be used as a key directory name.", nameof(instanceName)); + } + + return JoinLinuxPath(JoinLinuxPath(KeysDirectory, instanceName), KeyFileName); } - void Generate() + public static string LegacyKeyFilePathForThisHost + => KubernetesSupportDetection.IsRunningAsKubernetesAgent + ? JoinLinuxPath(Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleHome)!, LegacyKeyFileName) + : LegacyKeyFilePath; + + public (byte[] Key, byte[] IV) Load() + => TryLoad() ?? throw new InvalidOperationException($"There is no machine key file at `{KeyFilePath}`."); + + public (byte[] Key, byte[] IV)? TryLoad() { - log.Verbose("Machine key file does not yet exist. Generating key file that will be used to encrypt data on this machine"); - var aes = Aes.Create(); + if (loaded.HasValue) + { + return loaded; + } + + if (!fileSystem.FileExists(KeyFilePath)) + { + return null; + } + + loaded = LoadFromFile(KeyFilePath); + return loaded; + } + + // Only the configuration upgrade creates the key, so that it can then give the key to the configuration's owner. + public void CreateIfMissing() + { + if (fileSystem.FileExists(KeyFilePath)) + { + return; + } + + using var aes = Aes.Create(); + aes.KeySize = 256; aes.GenerateIV(); aes.GenerateKey(); var raw = Convert.ToBase64String(aes.Key) + "." + Convert.ToBase64String(aes.IV); - if (!fileSystem.FileExists(Path.GetDirectoryName(FileName)!)) - fileSystem.CreateDirectory(Path.GetDirectoryName(FileName)!); + fileSystem.EnsureDirectoryExists(KeyDirectory); - fileSystem.WriteAllText(FileName, raw); + // Several instances starting at once after an upgrade must all end up with the same key. + if (!fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(KeyFilePath, Encoding.ASCII.GetBytes(raw))) + { + log.Verbose($"Another process created the machine key file `{KeyFilePath}` first; using its key."); + return; + } + + log.Info($"Generated a new machine key at `{KeyFilePath}`. Back it up with the configuration file it protects: the configuration cannot be decrypted without it."); } - (byte[] Key, byte[] IV) LoadFromFile() + (byte[] Key, byte[] IV) LoadFromFile(string path) { + string contents; try { - var content = fileSystem.ReadAllText(FileName).Split('.'); + contents = fileSystem.ReadAllText(path); + } + catch (UnauthorizedAccessException e) + { + var user = Environment.UserName; + var directory = LinuxDirectoryOf(path); + throw new InvalidOperationException($"The machine key file `{path}` exists but the user Tentacle is running as ({user}) cannot read it. " + + $"It must be owned by and readable only by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {path}`.", e); + } + + try + { + var content = contents.Split('.'); var key = Convert.FromBase64String(content[0]); var iv = Convert.FromBase64String(content[1]); + if (key.Length == 0) + { + throw new FormatException("The key is empty."); + } return (key, iv); } catch (Exception ex) when (ex is FormatException || ex is IndexOutOfRangeException) { - throw new InvalidOperationException($"Machine key file at `{FileName}` is corrupt and cannot be loaded. " - + $"If this file previously contained a valid key to encrypt data, that data may no longer be retrievable." - + $"Remove the file `{FileName}` and allow Octopus to regenerate the key."); + throw new InvalidOperationException($"Machine key file at `{path}` is corrupt and cannot be loaded. " + + "If this file previously contained a valid key to encrypt data, that data may no longer be retrievable. " + + $"Remove the file `{path}` and allow Octopus to regenerate the key."); } } - public (byte[] Key, byte[] IV) Load() + // Always Linux paths, even when unit tests run on Windows. + static string JoinLinuxPath(string directory, string fileName) + => directory.EndsWith("/", StringComparison.Ordinal) ? directory + fileName : directory + "/" + fileName; + + static string LinuxDirectoryOf(string path) { - if (!fileSystem.FileExists(FileName)) - Generate(); - return LoadFromFile(); + var lastSeparator = path.LastIndexOf('/'); + return lastSeparator <= 0 ? "/" : path.Substring(0, lastSeparator); } } -} \ No newline at end of file +} diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs index 39a1bb049..0327f2d84 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs @@ -28,6 +28,11 @@ public LinuxMachineIdKey(IOctopusFileSystem fileSystem) { return (GetMachineId(), Iv); } + + public (byte[] Key, byte[] IV)? TryLoad() + { + return fileSystem.FileExists(FileName) ? Load() : null; + } byte[] GetMachineId() { diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs index c9d9427d1..5b2becc03 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs @@ -1,65 +1,230 @@ -using System; +using System; using System.Collections.Generic; +using System.Linq; using System.Security.Cryptography; using System.Text; using Octopus.Tentacle.Core.Diagnostics; namespace Octopus.Tentacle.Configuration.Crypto { + // Stored as $OctopusMachineKeyV1$base64(nonce || ciphertext || tag), AES-256-GCM with the prefix as associated data. + // Values without the prefix were written by earlier versions with AES-CBC and a fixed IV. public class LinuxMachineKeyEncryptor : IMachineKeyEncryptor { + // $ is not a base64 character, so a value without this prefix is unambiguously a legacy one. + public const string ProtectedValuePrefix = "$OctopusMachineKeyV1$"; + + const int KeySizeInBytes = 32; + const int NonceSizeInBytes = 12; + const int TagSizeInBytes = 16; + + static readonly byte[] AssociatedData = Encoding.ASCII.GetBytes(ProtectedValuePrefix); + + // A wrong legacy key passes the AES-CBC padding check about 1 time in 256; the garbage it yields is rarely valid UTF-8. + static readonly Encoding StrictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + readonly ISystemLog log; - readonly IEnumerable keySources; + readonly ICryptoKeyNixSource keySource; + readonly IReadOnlyList legacyKeySources; - public LinuxMachineKeyEncryptor(ISystemLog log, IEnumerable keySources) + public LinuxMachineKeyEncryptor(ISystemLog log, ICryptoKeyNixSource keySource, IEnumerable legacyKeySources) { this.log = log; - this.keySources = keySources; + this.keySource = keySource; + this.legacyKeySources = legacyKeySources.ToArray(); } + static bool IsLegacyCiphertext(string encrypted) + => !encrypted.StartsWith(ProtectedValuePrefix, StringComparison.Ordinal); + + public bool RequiresReEncryption(string encrypted) + => IsLegacyCiphertext(encrypted); + + // Until the configuration upgrade has created the key, values are written the way earlier versions wrote them. public string Encrypt(string raw) { - return IterateKeySourcesUntilCryptoSuccess(cipherKeys => + try + { + var currentKey = TryLoadCurrentKey(); + return currentKey == null ? EncryptLegacy(raw) : EncryptCurrent(currentKey, raw); + } + catch (Exception e) + { + throw new CryptographicException($"Unable to encrypt a value with the Tentacle machine key: {e.Message}", e); + } + } + + static string EncryptCurrent(byte[] key, string raw) + { + var plaintext = Encoding.UTF8.GetBytes(raw); + var payload = new byte[NonceSizeInBytes + plaintext.Length + TagSizeInBytes]; + using (var random = RandomNumberGenerator.Create()) + { + var nonce = new byte[NonceSizeInBytes]; + random.GetBytes(nonce); + Buffer.BlockCopy(nonce, 0, payload, 0, NonceSizeInBytes); + } + + Gcm.Encrypt(key, plaintext, payload, AssociatedData); + + return ProtectedValuePrefix + Convert.ToBase64String(payload); + } + + string EncryptLegacy(string raw) + { + var errors = new List(); + foreach (var source in legacyKeySources) + { + try + { + var (key, iv) = source.Load(); + using var aes = Aes.Create(); + using var encryptor = aes.CreateEncryptor(key, iv); + var plaintext = Encoding.UTF8.GetBytes(raw); + return Convert.ToBase64String(encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length)); + } + catch (Exception e) + { + log.Verbose(e.Message); + errors.Add(e); + } + } + + throw new AggregateException("There is no configuration encryption key yet, and none of the keys earlier versions used is available.", errors); + } + + byte[]? TryLoadCurrentKey() + { + try + { + var existing = keySource.TryLoad(); + return existing == null ? null : CheckSize(existing.Value.Key); + } + catch (Exception e) { - var (key, iv) = cipherKeys; - using var aes = Aes.Create(); - using var enc = aes.CreateEncryptor(key, iv); - var inBlock = Encoding.UTF8.GetBytes(raw); - var trans = enc.TransformFinalBlock(inBlock, 0, inBlock.Length); - return Convert.ToBase64String(trans); - }); + log.Verbose($"Unable to use the configuration encryption key, so using the key earlier versions used: {e.Message}"); + return null; + } } public string Decrypt(string encrypted) + => IsLegacyCiphertext(encrypted) + ? DecryptLegacy(encrypted) + : DecryptCurrent(encrypted); + + string DecryptCurrent(string encrypted) + { + try + { + var payload = Convert.FromBase64String(encrypted.Substring(ProtectedValuePrefix.Length)); + if (payload.Length < NonceSizeInBytes + TagSizeInBytes) + { + throw new FormatException("The encrypted value is too short to contain a nonce and an authentication tag."); + } + + var plaintext = Gcm.Decrypt(LoadCurrentKey(), payload, AssociatedData); + return StrictUtf8.GetString(plaintext); + } + catch (InvalidOperationException e) when (e.InnerException is UnauthorizedAccessException) + { + throw new CryptographicException(e.Message, e); + } + catch (Exception e) + { + // No fallback to the legacy keys: they could never have written a value with the prefix. + throw new CryptographicException("Unable to decrypt a value protected with the Tentacle machine key. " + + "Either the value has been altered, or the machine key file it was encrypted with has been replaced or removed. " + + $"Details: {e.Message}", e); + } + } + + byte[] LoadCurrentKey() + => CheckSize(keySource.Load().Key); + + static byte[] CheckSize(byte[] key) { - return IterateKeySourcesUntilCryptoSuccess(cipherKeys => + if (key.Length != KeySizeInBytes) { - var (key, iv) = cipherKeys; - using var aes = Aes.Create(); - using var dec = aes.CreateDecryptor(key, iv); - var fromBase = Convert.FromBase64String(encrypted); - var asd = dec.TransformFinalBlock(fromBase, 0, fromBase.Length); - return Encoding.UTF8.GetString(asd); - }); + throw new CryptographicException($"The machine key must be {KeySizeInBytes * 8} bits, but is {key.Length * 8}."); + } + return key; } - string IterateKeySourcesUntilCryptoSuccess(Func<(byte[] Key, byte[] IV), string> cipherOp) + string DecryptLegacy(string encrypted) { - var ex = new List(); - foreach (var source in keySources) + var errors = new List(); + foreach (var source in legacyKeySources) { try { - return cipherOp(source.Load()); + var (key, iv) = source.Load(); + using var aes = Aes.Create(); + using var decryptor = aes.CreateDecryptor(key, iv); + var payload = Convert.FromBase64String(encrypted); + var plaintext = decryptor.TransformFinalBlock(payload, 0, payload.Length); + return StrictUtf8.GetString(plaintext); } catch (Exception e) { log.Verbose(e.Message); - ex.Add(e); + errors.Add(e); } } - throw new AggregateException(ex); + throw new CryptographicException("Unable to decrypt a value that was protected by an earlier version of Tentacle with any of the keys it could have used. " + + "Earlier versions derived the key from /etc/machine-id, so this happens when the configuration was moved from another machine, " + + "or is on a volume mounted into a container whose image has since changed. " + + "If the machine-id it was written with is still available (for a container, `docker run --rm --entrypoint cat /etc/machine-id`), " + + "make it available read-only at /etc/machine-id for one start and Tentacle will re-encrypt the configuration with its own key. " + + "Otherwise run 'tentacle new-certificate' and re-establish trust with the Octopus Server, or restore the configuration file from a backup taken on the original machine.", + new AggregateException(errors)); + } + + // Only reachable on .NET (Core): the .NET Framework build only runs on Windows, which uses DPAPI instead. + static class Gcm + { + public static void Encrypt(byte[] key, byte[] plaintext, byte[] payload, byte[] associatedData) + { +#if NETFRAMEWORK + throw new PlatformNotSupportedException("The Linux machine key scheme is not available on .NET Framework."); +#else + EnsureSupported(); + using var aes = new AesGcm(key, TagSizeInBytes); + aes.Encrypt(payload.AsSpan(0, NonceSizeInBytes), + plaintext, + payload.AsSpan(NonceSizeInBytes, plaintext.Length), + payload.AsSpan(NonceSizeInBytes + plaintext.Length, TagSizeInBytes), + associatedData); +#endif + } + + public static byte[] Decrypt(byte[] key, byte[] payload, byte[] associatedData) + { +#if NETFRAMEWORK + throw new PlatformNotSupportedException("The Linux machine key scheme is not available on .NET Framework."); +#else + EnsureSupported(); + var ciphertextLength = payload.Length - NonceSizeInBytes - TagSizeInBytes; + var plaintext = new byte[ciphertextLength]; + using var aes = new AesGcm(key, TagSizeInBytes); + aes.Decrypt(payload.AsSpan(0, NonceSizeInBytes), + payload.AsSpan(NonceSizeInBytes, ciphertextLength), + payload.AsSpan(NonceSizeInBytes + ciphertextLength, TagSizeInBytes), + plaintext, + associatedData); + return plaintext; +#endif + } + +#if !NETFRAMEWORK + static void EnsureSupported() + { + if (!AesGcm.IsSupported) + { + throw new PlatformNotSupportedException("AES-GCM is not available on this platform."); + } + } +#endif } } -} \ No newline at end of file +} diff --git a/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs index b262d02c2..6a7db8cd4 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs @@ -1,49 +1,43 @@ using System; +using System.Collections.Generic; +using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Diagnostics; -using Octopus.Tentacle.Kubernetes; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Configuration.Crypto { - public class MachineKeyEncryptor : IMachineKeyEncryptor + public static class MachineKeyEncryptor { - public static readonly IMachineKeyEncryptor Current; + static readonly ISystemLog Log = new SystemLog(); - static MachineKeyEncryptor() - { - if (PlatformDetection.IsRunningOnWindows) - { - Current = new WindowsMachineKeyEncryptor(); - } - else - { - Current = LinuxEncryptor(); - } - } + public static IMachineKeyEncryptor ForKeyFile(IOctopusFileSystem fileSystem, string? keyFilePath) + => PlatformDetection.IsRunningOnWindows + ? new WindowsMachineKeyEncryptor() + : keyFilePath == null + ? CreateLinuxEncryptor(Log, fileSystem, new NoConfigurationEncryptionKey()) + : CreateLinuxEncryptor(Log, fileSystem, keyFilePath); - static IMachineKeyEncryptor LinuxEncryptor() + internal static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, string keyFilePath) + => CreateLinuxEncryptor(log, fileSystem, new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath)); + + static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, ICryptoKeyNixSource generatedKey) { - var log = new SystemLog(); - var filesystem = new OctopusPhysicalFileSystem(log); - // Sources to find the crypto IV+Key. We want to enforce trying to use the machine-key - // first but still fallback to the existing Octopus generated one if that doesnt work. - var keySources = new ICryptoKeyNixSource[] + // The keys earlier versions used, in the order they tried them. Only read, never created or changed. + var legacyKeySources = new List { - new LinuxMachineIdKey(filesystem), - new LinuxGeneratedMachineKey(log, filesystem) + new LinuxMachineIdKey(fileSystem), + new LinuxGeneratedMachineKey(log, fileSystem, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost) }; - return new LinuxMachineKeyEncryptor(log, keySources); + return new LinuxMachineKeyEncryptor(log, generatedKey, legacyKeySources); } - MachineKeyEncryptor() + class NoConfigurationEncryptionKey : ICryptoKeyNixSource { - } + public (byte[] Key, byte[] IV) Load() + => throw new InvalidOperationException("The configuration encryption key for this configuration is not available. Register the configuration with `create-instance --instance `."); - public string Encrypt(string raw) - => Current.Encrypt(raw); - - public string Decrypt(string encrypted) - => Current.Decrypt(encrypted); + public (byte[] Key, byte[] IV)? TryLoad() => null; + } } -} \ No newline at end of file +} diff --git a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs index a48df445c..b1e8ff781 100644 --- a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs @@ -1,4 +1,5 @@ using System; +using System.Security.Cryptography; using Newtonsoft.Json; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Configuration.Instances; @@ -8,10 +9,12 @@ namespace Octopus.Tentacle.Configuration public abstract class FlatDictionaryKeyValueStore : DictionaryKeyValueStore, IAggregatableKeyValueStore { protected readonly JsonSerializerSettings JsonSerializerSettings; + protected readonly IMachineKeyEncryptor Encryptor; - protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSettings, bool autoSaveOnSet = true, bool isWriteOnly = false) : base(autoSaveOnSet, isWriteOnly) + protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSettings, IMachineKeyEncryptor encryptor, bool autoSaveOnSet = true, bool isWriteOnly = false) : base(autoSaveOnSet, isWriteOnly) { JsonSerializerSettings = jsonSerializerSettings; + Encryptor = encryptor ?? throw new ArgumentNullException(nameof(encryptor)); } public override TData? Get(string name, TData? defaultValue = default, ProtectionLevel protectionLevel = ProtectionLevel.None) where TData : default @@ -19,6 +22,7 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti if (name == null) throw new ArgumentNullException(nameof(name)); string? valueAsString = null; + var decrypting = false; try { var data = Read(name); @@ -29,7 +33,11 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti return defaultValue; if (protectionLevel == ProtectionLevel.MachineKey) - data = MachineKeyEncryptor.Current.Decrypt(valueAsString); + { + decrypting = true; + data = Encryptor.Decrypt(valueAsString); + decrypting = false; + } if (typeof(TData) == typeof(string)) return (TData)data; @@ -42,6 +50,11 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti } catch (Exception e) { + // The console does not always print inner messages, and this one says how to recover. + if (decrypting) + { + throw new FormatException($"Unable to decrypt the protected configuration setting '{name}'. {e.Message}", e); + } if (protectionLevel == ProtectionLevel.None) throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'. Value was '{valueAsString}'.", e); throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'.", e); @@ -53,6 +66,7 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti if (name == null) throw new ArgumentNullException(nameof(name)); string? valueAsString = null; + var decrypting = false; try { var data = Read(name); @@ -63,7 +77,11 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti return (false, default!); if (protectionLevel == ProtectionLevel.MachineKey) - data = MachineKeyEncryptor.Current.Decrypt(valueAsString); + { + decrypting = true; + data = Encryptor.Decrypt(valueAsString); + decrypting = false; + } if (typeof(TData) == typeof(string)) return (true, (TData)data); @@ -76,6 +94,10 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti } catch (Exception e) { + if (decrypting) + { + throw new FormatException($"Unable to decrypt the protected configuration setting '{name}'. {e.Message}", e); + } if (protectionLevel == ProtectionLevel.None) throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'. Value was '{valueAsString}'.", e); throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'.", e); @@ -100,7 +122,7 @@ public override bool Set(string name, TData value, ProtectionLevel protec valueAsObject = JsonConvert.SerializeObject(value, JsonSerializerSettings); if (protectionLevel == ProtectionLevel.MachineKey && valueAsObject != null) - valueAsObject = MachineKeyEncryptor.Current.Encrypt((string)valueAsObject); + valueAsObject = EncryptWithoutDowngrading(name, (string)valueAsObject); Write(name, valueAsObject); if (AutoSaveOnSet) @@ -109,6 +131,16 @@ public override bool Set(string name, TData value, ProtectionLevel protec return true; } + string EncryptWithoutDowngrading(string name, string raw) + { + var encrypted = Encryptor.Encrypt(raw); + if (Encryptor.RequiresReEncryption(encrypted) && Read(name) is string previous && !string.IsNullOrWhiteSpace(previous) && !Encryptor.RequiresReEncryption(previous)) + { + throw new CryptographicException($"Unable to update the protected setting '{name}': it is protected with the configuration encryption key, which is not available. Make sure the key file exists and is readable."); + } + return encrypted; + } + protected virtual bool ValueNeedsToBeSerialized(ProtectionLevel protectionLevel, object valueAsObject) { //null would end up as "null" rather than empty diff --git a/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs index 790951c6f..e72ea0655 100644 --- a/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs @@ -1,16 +1,11 @@ using System; -using Newtonsoft.Json; -using Octopus.Tentacle.Configuration.Crypto; namespace Octopus.Tentacle.Configuration { public abstract class HierarchicalDictionaryKeyValueStore : DictionaryKeyValueStore { - readonly JsonSerializerSettings jsonSerializerSettings; - - protected HierarchicalDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSettings, bool autoSaveOnSet = true, bool isWriteOnly = false) : base(autoSaveOnSet, isWriteOnly) + protected HierarchicalDictionaryKeyValueStore(bool autoSaveOnSet = true, bool isWriteOnly = false) : base(autoSaveOnSet, isWriteOnly) { - this.jsonSerializerSettings = jsonSerializerSettings; } public override TData? Get(string name, TData? defaultValue, ProtectionLevel protectionLevel = ProtectionLevel.None) where TData : default @@ -30,12 +25,10 @@ public override bool Set(string name, TData value, ProtectionLevel protec var valueAsObject = (object)value; + // This store only ever backs `show-configuration` output, which is never read back by Tentacle, so there is + // no key it could sensibly be encrypted with. Refuse rather than write a secret somewhere nothing can decrypt. if (protectionLevel == ProtectionLevel.MachineKey) - { - if (!(valueAsObject is string)) - valueAsObject = JsonConvert.SerializeObject(value, jsonSerializerSettings); - valueAsObject = MachineKeyEncryptor.Current.Encrypt((string)valueAsObject); - } + throw new NotSupportedException($"{GetType().Name} cannot store {nameof(ProtectionLevel.MachineKey)} values; it is only used to display configuration."); Write(name, valueAsObject); if (AutoSaveOnSet) diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceConfiguration.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceConfiguration.cs index fdbfef4d1..c7fb6fabd 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceConfiguration.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceConfiguration.cs @@ -7,8 +7,10 @@ public ApplicationInstanceConfiguration( string? instanceName, string? configurationPath, IKeyValueStore? configuration, - IWritableKeyValueStore? writableConfiguration) + IWritableKeyValueStore? writableConfiguration, + string? keyFilePath = null) { + KeyFilePath = keyFilePath; InstanceName = instanceName; ConfigurationPath = configurationPath; Configuration = configuration; @@ -18,6 +20,9 @@ public ApplicationInstanceConfiguration( public string? ConfigurationPath { get; } public string? InstanceName { get; } + // The Linux configuration encryption key, or null when the instance has none. + public string? KeyFilePath { get; } + public IKeyValueStore? Configuration { get; } public IWritableKeyValueStore? WritableConfiguration { get; } diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs index 5179b2523..8ceeb90c0 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Linq; +using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Kubernetes; using Octopus.Tentacle.Kubernetes.Configuration; @@ -71,12 +72,46 @@ ApplicationInstanceConfiguration LoadInstance() { var appInstance = LocateApplicationPrimaryConfiguration(); - var (aggregatedKeyValueStore, writableConfig) = LoadConfigurationStore(appInstance); + var keyFilePath = KeyFilePathFor(appInstance); - return new ApplicationInstanceConfiguration(appInstance.instanceName, appInstance.configurationpath, aggregatedKeyValueStore, writableConfig); + var (aggregatedKeyValueStore, writableConfig) = LoadConfigurationStore(appInstance, keyFilePath); + + return new ApplicationInstanceConfiguration(appInstance.instanceName, appInstance.configurationpath, aggregatedKeyValueStore, writableConfig, keyFilePath); + } + + string? KeyFilePathFor((string? instanceName, string? configurationpath) appInstance) + { + if (PlatformDetection.IsRunningOnWindows) + { + return null; + } + + var name = appInstance.instanceName ?? RegisteredInstanceNameFor(appInstance.configurationpath); + return name == null ? null : LinuxGeneratedMachineKey.KeyFilePathFor(name); + } + + string? RegisteredInstanceNameFor(string? configurationPath) + { + if (configurationPath == null) + { + return null; + } + + try + { + var fullPath = fileSystem.GetFullPath(configurationPath); + return applicationInstanceStore.ListInstances() + .FirstOrDefault(i => string.Equals(fileSystem.GetFullPath(i.ConfigurationFilePath), fullPath, StringComparison.Ordinal)) + ?.InstanceName; + } + catch (Exception e) + { + log.Verbose(e, "Could not read the instance registry, treating the configuration as unregistered"); + return null; + } } - (IKeyValueStore, IWritableKeyValueStore) LoadConfigurationStore((string? instanceName, string? configurationpath) appInstance) + (IKeyValueStore, IWritableKeyValueStore) LoadConfigurationStore((string? instanceName, string? configurationpath) appInstance, string? keyFilePath) { if (appInstance is { instanceName: not null, configurationpath: null } && KubernetesSupportDetection.IsRunningAsKubernetesAgent) @@ -89,7 +124,7 @@ ApplicationInstanceConfiguration LoadInstance() EnsureConfigurationExists(appInstance.instanceName, appInstance.configurationpath); log.Verbose($"Loading configuration from {appInstance.configurationpath}"); - var writable = new XmlFileKeyValueStore(fileSystem, appInstance.configurationpath!); + var writable = new XmlFileKeyValueStore(fileSystem, appInstance.configurationpath!, keyFilePath: keyFilePath); return (ContributeAdditionalConfiguration(writable), writable); } diff --git a/source/Octopus.Tentacle/Configuration/JsonHierarchicalKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/JsonHierarchicalKeyValueStore.cs index 771924bb9..2cccd5e2b 100644 --- a/source/Octopus.Tentacle/Configuration/JsonHierarchicalKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/JsonHierarchicalKeyValueStore.cs @@ -8,7 +8,7 @@ public abstract class JsonHierarchicalKeyValueStore : HierarchicalDictionaryKeyV { protected readonly JsonSerializerSettings JsonSerializerSettings; - protected JsonHierarchicalKeyValueStore(bool autoSaveOnSet, JsonSerializerSettings settings, bool isWriteOnly = false) : base(settings, autoSaveOnSet, isWriteOnly) + protected JsonHierarchicalKeyValueStore(bool autoSaveOnSet, JsonSerializerSettings settings, bool isWriteOnly = false) : base(autoSaveOnSet, isWriteOnly) { JsonSerializerSettings = settings; } diff --git a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs new file mode 100644 index 000000000..05cf2ebfd --- /dev/null +++ b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs @@ -0,0 +1,194 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Configuration +{ + public interface ITentacleConfigurationUpgrade + { + // Creates the configuration encryption key if it is missing, and gives it to the configuration's owner when running as root. + void PrepareKey(); + + // As PrepareKey, but fails when the key cannot be created. + void CreateKey(); + + // Prepares the key, then re-encrypts protected settings written with the keys earlier versions used. + void Run(); + + // As Run, but fails when the key cannot be created or a setting cannot be re-encrypted. + void RunOrThrow(); + } + + // Until Run succeeds, Tentacle keeps working on the keys earlier versions used. + public class TentacleConfigurationUpgrade : ITentacleConfigurationUpgrade + { + public static readonly IReadOnlyList ProtectedSettingNames = new[] + { + TentacleConfiguration.CertificateSettingName, + ProxyConfiguration.ProxyPasswordSettingName, + PollingProxyConfiguration.ProxyPasswordSettingName + }; + + const string StillOnLegacyKeys = "so the configuration is still protected by the key earlier versions used. Tentacle will keep working and try again the next time it starts."; + + readonly IApplicationInstanceSelector instanceSelector; + readonly IOctopusFileSystem fileSystem; + readonly ISystemLog log; + + public TentacleConfigurationUpgrade(IApplicationInstanceSelector instanceSelector, IOctopusFileSystem fileSystem, ISystemLog log) + { + this.instanceSelector = instanceSelector; + this.fileSystem = fileSystem; + this.log = log; + } + + public void PrepareKey() + { + try + { + TryPrepareKey(); + } + catch (Exception e) + { + log.Warn(e, "Unable to prepare the configuration encryption key, " + StillOnLegacyKeys); + } + } + + public void CreateKey() + => TryPrepareKey(); + + public void Run() + { + try + { + RunOrThrow(); + } + catch (Exception e) + { + log.Warn(e, "Unable to move the configuration to its own encryption key, " + StillOnLegacyKeys); + } + } + + public void RunOrThrow() + { +#if NET + var prepared = TryPrepareKey(); + if (prepared == null) + { + return; + } + + var (key, store) = prepared.Value; + key.Load(); + foreach (var name in ProtectedSettingNames) + { + if (store.ReEncryptIfLegacy(name)) + { + log.Info($"Re-encrypted the protected setting '{name}' with the configuration encryption key."); + } + } +#endif + } + +#if NET + (LinuxGeneratedMachineKey Key, XmlFileKeyValueStore Store)? TryPrepareKey() + { + if (OperatingSystem.IsWindows()) + { + return null; + } + + // Only the file-backed store has a legacy scheme; the Kubernetes agent's ConfigMap store does not. + var instance = instanceSelector.Current; + if (!(instance.WritableConfiguration is XmlFileKeyValueStore store) || instance.ConfigurationPath == null || !File.Exists(instance.ConfigurationPath)) + { + return null; + } + + if (instance.KeyFilePath == null) + { + log.Warn($"The instance using `{instance.ConfigurationPath}` is not in the instance registry, so its configuration stays protected by the key earlier versions used. " + + "Register it with `create-instance --instance --config ` to upgrade it."); + return null; + } + + var key = new LinuxGeneratedMachineKey(log, fileSystem, instance.KeyFilePath); + key.CreateIfMissing(); + + var configurationOwner = UnixOwnership.OwnerOf(instance.ConfigurationPath); + UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyDirectory); + UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyFilePath); + + return (key, store); + } +#else + void TryPrepareKey() + { + } +#endif + +#if NET + static class UnixOwnership + { + const uint UnchangedGroup = uint.MaxValue; + + public static uint OwnerOf(string path) + { + return SystemNative_Stat(path, out var status) == 0 + ? status.Uid + : throw new IOException($"Unable to find the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}"); + } + + public static void GiveToIfRoot(uint owner, string path) + { + if (geteuid() != 0 || OwnerOf(path) == owner) + { + return; + } + + if (lchown(path, owner, UnchangedGroup) != 0) + { + throw new IOException($"Unable to change the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}"); + } + } + + [DllImport("libc")] + static extern uint geteuid(); + + [DllImport("libc", SetLastError = true)] + static extern int lchown(string path, uint owner, uint group); + + // The .NET runtime's own stat shim: one struct layout on every libc and architecture. + [DllImport("libSystem.Native", SetLastError = true)] + static extern int SystemNative_Stat(string path, out FileStatus output); + + [StructLayout(LayoutKind.Sequential)] + struct FileStatus + { + public int Flags; + public int Mode; + public uint Uid; + public uint Gid; + public long Size; + public long ATime; + public long ATimeNsec; + public long MTime; + public long MTimeNsec; + public long CTime; + public long CTimeNsec; + public long BirthTime; + public long BirthTimeNsec; + public long Dev; + public long RDev; + public long Ino; + public uint UserFlags; + } + } +#endif + } +} diff --git a/source/Octopus.Tentacle/Configuration/WindowsMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/WindowsMachineKeyEncryptor.cs index b527e5f85..d613aa17e 100644 --- a/source/Octopus.Tentacle/Configuration/WindowsMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/WindowsMachineKeyEncryptor.cs @@ -14,5 +14,8 @@ public string Encrypt(string raw) public string Decrypt(string encrypted) => Encoding.UTF8.GetString(ProtectedData.Unprotect(Convert.FromBase64String(encrypted), null, DataProtectionScope.LocalMachine)); #pragma warning restore CA1416 + + public bool RequiresReEncryption(string encrypted) + => false; } -} \ No newline at end of file +} diff --git a/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs index 2181b321c..841375f0b 100644 --- a/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Configuration @@ -13,12 +14,35 @@ public class XmlFileKeyValueStore : XmlKeyValueStore public XmlFileKeyValueStore(IOctopusFileSystem fileSystem, string configurationFile, bool autoSaveOnSet = true, - bool isWriteOnly = false) : base(autoSaveOnSet, isWriteOnly) + bool isWriteOnly = false, + IMachineKeyEncryptor? encryptor = null, + string? keyFilePath = null) : base(encryptor ?? MachineKeyEncryptor.ForKeyFile(fileSystem, keyFilePath), autoSaveOnSet, isWriteOnly) { this.fileSystem = fileSystem; this.configurationFile = fileSystem.GetFullPath(configurationFile); } + public bool ReEncryptIfLegacy(string name) + { + if (name == null) throw new ArgumentNullException(nameof(name)); + + var stored = Read(name) as string; + if (stored == null || string.IsNullOrWhiteSpace(stored) || !Encryptor.RequiresReEncryption(stored)) + { + return false; + } + + var reEncrypted = Encryptor.Encrypt(Encryptor.Decrypt(stored)); + + Write(name, reEncrypted); + if (AutoSaveOnSet) + { + Save(); + } + + return true; + } + protected override void LoadSettings(IDictionary settingsToFill) { if (!ExistsForReading()) diff --git a/source/Octopus.Tentacle/Configuration/XmlKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/XmlKeyValueStore.cs index 93f158d06..a67148176 100644 --- a/source/Octopus.Tentacle/Configuration/XmlKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/XmlKeyValueStore.cs @@ -5,12 +5,13 @@ using System.Text; using System.Xml; using System.Xml.Serialization; +using Octopus.Tentacle.Configuration.Crypto; namespace Octopus.Tentacle.Configuration { public abstract class XmlKeyValueStore : FlatDictionaryKeyValueStore { - protected XmlKeyValueStore(bool autoSaveOnSet, bool isWriteOnly = false) : base(JsonSerialization.GetDefaultSerializerSettings(), autoSaveOnSet, isWriteOnly) + protected XmlKeyValueStore(IMachineKeyEncryptor encryptor, bool autoSaveOnSet, bool isWriteOnly = false) : base(JsonSerialization.GetDefaultSerializerSettings(), encryptor, autoSaveOnSet, isWriteOnly) { } diff --git a/source/Octopus.Tentacle/Kubernetes/Crypto/KubernetesMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Kubernetes/Crypto/KubernetesMachineKeyEncryptor.cs index dbd165f47..a23d7fedc 100644 --- a/source/Octopus.Tentacle/Kubernetes/Crypto/KubernetesMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Kubernetes/Crypto/KubernetesMachineKeyEncryptor.cs @@ -44,6 +44,9 @@ public string Decrypt(string encrypted) return Encoding.UTF8.GetString(asd); } + public bool RequiresReEncryption(string encrypted) + => false; + [MemberNotNull(nameof(key), nameof(iv))] void EnsureMachineKeyAndIvLoaded() { diff --git a/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs b/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs index 960d0eaee..f2bb10ad5 100644 --- a/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs @@ -139,6 +139,11 @@ public void WriteAllText(string filePath, string contents) syncRetryPolicy.Execute(() => inner.WriteAllText(filePath, contents)); } + public bool AtomicCreateFileWithUserReadWriteAccessOnly(string filePath, byte[] contents) + { + return syncRetryPolicy.Execute(() => inner.AtomicCreateFileWithUserReadWriteAccessOnly(filePath, contents)); + } + public string ReadAllText(string scriptFile) { return syncRetryPolicy.Execute(() => inner.ReadAllText(scriptFile)); diff --git a/source/Octopus.Tentacle/Program.cs b/source/Octopus.Tentacle/Program.cs index f4c4d5f50..0362e177c 100644 --- a/source/Octopus.Tentacle/Program.cs +++ b/source/Octopus.Tentacle/Program.cs @@ -94,6 +94,7 @@ public override IContainer BuildContainer(StartUpInstanceRequest startUpInstance builder.RegisterCommand("version", "Show the Tentacle version information"); builder.RegisterCommand("livez", "Checks that the Tentacle agent process is alive (suitable for a Kubernetes liveness probe)."); builder.RegisterCommand("show-configuration", "Outputs the Tentacle configuration"); + builder.RegisterCommand("upgrade-configuration-encryption", "Creates this instance's configuration encryption key, gives it to the configuration's owner, and re-encrypts protected settings with it"); return builder.Build(); } diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs index 44d5033fa..c3bf502ca 100644 --- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs +++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs @@ -17,6 +17,7 @@ public class ServiceCommand : AbstractCommand readonly IApplicationInstanceSelector instanceSelector; readonly ServiceConfigurationState serviceConfigurationState; readonly IServiceConfigurator serviceConfigurator; + readonly Lazy configurationUpgrade; private readonly ISystemLog log; readonly string ServicePasswordEnvVar = "OCTOPUS_SERVICE_PASSWORD"; readonly string ServiceUsernameEnvVar = "OCTOPUS_SERVICE_USERNAME"; @@ -30,9 +31,11 @@ public ServiceCommand(ApplicationName applicationName, Assembly assemblyContainingService, IServiceConfigurator serviceConfigurator, ISystemLog log, - ILogFileOnlyLogger logFileOnlyLogger) + ILogFileOnlyLogger logFileOnlyLogger, + Lazy configurationUpgrade) : base(logFileOnlyLogger) { + this.configurationUpgrade = configurationUpgrade; this.applicationName = applicationName; this.instanceLocator = instanceLocator; this.instanceSelector = instanceSelector; @@ -124,6 +127,9 @@ protected override void Start() if (serviceConfigurationState.Install || serviceConfigurationState.Reconfigure) { ConfigurationFilePermissions.RestrictToServiceUser(instanceSelector.Current.ConfigurationPath, serviceConfigurationState.Username, log); + + // A non-root service cannot create its key under /var/octopus, so it is created here while running as root. + configurationUpgrade.Value.PrepareKey(); } } } diff --git a/testing/README.md b/testing/README.md index ff979962b..15d7b157d 100644 --- a/testing/README.md +++ b/testing/README.md @@ -26,7 +26,7 @@ The script runs in four stages, each of which can be skipped: |---|---| | `deb` | Builds the linux-x64 `.deb` via NUKE (`--target PackDebianPackage`) | | `image` | Builds the image with the same `docker-compose.build.yml` command TeamCity runs | -| `smoke` | Asserts the image's contents and behaviour - base image, .NET runtime dependencies, docker-in-docker, entrypoint guards, labels | +| `smoke` | Asserts the image's contents and behaviour - base image, .NET runtime dependencies, docker-in-docker, entrypoint guards, labels - and upgrades a configuration written by the previous image ([`test-config-encryption-upgrade.sh`](./docker-linux/test-config-encryption-upgrade.sh)) | | `e2e` | Stands up SQL Server and an Octopus Server, then registers a listening and a polling Tentacle built from the fresh image | ``` @@ -42,6 +42,14 @@ The script runs in four stages, each of which can be skipped: The `e2e` stage needs an Octopus Server licence, because an unlicensed server enforces a limit of 0 targets and no Tentacle can register. Set `OCTOPUS_SERVER_BASE64_LICENSE`, or let the script read a development licence from 1Password when run interactively. Without one, the stage still verifies configuration and server connectivity up to the licence refusal. Pass `--no-1password` anywhere `op` must not run. +## Linux-only unit tests + +Tests marked `[LinuxTest]` are skipped on macOS and Windows. [`run-linux-unit-tests-in-docker.sh`](./run-linux-unit-tests-in-docker.sh) runs them in a .NET SDK container for the host's architecture, as root and then as a non-root user: + +``` +./testing/run-linux-unit-tests-in-docker.sh [dotnet test filter] +``` + ## Linux Packages Use [`linux-packages/test-packages-on-distros.sh`](./linux-packages/test-packages-on-distros.sh) to run NUKE's `TestLinuxPackages` target locally. That target installs the built `.deb`/`.rpm` on every distribution in the matrix in `build/Build.Tests.cs` and checks the installed Tentacle reports the expected version. diff --git a/testing/docker-linux/build-and-test-linux-docker-image.sh b/testing/docker-linux/build-and-test-linux-docker-image.sh index 78fd391a2..ca462c860 100755 --- a/testing/docker-linux/build-and-test-linux-docker-image.sh +++ b/testing/docker-linux/build-and-test-linux-docker-image.sh @@ -410,6 +410,13 @@ if [[ $SKIP_SMOKE -eq 0 ]]; then NOSERVER_OUT=$(docker run --rm --platform "$PLATFORM" -e ACCEPT_EULA=Y -e ServerApiKey=API-FAKE "$IMAGE" 2>&1 || true) assert_contains "container refuses to start without ServerUrl" "$NOSERVER_OUT" "Please specify an Octopus Server" + + # --- configuration encryption upgrade ------------------------------------ + if UPGRADE_OUT=$("$REPO_DIR/testing/docker-linux/test-config-encryption-upgrade.sh" "$IMAGE" 2>&1); then + pass "configuration from the previous image upgrades to the generated key" + else + fail "configuration from the previous image upgrades to the generated key" "$UPGRADE_OUT" + fi fi ############################################################################### diff --git a/testing/docker-linux/test-config-encryption-upgrade.sh b/testing/docker-linux/test-config-encryption-upgrade.sh new file mode 100755 index 000000000..c43cd9c72 --- /dev/null +++ b/testing/docker-linux/test-config-encryption-upgrade.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# +# Upgrades a Tentacle configuration written by a previous image, whose key came from its /etc/machine-id, to a new +# image on the same /etc/octopus and key volumes, following the recovery steps in docker/readme.md. +# +# Usage: ./testing/docker-linux/test-config-encryption-upgrade.sh [previous image] +# +set -euo pipefail + +NEW_IMAGE=$1 +PREVIOUS_IMAGE=${2:-octopusdeploy/tentacle:latest} +VOLUME="tentacle-config-upgrade-$$" +KEYS_VOLUME="tentacle-keys-upgrade-$$" +WORK_DIR=$(mktemp -d) +trap 'docker volume rm -f "$VOLUME" "$KEYS_VOLUME" >/dev/null; rm -rf "$WORK_DIR"' EXIT + +FAILURES=0 +check() { + if [[ "$2" == "$3" ]]; then echo "PASS $1"; else echo "FAIL $1: expected '$3', got '$2'"; FAILURES=$((FAILURES + 1)); fi +} + +in_container() { + local image=$1 command=$2 + shift 2 + docker run --rm -v "$VOLUME:/etc/octopus" -v "$KEYS_VOLUME:/var/octopus/tentacle/keys" "$@" --entrypoint bash "$image" -c "$command" 2>&1 +} + +in_container "$PREVIOUS_IMAGE" 'tentacle create-instance --instance Tentacle --config /etc/octopus/tentacle.config >/dev/null && tentacle new-certificate --instance Tentacle >/dev/null' +THUMBPRINT=$(in_container "$PREVIOUS_IMAGE" 'tentacle show-thumbprint --instance Tentacle') +in_container "$PREVIOUS_IMAGE" 'cat /etc/machine-id' > "$WORK_DIR/machine-id" + +OUTPUT=$(in_container "$NEW_IMAGE" 'tentacle show-thumbprint --instance Tentacle' || true) +check "the new image cannot decrypt without the previous machine-id" \ + "$(grep -c 'docker run --rm --entrypoint cat /etc/machine-id' <<<"$OUTPUT")" "1" + +OUTPUT=$(in_container "$NEW_IMAGE" 'timeout 30 tentacle run --instance Tentacle' -v "$WORK_DIR/machine-id:/etc/machine-id:ro" || true) +check "the agent re-encrypts with the previous machine-id mounted" \ + "$(grep -c "Re-encrypted the protected setting 'Tentacle.Certificate'" <<<"$OUTPUT")" "1" + +check "the certificate carries the versioned prefix" \ + "$(in_container "$NEW_IMAGE" 'grep -cF "key=\"Tentacle.Certificate\">\$OctopusMachineKeyV1\$" /etc/octopus/tentacle.config')" "1" +check "the key is owner-only" "$(in_container "$NEW_IMAGE" 'stat -c %a /var/octopus/tentacle/keys/Tentacle/config-encryption.key')" "600" +check "the key is not beside the configuration" "$(in_container "$NEW_IMAGE" 'test -e /etc/octopus/config-encryption.key && echo present || echo absent')" "absent" +check "the thumbprint is unchanged without the previous machine-id" "$(in_container "$NEW_IMAGE" 'tentacle show-thumbprint --instance Tentacle')" "$THUMBPRINT" + +OUTPUT=$(in_container "$NEW_IMAGE" 'timeout 30 tentacle run --instance Tentacle' || true) +check "the agent starts again without the previous machine-id" "$(grep -c 'Unable to decrypt' <<<"$OUTPUT")" "0" + +exit $((FAILURES > 0)) diff --git a/testing/run-linux-unit-tests-in-docker.sh b/testing/run-linux-unit-tests-in-docker.sh new file mode 100755 index 000000000..21ad61ed2 --- /dev/null +++ b/testing/run-linux-unit-tests-in-docker.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# +# Runs Linux-only unit tests in a .NET SDK container for this host's architecture, first as root and then as a +# non-root user. +# +# Usage: ./testing/run-linux-unit-tests-in-docker.sh [dotnet test filter] +# +set -euo pipefail + +REPO_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +FILTER=${1:-FullyQualifiedName~Octopus.Tentacle.Tests.Configuration} +case "$(uname -m)" in + arm64|aarch64) PLATFORM=linux/arm64 ;; + *) PLATFORM=linux/amd64 ;; +esac + +docker run --rm --platform "$PLATFORM" \ + -v "$REPO_DIR:/src:ro" \ + -e FILTER="$FILTER" \ + -e NUGET_PACKAGES=/work/.nuget-packages \ + mcr.microsoft.com/dotnet/sdk:10.0 \ + bash -euc ' + mkdir /work + tar -C /src --exclude=./.git --exclude="*/bin" --exclude="*/obj" --exclude=./_artifacts -cf - . | tar -C /work -xf - + cd /work + project=source/Octopus.Tentacle.Tests/Octopus.Tentacle.Tests.csproj + + echo "==> as root" + dotnet test "$project" -f net10.0 --filter "$FILTER" + + echo "==> as a non-root user" + useradd --create-home tester + chown -R tester /work + su tester -c "cd /work && NUGET_PACKAGES=$NUGET_PACKAGES dotnet test $project -f net10.0 --no-build --filter \"$FILTER\"" + ' From d8b0dfc38045e288657962bead54c00ca6bfa65a Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 14:38:57 +1100 Subject: [PATCH 002/124] Clean up the Linux config encryption key change (#1352) * Split the per-instance configuration encryption key from the legacy machine key source * Do not fall back to legacy encryption when the configuration encryption key is unreadable * Remove duplicated legacy key and decryption error handling * Require callers to supply the encryptor when creating an XmlFileKeyValueStore * Reduce ITentacleConfigurationUpgrade to PrepareKey and Run, both throwing * Move Unix P/Invoke into UnixFile * Simplify AtomicCreateFileWithUserReadWriteAccessOnly to one implementation * Resolve the instance's key path in Tentacle Manager instead of passing null * Rename WriteUserReadWriteOnly to CreateOwnerOnlyFile * Read the link error before another call can overwrite it * Move the upgrade's warn-and-continue handling into TentacleConfigurationUpgrade * Rename the configuration upgrade's Run to Upgrade --- .../InstanceConfigurationLoader.cs | 14 +- .../Util/FileSystem/IOctopusFileSystem.cs | 7 +- .../Util/OctopusPhysicalFileSystem.cs | 66 +++----- source/Octopus.Tentacle.Core/Util/UnixFile.cs | 81 +++++++++- .../Support/SharedTentacleCryptoState.cs | 20 ++- .../Commands/CreateInstanceCommandFixture.cs | 2 +- .../Commands/RunAgentCommandFixture.cs | 2 +- .../ApplicationInstanceSelectorFixture.cs | 2 +- .../LegacyCiphertextCompatibilityFixture.cs | 2 +- .../LinuxConfigurationFileSecurityFixture.cs | 14 +- .../Crypto/LinuxGeneratedMachineKeyFixture.cs | 4 +- .../Crypto/LinuxMachineKeyEncryptorFixture.cs | 6 +- .../TentacleConfigurationUpgradeFixture.cs | 34 ++-- ...XmlFileKeyValueStoreReEncryptionFixture.cs | 2 +- .../Support/TestMachineKeyEncryptor.cs | 14 +- .../Commands/CreateInstanceCommand.cs | 2 +- .../Commands/RunAgentCommand.cs | 2 +- .../UpgradeConfigurationEncryptionCommand.cs | 2 +- .../ConfigurationFilePermissions.cs | 12 +- .../Crypto/ConfigurationEncryptionKey.cs | 145 ++++++++++++++++++ .../Crypto/ICryptoKeyNixSource.cs | 2 - .../Crypto/LinuxGeneratedMachineKey.cs | 118 ++------------ .../Configuration/Crypto/LinuxMachineIdKey.cs | 5 - .../Crypto/LinuxMachineKeyEncryptor.cs | 95 +++++------- .../Crypto/MachineKeyEncryptor.cs | 24 +-- .../FlatDictionaryKeyValueStore.cs | 49 +++--- .../Instances/ApplicationInstanceSelector.cs | 4 +- .../TentacleConfigurationUpgrade.cs | 124 ++++----------- .../Configuration/XmlFileKeyValueStore.cs | 5 +- .../Startup/ServiceCommand.cs | 2 +- 30 files changed, 443 insertions(+), 418 deletions(-) create mode 100644 source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs diff --git a/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs b/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs index 29c1b0e8e..fb6e13adb 100644 --- a/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs +++ b/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs @@ -3,6 +3,7 @@ using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle; using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Configuration.Instances; using Octopus.Tentacle.Diagnostics; using Octopus.Tentacle.Util; @@ -52,13 +53,15 @@ public InstanceConfigurationLoader( public InstanceConfiguration LoadConfiguration(ApplicationInstanceRecord applicationInstanceRecord) { - var keyStore = new XmlFileKeyValueStore(fileSystem, applicationInstanceRecord.ConfigurationFilePath); + var encryptor = MachineKeyEncryptor.ForKeyFile(fileSystem, ConfigurationEncryptionKey.KeyFilePathFor(applicationInstanceRecord.InstanceName)); + var keyStore = new XmlFileKeyValueStore(fileSystem, applicationInstanceRecord.ConfigurationFilePath, encryptor); var selector = new SimpleApplicationInstanceSelectorForTentacleManager( instanceStrategies, fileSystem, systemLog, - applicationInstanceRecord.ConfigurationFilePath); + applicationInstanceRecord.ConfigurationFilePath, + encryptor); var homeConfig = new HomeConfiguration(selector); var loggingConfig = new LoggingConfiguration(homeConfig); @@ -80,18 +83,21 @@ class SimpleApplicationInstanceSelectorForTentacleManager : IApplicationInstance readonly ISystemLog log; readonly string configFilePath; + readonly IMachineKeyEncryptor encryptor; readonly bool canLoadCurrentInstance; public SimpleApplicationInstanceSelectorForTentacleManager( IApplicationConfigurationContributor[] instanceStrategies, IOctopusFileSystem fileSystem, ISystemLog log, - string configFilePath) + string configFilePath, + IMachineKeyEncryptor encryptor) { this.instanceStrategies = instanceStrategies; this.fileSystem = fileSystem; this.log = log; this.configFilePath = configFilePath; + this.encryptor = encryptor; try { @@ -120,7 +126,7 @@ ApplicationInstanceConfiguration LoadInstance() EnsureConfigurationExists(configurationPath); log.Verbose($"Loading configuration from {configurationPath}"); - var writable = new XmlFileKeyValueStore(fileSystem, configurationPath); + var writable = new XmlFileKeyValueStore(fileSystem, configurationPath, encryptor); return (ContributeAdditionalConfiguration(writable), writable); } diff --git a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs index 20a63e78c..f75710d0a 100644 --- a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs @@ -37,7 +37,12 @@ public interface IOctopusFileSystem void WriteAllBytes(string filePath, byte[] data); void WriteAllText(string filePath, string contents); - // Returns false, leaving the existing file untouched, if another process created it first. + /// + /// Creates a file at filePath with contents IF it doesn't exist. + /// The operation is as atomic as it can be for the FileSystem. + /// The resulting file has permissions 0600 for linux. + /// + /// True if this call created the file, false if it already existed, in which case the existing file is left untouched. bool AtomicCreateFileWithUserReadWriteAccessOnly(string filePath, byte[] contents); string ReadAllText(string scriptFile); diff --git a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs index a4fd34f6e..edeca02b6 100644 --- a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs @@ -250,53 +250,13 @@ public void WriteAllText(string path, string contents) File.WriteAllText(path, contents); } -#if NETFRAMEWORK - public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) - { - var temporaryPath = TemporaryPathBeside(path); - try - { - File.WriteAllBytes(temporaryPath, contents); - try - { - // MoveFile never replaces an existing file. - File.Move(temporaryPath, path); - return true; - } - catch (IOException) when (File.Exists(path)) - { - return false; - } - } - finally - { - DeleteIfExists(temporaryPath); - } - } -#else public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) { var temporaryPath = TemporaryPathBeside(path); try { CreateFileWithUserReadWriteAccessOnly(temporaryPath, contents); - - // File.Move(overwrite: false) checks then renames, so on Unix two racing processes could each keep their own file. - if (!OperatingSystem.IsWindows() && UnixFile.TryLinkWithoutReplacing(temporaryPath, path)) - { - return true; - } - if (File.Exists(path)) - { - return false; - } - - File.Move(temporaryPath, path, overwrite: false); - return true; - } - catch (IOException) when (File.Exists(path)) - { - return false; + return PublishWithoutReplacing(temporaryPath, path); } finally { @@ -306,6 +266,9 @@ public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] cont static void CreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) { +#if NETFRAMEWORK + using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); +#else var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None }; if (!OperatingSystem.IsWindows()) { @@ -313,10 +276,31 @@ static void CreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) } using var stream = new FileStream(path, options); +#endif stream.Write(contents, 0, contents.Length); stream.Flush(flushToDisk: true); } + + static bool PublishWithoutReplacing(string temporaryPath, string path) + { +#if !NETFRAMEWORK + if (!PlatformDetection.IsRunningOnWindows) + { + // Unlike File.Move, link(2) is atomic about not replacing: two racing processes cannot each keep their own file. + return UnixFile.TryLinkWithoutReplacing(temporaryPath, path); + } #endif + try + { + // MoveFile never replaces an existing file. + File.Move(temporaryPath, path); + return true; + } + catch (IOException) when (File.Exists(path)) + { + return false; + } + } static void DeleteIfExists(string path) { diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs index 040ea8d90..6b6227f08 100644 --- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -1,16 +1,93 @@ #if !NETFRAMEWORK +using System.IO; using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; namespace Octopus.Tentacle.Core.Util { - static class UnixFile + public static class UnixFile { + const uint UnchangedGroup = uint.MaxValue; + const int FileExistsError = 17; + // Unlike rename(2), link(2) never replaces an existing file. public static bool TryLinkWithoutReplacing(string existingPath, string newPath) - => link(existingPath, newPath) == 0; + { + if (link(existingPath, newPath) == 0) + { + return true; + } + + return Marshal.GetLastPInvokeError() == FileExistsError + ? false + : throw new IOException($"Unable to create `{newPath}`: {Marshal.GetLastPInvokeErrorMessage()}"); + } + + public static uint OwnerOf(string path) + { + return SystemNative_Stat(path, out var status) == 0 + ? status.Uid + : throw new IOException($"Unable to find the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}"); + } + + public static void SetOwnerIfRunningAsRoot(uint owner, string path) + { + if (geteuid() != 0 || OwnerOf(path) == owner) + { + return; + } + + if (lchown(path, owner, UnchangedGroup) != 0) + { + throw new IOException($"Unable to change the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}"); + } + } + + public static void GiveTo(SafeFileHandle file, uint owner) + { + if (fchown(file, owner, UnchangedGroup) != 0) + { + throw new IOException(Marshal.GetLastPInvokeErrorMessage()); + } + } [DllImport("libc", SetLastError = true)] static extern int link(string oldpath, string newpath); + + [DllImport("libc")] + static extern uint geteuid(); + + [DllImport("libc", SetLastError = true)] + static extern int lchown(string path, uint owner, uint group); + + [DllImport("libc", SetLastError = true)] + static extern int fchown(SafeFileHandle fd, uint owner, uint group); + + // The .NET runtime has no public API for a file's owner; its own stat shim has one struct layout on every libc and architecture. + [DllImport("libSystem.Native", SetLastError = true)] + static extern int SystemNative_Stat(string path, out FileStatus output); + + [StructLayout(LayoutKind.Sequential)] + struct FileStatus + { + public int Flags; + public int Mode; + public uint Uid; + public uint Gid; + public long Size; + public long ATime; + public long ATimeNsec; + public long MTime; + public long MTimeNsec; + public long CTime; + public long CTimeNsec; + public long BirthTime; + public long BirthTimeNsec; + public long Dev; + public long RDev; + public long Ino; + public uint UserFlags; + } } } #endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs index 502d3dcc2..0a52bdb51 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs @@ -1,6 +1,9 @@ using System; +using System.IO; using System.Linq; +using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; +using System.Text; using Octopus.Tentacle.CommonTestUtils; using Octopus.Tentacle.Configuration; using Octopus.Tentacle.Configuration.Crypto; @@ -74,10 +77,25 @@ static void CreateTheFallbackKeyEarlierVersionsShare(SystemLog log) } catch (InvalidOperationException) { - new LinuxGeneratedMachineKey(log, fileSystem, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost).CreateIfMissing(); + CreateLegacyMachineKeyIfMissing(fileSystem, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost); } } + static void CreateLegacyMachineKeyIfMissing(OctopusPhysicalFileSystem fileSystem, string path) + { + if (fileSystem.FileExists(path)) + { + return; + } + + using var aes = Aes.Create(); + aes.GenerateIV(); + aes.GenerateKey(); + var contents = Convert.ToBase64String(aes.Key) + "." + Convert.ToBase64String(aes.IV); + fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(path)!); + fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(path, Encoding.ASCII.GetBytes(contents)); + } + // A Tentacle only reuses the stored certificate when it comes back with its private key. // Otherwise it adds it to the store again, which is the concurrent write this avoids. static void VerifyTheStoreHoldsTheCertificateWithItsPrivateKey() diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs index 2b94a7b9c..c1356222d 100644 --- a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs @@ -27,7 +27,7 @@ public override void SetUp() [Test] public void ANamedInstanceFailsWhenItsKeyCannotBeCreated() { - configurationUpgrade.When(u => u.CreateKey()).Do(_ => throw new IOException("Permission denied")); + configurationUpgrade.When(u => u.PrepareKey()).Do(_ => throw new IOException("Permission denied")); Action start = () => Start("--instance=Tentacle", "--config=/etc/octopus/tentacle.config"); diff --git a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs index bd43cb327..0dbe2a71b 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs @@ -77,7 +77,7 @@ public void WhenCommandIsStartedThenTheConfigurationIsUpgradedBeforeHalibutStart // Assert Received.InOrder(() => { - configurationUpgrade.Run(); + configurationUpgrade.TryUpgrade(); halibut.Start(); }); } diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs index d297785c5..492df010a 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs @@ -108,7 +108,7 @@ public void GivenARegisteredInstanceUsesTheConfiguration_WhenRequestingConfigura new ApplicationInstanceRecord("Registered", filePath) }); - mock.Current.KeyFilePath.Should().Be(LinuxGeneratedMachineKey.KeyFilePathFor("Registered")); + mock.Current.KeyFilePath.Should().Be(ConfigurationEncryptionKey.KeyFilePathFor("Registered")); } [Test] diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs index 8eb4b7406..cd6a9a4bc 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs @@ -73,7 +73,7 @@ IMachineKeyEncryptor CreateEncryptorAsComposedInProduction(bool machineIdPresent fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(machineIdPresent); fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { MachineId }); - return MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, LinuxGeneratedMachineKey.KeyFilePathFor("Tentacle")); + return MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle")); } [TestCaseSource(nameof(WrittenWithTheMachineIdKey))] diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs index 2bfdd0dc1..b5f4d9b14 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs @@ -31,7 +31,7 @@ public class LinuxConfigurationFileSecurityFixture public void SetUp() { directory = Path.Combine(Path.GetTempPath(), "octopus-config-encryption-key-" + Guid.NewGuid()); - keyFilePath = Path.Combine(directory, LinuxGeneratedMachineKey.KeyFileName); + keyFilePath = Path.Combine(directory, ConfigurationEncryptionKey.KeyFileName); log = Substitute.For(); fileSystem = new OctopusPhysicalFileSystem(log); } @@ -49,16 +49,16 @@ public void TearDown() public void WhenTheKeyIsCreatedThenOnlyItsOwnerCanReadIt() { // Arrange - var keySource = new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath); + var keySource = new ConfigurationEncryptionKey(log, fileSystem, keyFilePath); // Act keySource.CreateIfMissing(); - var (key, iv) = keySource.Load(); + var key = keySource.Load(); // Assert File.Exists(keyFilePath).Should().BeTrue("the directory is created on demand, as it always was"); File.GetUnixFileMode(keyFilePath).Should().Be(OwnerReadWrite); - File.ReadAllText(keyFilePath).Should().Be(Convert.ToBase64String(key) + "." + Convert.ToBase64String(iv)); + File.ReadAllText(keyFilePath).Should().Be(Convert.ToBase64String(key)); Directory.GetFiles(directory).Should().ContainSingle("the temporary file the key is written to first is not left behind"); } @@ -72,9 +72,9 @@ public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() .Select(_ => Task.Run(() => { start.Wait(); - var keySource = new LinuxGeneratedMachineKey(log, new OctopusPhysicalFileSystem(log), keyFilePath); + var keySource = new ConfigurationEncryptionKey(log, new OctopusPhysicalFileSystem(log), keyFilePath); keySource.CreateIfMissing(); - return keySource.Load().Key; + return keySource.Load(); })) .ToArray(); @@ -83,7 +83,7 @@ public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() var keys = await Task.WhenAll(loads); // Assert - var onDisk = Convert.FromBase64String(File.ReadAllText(keyFilePath).Split('.')[0]); + var onDisk = Convert.FromBase64String(File.ReadAllText(keyFilePath)); keys.Should().AllSatisfy(k => k.Should().Equal(onDisk)); Directory.GetFiles(directory).Should().ContainSingle("no racer's temporary file is left behind"); } diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs index 4bf67d003..3be7b2b4b 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs @@ -53,7 +53,7 @@ public void GivenMachineIdFileIsValidLength_ThenReturnsKeys() [Test] public void KeyFileIsKeptPerInstanceOutsideTheConfigurationDirectory() { - LinuxGeneratedMachineKey.KeyFilePathFor("Tentacle").Should().Be("/var/octopus/tentacle/keys/Tentacle/config-encryption.key"); + ConfigurationEncryptionKey.KeyFilePathFor("Tentacle").Should().Be("/var/octopus/tentacle/keys/Tentacle/config-encryption.key"); } [TestCase("")] @@ -62,7 +62,7 @@ public void KeyFileIsKeptPerInstanceOutsideTheConfigurationDirectory() [TestCase("a\\b")] public void InstanceNamesThatAreNotASingleDirectoryNameAreRejected(string instanceName) { - Assert.Throws(() => LinuxGeneratedMachineKey.KeyFilePathFor(instanceName)); + Assert.Throws(() => ConfigurationEncryptionKey.KeyFilePathFor(instanceName)); } } } diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs index 4516297a7..5aee06c92 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs @@ -14,7 +14,7 @@ namespace Octopus.Tentacle.Tests.Configuration.Crypto public class LinuxMachineKeyEncryptorFixture { readonly ISystemLog systemLog = Substitute.For(); - readonly InMemoryCryptoKeyNixSource generatedKey = new(); + readonly ConfigurationEncryptionKey generatedKey = InMemoryConfigurationEncryptionKey.Create(); LinuxMachineKeyEncryptor CreateEncryptor(params ICryptoKeyNixSource[] legacyKeySources) => new(systemLog, generatedKey, legacyKeySources); @@ -38,9 +38,9 @@ public void WhenAValueIsEncryptedThenItIsVersionedAndDecrypts() public void WhenACurrentValueWasEncryptedWithAnotherKeyThenALegacyKeyIsNotTried() { // Arrange - var otherKey = new InMemoryCryptoKeyNixSource(); + var otherKey = InMemoryConfigurationEncryptionKey.Create(); var encryptedWithOtherKey = new LinuxMachineKeyEncryptor(systemLog, otherKey, Array.Empty()).Encrypt("FooBar"); - var encryptor = CreateEncryptor(otherKey); + var encryptor = CreateEncryptor(new InMemoryCryptoKeyNixSource()); // Act Action decrypt = () => encryptor.Decrypt(encryptedWithOtherKey); diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs index 5173f7fe1..249dcb482 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs @@ -52,13 +52,13 @@ public void TearDown() public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted() { // Arrange - var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName); + var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); var store = CreateStore(keyFilePath); store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); RawCertificate().Should().NotStartWith(LinuxMachineKeyEncryptor.ProtectedValuePrefix, "without a key, values are written the way earlier versions wrote them"); // Act - CreateUpgrade(store, keyFilePath).Run(); + CreateUpgrade(store, keyFilePath).Upgrade(); // Assert File.Exists(keyFilePath).Should().BeTrue(); @@ -71,7 +71,7 @@ public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted() public void WhenOnlyTheKeyIsPreparedThenItIsCreatedAndValuesStayLegacy() { // Arrange - var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName); + var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); var store = CreateStore(keyFilePath); store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); var legacyValue = RawCertificate(); @@ -86,37 +86,33 @@ public void WhenOnlyTheKeyIsPreparedThenItIsCreatedAndValuesStayLegacy() } [Test] - public void WhenTheKeyCannotBeCreatedThenTentacleKeepsWorkingOnTheLegacyKey() + public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() { // Arrange - var keyFilePath = Path.Combine(configurationFile, "not-a-directory", LinuxGeneratedMachineKey.KeyFileName); + var keyFilePath = Path.Combine(configurationFile, "not-a-directory", ConfigurationEncryptionKey.KeyFileName); var store = CreateStore(keyFilePath); store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); var legacyValue = RawCertificate(); // Act - CreateUpgrade(store, keyFilePath).Run(); - store.Set(ProxyConfiguration.ProxyPasswordSettingName, "secret", ProtectionLevel.MachineKey); + Action run = () => CreateUpgrade(store, keyFilePath).Upgrade(); // Assert - log.Received().Warn(Arg.Any(), Arg.Any()); + run.Should().Throw(); RawCertificate().Should().Be(legacyValue); - var reloaded = CreateStore(keyFilePath); - reloaded.Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); - reloaded.Get(ProxyConfiguration.ProxyPasswordSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be("secret"); } [Test] public void WhenTheConfigurationIsNotInTheRegistryThenNoKeyIsCreatedAndValuesStayLegacy() { // Arrange - var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName); + var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); var store = CreateStore(keyFilePath); store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); var legacyValue = RawCertificate(); // Act - CreateUpgrade(store, keyFilePath: null, instanceName: null).Run(); + CreateUpgrade(store, keyFilePath: null, instanceName: null).Upgrade(); // Assert File.Exists(keyFilePath).Should().BeFalse(); @@ -128,7 +124,7 @@ public void WhenTheConfigurationIsNotInTheRegistryThenNoKeyIsCreatedAndValuesSta public void UpgradeConfigurationEncryptionCreatesTheKeyAndReEncryptsLegacyValues() { // Arrange - var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName); + var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); var store = CreateStore(keyFilePath); store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); @@ -145,7 +141,7 @@ public void UpgradeConfigurationEncryptionCreatesTheKeyAndReEncryptsLegacyValues public void UpgradeConfigurationEncryptionFailsForAConfigurationNotInTheRegistry() { // Arrange - var store = CreateStore(Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName)); + var store = CreateStore(Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName)); store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); var legacyValue = RawCertificate(); @@ -161,11 +157,11 @@ public void UpgradeConfigurationEncryptionFailsForAConfigurationNotInTheRegistry public void AValueProtectedWithTheKeyIsNeverRewrittenWithALegacyKey() { // Arrange - var keyFilePath = Path.Combine(directory, "my-key", LinuxGeneratedMachineKey.KeyFileName); - new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath).CreateIfMissing(); + var keyFilePath = Path.Combine(directory, "my-key", ConfigurationEncryptionKey.KeyFileName); + new ConfigurationEncryptionKey(log, fileSystem, keyFilePath).CreateIfMissing(); CreateStore(keyFilePath).Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); var protectedValue = RawCertificate(); - var storeWithoutKey = CreateStore(Path.Combine(directory, "missing", LinuxGeneratedMachineKey.KeyFileName)); + var storeWithoutKey = CreateStore(Path.Combine(directory, "missing", ConfigurationEncryptionKey.KeyFileName)); // Act Action set = () => storeWithoutKey.Set(TentacleConfiguration.CertificateSettingName, "another certificate", ProtectionLevel.MachineKey); @@ -178,7 +174,7 @@ public void AValueProtectedWithTheKeyIsNeverRewrittenWithALegacyKey() readonly InMemoryCryptoKeyNixSource legacyKey = new(); XmlFileKeyValueStore CreateStore(string keyFilePath) - => new(fileSystem, configurationFile, encryptor: new LinuxMachineKeyEncryptor(log, new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath), new[] { legacyKey })); + => new(fileSystem, configurationFile, encryptor: new LinuxMachineKeyEncryptor(log, new ConfigurationEncryptionKey(log, fileSystem, keyFilePath), new[] { legacyKey })); TentacleConfigurationUpgrade CreateUpgrade(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle") => new(CreateSelector(store, keyFilePath, instanceName), fileSystem, log); diff --git a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs index a5e58c5df..c53a3983d 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs @@ -32,7 +32,7 @@ public void SetUp() fileSystem.OverwriteFile(configurationFile, @""); legacyKey = new InMemoryCryptoKeyNixSource(); - encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), new InMemoryCryptoKeyNixSource(), new[] { legacyKey }); + encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), new[] { legacyKey }); // Writes what an earlier version would have left in the file... legacyStore = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: new LegacySchemeEncryptor(legacyKey)); diff --git a/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs b/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs index 79adeab1e..9e13874bb 100644 --- a/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs @@ -4,6 +4,7 @@ using Octopus.Tentacle.Configuration; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Util; using PlatformDetection = Octopus.Tentacle.Util.PlatformDetection; namespace Octopus.Tentacle.Tests.Support @@ -14,7 +15,7 @@ public static class TestMachineKeyEncryptor { public static readonly IMachineKeyEncryptor Current = PlatformDetection.IsRunningOnWindows ? new WindowsMachineKeyEncryptor() - : new LinuxMachineKeyEncryptor(Substitute.For(), new InMemoryCryptoKeyNixSource(), Array.Empty()); + : new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), Array.Empty()); } public class InMemoryCryptoKeyNixSource : ICryptoKeyNixSource @@ -35,10 +36,17 @@ public InMemoryCryptoKeyNixSource() { return (Key, IV); } + } - public (byte[] Key, byte[] IV)? TryLoad() + public static class InMemoryConfigurationEncryptionKey + { + public static ConfigurationEncryptionKey Create() { - return Load(); + const string path = "/in-memory/config-encryption.key"; + var fileSystem = Substitute.For(); + fileSystem.FileExists(path).Returns(true); + fileSystem.ReadAllText(path).Returns(Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))); + return new ConfigurationEncryptionKey(Substitute.For(), fileSystem, path); } } } diff --git a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs index fa38b0e87..f1e1adef7 100644 --- a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs +++ b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs @@ -33,7 +33,7 @@ protected override void Start() instanceManager.CreateInstance(instanceName, config, home); } - configurationUpgrade.Value.CreateKey(); + configurationUpgrade.Value.PrepareKey(); } } } diff --git a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs index 3c282dcca..2c74704af 100644 --- a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs +++ b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs @@ -101,7 +101,7 @@ protected override void Start() return; } - configurationUpgrade.Value.Run(); + configurationUpgrade.Value.TryUpgrade(); var currentPath = typeof(RunAgentCommand).Assembly.FullLocalPath(); var exePath = PlatformDetection.IsRunningOnWindows diff --git a/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs b/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs index ef2b9e5f0..76e5121b7 100644 --- a/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs +++ b/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs @@ -42,7 +42,7 @@ protected override void Start() + $"Register it with `create-instance --instance --config {instance.ConfigurationPath}`, then run this command again."); } - configurationUpgrade.Value.RunOrThrow(); + configurationUpgrade.Value.Upgrade(); log.Info($"The configuration is protected with the encryption key `{instance.KeyFilePath}`."); } } diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs b/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs index 1db32e708..d0aa1afc4 100644 --- a/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs +++ b/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs @@ -4,9 +4,8 @@ using Octopus.Tentacle.Util; #if NET using System.Diagnostics; -using System.Runtime.InteropServices; using System.Runtime.Versioning; -using Microsoft.Win32.SafeHandles; +using Octopus.Tentacle.Core.Util; #endif namespace Octopus.Tentacle.Configuration @@ -16,7 +15,6 @@ static class ConfigurationFilePermissions { #if NET public const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite; - const uint UnchangedGroup = uint.MaxValue; #endif public static void CreateEmpty(IOctopusFileSystem fileSystem, string configurationPath, string contents) @@ -100,9 +98,8 @@ public static void RestrictToServiceUser(string? configurationPath, string? user using var stream = new FileStream(configurationPath, FileMode.Open, FileAccess.Read); File.SetUnixFileMode(stream.SafeFileHandle, OwnerOnly); - return fchown(stream.SafeFileHandle, userId.Value, UnchangedGroup) == 0 - ? null - : Marshal.GetLastPInvokeErrorMessage(); + UnixFile.GiveTo(stream.SafeFileHandle, userId.Value); + return null; } catch (Exception ex) { @@ -132,9 +129,6 @@ public static void RestrictToServiceUser(string? configurationPath, string? user return null; } } - - [DllImport("libc", SetLastError = true)] - static extern int fchown(SafeFileHandle fd, uint owner, uint group); #endif } } diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs new file mode 100644 index 000000000..6b25c530b --- /dev/null +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -0,0 +1,145 @@ +using System; +using System.Security.Cryptography; +using System.Text; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Core.Util; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Configuration.Crypto +{ + // The per-instance AES-256 key that protects a configuration file on Linux, stored as base64(key). + public class ConfigurationEncryptionKey + { + public const string KeyFileName = "config-encryption.key"; + + // Kept apart from /etc/octopus so that a copy of the configuration does not also carry the key that decrypts it. + public const string DefaultKeysDirectory = "/var/octopus/tentacle/keys"; + + const int KeySizeInBytes = 32; + + static string KeysDirectory + => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory) is { Length: > 0 } directory ? directory : DefaultKeysDirectory; + + readonly ISystemLog log; + readonly IOctopusFileSystem fileSystem; + byte[]? loaded; + + // A null path means the configuration has no key, for example because it is not registered as an instance. + public ConfigurationEncryptionKey(ISystemLog log, IOctopusFileSystem fileSystem, string? keyFilePath) + { + this.log = log; + this.fileSystem = fileSystem; + KeyFilePath = keyFilePath; + } + + public string? KeyFilePath { get; } + + public string? KeyDirectory => KeyFilePath == null ? null : LinuxDirectoryOf(KeyFilePath); + + public static string KeyFilePathFor(string instanceName) + { + if (string.IsNullOrWhiteSpace(instanceName) + || instanceName.IndexOfAny(new[] { '/', '\\', '\0' }) >= 0 + || instanceName == "." + || instanceName == "..") + { + throw new ArgumentException($"The instance name `{instanceName}` cannot be used as a key directory name.", nameof(instanceName)); + } + + return JoinLinuxPath(JoinLinuxPath(KeysDirectory, instanceName), KeyFileName); + } + + public byte[] Load() + => TryLoad() ?? throw new InvalidOperationException(KeyFilePath == null + ? "The configuration encryption key for this configuration is not available. Register the configuration with `create-instance --instance `." + : $"The configuration encryption key file `{KeyFilePath}` does not exist, so the values it protected cannot be decrypted. Restore it from a backup."); + + public byte[]? TryLoad() + { + if (loaded != null) + { + return loaded; + } + + if (KeyFilePath == null || !fileSystem.FileExists(KeyFilePath)) + { + return null; + } + + loaded = LoadFromFile(KeyFilePath); + return loaded; + } + + // Only the configuration upgrade creates the key, so that it can then give the key to the configuration's owner. + public void CreateIfMissing() + { + var path = KeyFilePath ?? throw new InvalidOperationException("There is no key file path to create the configuration encryption key at."); + if (fileSystem.FileExists(path)) + { + return; + } + + var raw = Convert.ToBase64String(RandomKey()); + + fileSystem.EnsureDirectoryExists(KeyDirectory!); + + // Several instances starting at once after an upgrade must all end up with the same key. + if (!fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(path, Encoding.ASCII.GetBytes(raw))) + { + log.Verbose($"Another process created the configuration encryption key `{path}` first; using its key."); + return; + } + + log.Info($"Generated a new configuration encryption key at `{path}`. Back it up with the configuration file it protects: the configuration cannot be decrypted without it."); + } + + static byte[] RandomKey() + { + var key = new byte[KeySizeInBytes]; + using var random = RandomNumberGenerator.Create(); + random.GetBytes(key); + return key; + } + + byte[] LoadFromFile(string path) + { + string contents; + try + { + contents = fileSystem.ReadAllText(path); + } + catch (UnauthorizedAccessException e) + { + var user = Environment.UserName; + var directory = LinuxDirectoryOf(path); + throw new InvalidOperationException($"The configuration encryption key file `{path}` exists but the user Tentacle is running as ({user}) cannot read it. " + + $"It must be owned by and readable only by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {path}`.", e); + } + + try + { + var key = Convert.FromBase64String(contents.Trim()); + if (key.Length == KeySizeInBytes) + { + return key; + } + } + catch (FormatException) + { + } + + throw new InvalidOperationException($"The configuration encryption key file `{path}` is corrupt: it must hold a base64-encoded {KeySizeInBytes * 8}-bit key. " + + "Restore it from a backup; values encrypted with a lost key cannot be recovered."); + } + + // Always Linux paths, even when unit tests run on Windows. + static string JoinLinuxPath(string directory, string fileName) + => directory.EndsWith("/", StringComparison.Ordinal) ? directory + fileName : directory + "/" + fileName; + + static string LinuxDirectoryOf(string path) + { + var lastSeparator = path.LastIndexOf('/'); + return lastSeparator <= 0 ? "/" : path.Substring(0, lastSeparator); + } + } +} diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs b/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs index 43c5d891c..0cd958ea2 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs @@ -5,7 +5,5 @@ namespace Octopus.Tentacle.Configuration.Crypto public interface ICryptoKeyNixSource { (byte[] Key, byte[] IV) Load(); - - (byte[] Key, byte[] IV)? TryLoad(); } } \ No newline at end of file diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs index 438483cf9..aac2ffc1f 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs @@ -1,130 +1,42 @@ using System; -using System.Security.Cryptography; -using System.Text; -using Octopus.Tentacle.Core.Diagnostics; +using System.IO; using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Configuration.Crypto { - // The legacy machinekey file was world-readable, so it is only ever read to decrypt what earlier versions wrote and is - // never adopted as the current key. Both files are base64(key).base64(iv); the IV is only used by the legacy scheme. + // The key file earlier versions generated on first use, as base64(key).base64(iv). It is only read, to decrypt what they wrote. public class LinuxGeneratedMachineKey : ICryptoKeyNixSource { - public const string KeyFileName = "config-encryption.key"; public const string LegacyKeyFileName = "machinekey"; public const string LegacyKeyFilePath = "/etc/octopus/" + LegacyKeyFileName; - // Kept apart from /etc/octopus so that a copy of the configuration does not also carry the key that decrypts it. - public const string DefaultKeysDirectory = "/var/octopus/tentacle/keys"; - - static string KeysDirectory - => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory) is { Length: > 0 } directory ? directory : DefaultKeysDirectory; - - readonly ISystemLog log; readonly IOctopusFileSystem fileSystem; - (byte[] Key, byte[] IV)? loaded; - public LinuxGeneratedMachineKey(ISystemLog log, IOctopusFileSystem fileSystem, string keyFilePath) + public LinuxGeneratedMachineKey(IOctopusFileSystem fileSystem) { - this.log = log; this.fileSystem = fileSystem; - KeyFilePath = keyFilePath; - } - - public string KeyFilePath { get; } - - public string KeyDirectory => LinuxDirectoryOf(KeyFilePath); - - public static string KeyFilePathFor(string instanceName) - { - if (string.IsNullOrWhiteSpace(instanceName) - || instanceName.IndexOfAny(new[] { '/', '\\', '\0' }) >= 0 - || instanceName == "." - || instanceName == "..") - { - throw new ArgumentException($"The instance name `{instanceName}` cannot be used as a key directory name.", nameof(instanceName)); - } - - return JoinLinuxPath(JoinLinuxPath(KeysDirectory, instanceName), KeyFileName); } public static string LegacyKeyFilePathForThisHost => KubernetesSupportDetection.IsRunningAsKubernetesAgent - ? JoinLinuxPath(Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleHome)!, LegacyKeyFileName) + //if we are running in K8S, the machine key is in the home directory, which is likely on a network drive + ? Path.Combine(Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleHome)!, LegacyKeyFileName) : LegacyKeyFilePath; public (byte[] Key, byte[] IV) Load() - => TryLoad() ?? throw new InvalidOperationException($"There is no machine key file at `{KeyFilePath}`."); - - public (byte[] Key, byte[] IV)? TryLoad() - { - if (loaded.HasValue) - { - return loaded; - } - - if (!fileSystem.FileExists(KeyFilePath)) - { - return null; - } - - loaded = LoadFromFile(KeyFilePath); - return loaded; - } - - // Only the configuration upgrade creates the key, so that it can then give the key to the configuration's owner. - public void CreateIfMissing() { - if (fileSystem.FileExists(KeyFilePath)) - { - return; - } - - using var aes = Aes.Create(); - aes.KeySize = 256; - aes.GenerateIV(); - aes.GenerateKey(); - var raw = Convert.ToBase64String(aes.Key) + "." + Convert.ToBase64String(aes.IV); - - fileSystem.EnsureDirectoryExists(KeyDirectory); - - // Several instances starting at once after an upgrade must all end up with the same key. - if (!fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(KeyFilePath, Encoding.ASCII.GetBytes(raw))) + var path = LegacyKeyFilePathForThisHost; + if (!fileSystem.FileExists(path)) { - log.Verbose($"Another process created the machine key file `{KeyFilePath}` first; using its key."); - return; + throw new InvalidOperationException($"There is no machine key file at `{path}`."); } - log.Info($"Generated a new machine key at `{KeyFilePath}`. Back it up with the configuration file it protects: the configuration cannot be decrypted without it."); - } - - (byte[] Key, byte[] IV) LoadFromFile(string path) - { - string contents; try { - contents = fileSystem.ReadAllText(path); - } - catch (UnauthorizedAccessException e) - { - var user = Environment.UserName; - var directory = LinuxDirectoryOf(path); - throw new InvalidOperationException($"The machine key file `{path}` exists but the user Tentacle is running as ({user}) cannot read it. " - + $"It must be owned by and readable only by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {path}`.", e); - } - - try - { - var content = contents.Split('.'); - var key = Convert.FromBase64String(content[0]); - var iv = Convert.FromBase64String(content[1]); - if (key.Length == 0) - { - throw new FormatException("The key is empty."); - } - return (key, iv); + var content = fileSystem.ReadAllText(path).Split('.'); + return (Convert.FromBase64String(content[0]), Convert.FromBase64String(content[1])); } catch (Exception ex) when (ex is FormatException || ex is IndexOutOfRangeException) { @@ -133,15 +45,5 @@ public void CreateIfMissing() + $"Remove the file `{path}` and allow Octopus to regenerate the key."); } } - - // Always Linux paths, even when unit tests run on Windows. - static string JoinLinuxPath(string directory, string fileName) - => directory.EndsWith("/", StringComparison.Ordinal) ? directory + fileName : directory + "/" + fileName; - - static string LinuxDirectoryOf(string path) - { - var lastSeparator = path.LastIndexOf('/'); - return lastSeparator <= 0 ? "/" : path.Substring(0, lastSeparator); - } } } diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs index 0327f2d84..c6d286e9c 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs @@ -29,11 +29,6 @@ public LinuxMachineIdKey(IOctopusFileSystem fileSystem) return (GetMachineId(), Iv); } - public (byte[] Key, byte[] IV)? TryLoad() - { - return fileSystem.FileExists(FileName) ? Load() : null; - } - byte[] GetMachineId() { if (!fileSystem.FileExists(FileName)) diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs index 5b2becc03..74777b9cd 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs @@ -14,7 +14,6 @@ public class LinuxMachineKeyEncryptor : IMachineKeyEncryptor // $ is not a base64 character, so a value without this prefix is unambiguously a legacy one. public const string ProtectedValuePrefix = "$OctopusMachineKeyV1$"; - const int KeySizeInBytes = 32; const int NonceSizeInBytes = 12; const int TagSizeInBytes = 16; @@ -24,13 +23,13 @@ public class LinuxMachineKeyEncryptor : IMachineKeyEncryptor static readonly Encoding StrictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); readonly ISystemLog log; - readonly ICryptoKeyNixSource keySource; + readonly ConfigurationEncryptionKey configurationKey; readonly IReadOnlyList legacyKeySources; - public LinuxMachineKeyEncryptor(ISystemLog log, ICryptoKeyNixSource keySource, IEnumerable legacyKeySources) + public LinuxMachineKeyEncryptor(ISystemLog log, ConfigurationEncryptionKey configurationKey, IEnumerable legacyKeySources) { this.log = log; - this.keySource = keySource; + this.configurationKey = configurationKey; this.legacyKeySources = legacyKeySources.ToArray(); } @@ -45,7 +44,7 @@ public string Encrypt(string raw) { try { - var currentKey = TryLoadCurrentKey(); + var currentKey = configurationKey.TryLoad(); return currentKey == null ? EncryptLegacy(raw) : EncryptCurrent(currentKey, raw); } catch (Exception e) @@ -71,17 +70,26 @@ static string EncryptCurrent(byte[] key, string raw) } string EncryptLegacy(string raw) + { + var (encrypted, errors) = TryEachLegacyKey(legacy => + { + using var aes = Aes.Create(); + using var encryptor = aes.CreateEncryptor(legacy.Key, legacy.IV); + var plaintext = Encoding.UTF8.GetBytes(raw); + return Convert.ToBase64String(encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length)); + }); + + return encrypted ?? throw new AggregateException("There is no configuration encryption key yet, and none of the keys earlier versions used is available.", errors); + } + + (string? Result, List Errors) TryEachLegacyKey(Func<(byte[] Key, byte[] IV), string> use) { var errors = new List(); foreach (var source in legacyKeySources) { try { - var (key, iv) = source.Load(); - using var aes = Aes.Create(); - using var encryptor = aes.CreateEncryptor(key, iv); - var plaintext = Encoding.UTF8.GetBytes(raw); - return Convert.ToBase64String(encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length)); + return (use(source.Load()), errors); } catch (Exception e) { @@ -90,30 +98,26 @@ string EncryptLegacy(string raw) } } - throw new AggregateException("There is no configuration encryption key yet, and none of the keys earlier versions used is available.", errors); + return (null, errors); } - byte[]? TryLoadCurrentKey() + public string Decrypt(string encrypted) + => IsLegacyCiphertext(encrypted) + ? DecryptLegacy(encrypted) + : DecryptCurrent(encrypted); + + string DecryptCurrent(string encrypted) { + byte[] key; try { - var existing = keySource.TryLoad(); - return existing == null ? null : CheckSize(existing.Value.Key); + key = configurationKey.Load(); } catch (Exception e) { - log.Verbose($"Unable to use the configuration encryption key, so using the key earlier versions used: {e.Message}"); - return null; + throw new CryptographicException(e.Message, e); } - } - - public string Decrypt(string encrypted) - => IsLegacyCiphertext(encrypted) - ? DecryptLegacy(encrypted) - : DecryptCurrent(encrypted); - string DecryptCurrent(string encrypted) - { try { var payload = Convert.FromBase64String(encrypted.Substring(ProtectedValuePrefix.Length)); @@ -122,13 +126,9 @@ string DecryptCurrent(string encrypted) throw new FormatException("The encrypted value is too short to contain a nonce and an authentication tag."); } - var plaintext = Gcm.Decrypt(LoadCurrentKey(), payload, AssociatedData); + var plaintext = Gcm.Decrypt(key, payload, AssociatedData); return StrictUtf8.GetString(plaintext); } - catch (InvalidOperationException e) when (e.InnerException is UnauthorizedAccessException) - { - throw new CryptographicException(e.Message, e); - } catch (Exception e) { // No fallback to the legacy keys: they could never have written a value with the prefix. @@ -138,37 +138,20 @@ string DecryptCurrent(string encrypted) } } - byte[] LoadCurrentKey() - => CheckSize(keySource.Load().Key); - - static byte[] CheckSize(byte[] key) + string DecryptLegacy(string encrypted) { - if (key.Length != KeySizeInBytes) + var (decrypted, errors) = TryEachLegacyKey(legacy => { - throw new CryptographicException($"The machine key must be {KeySizeInBytes * 8} bits, but is {key.Length * 8}."); - } - return key; - } + using var aes = Aes.Create(); + using var decryptor = aes.CreateDecryptor(legacy.Key, legacy.IV); + var payload = Convert.FromBase64String(encrypted); + var plaintext = decryptor.TransformFinalBlock(payload, 0, payload.Length); + return StrictUtf8.GetString(plaintext); + }); - string DecryptLegacy(string encrypted) - { - var errors = new List(); - foreach (var source in legacyKeySources) + if (decrypted != null) { - try - { - var (key, iv) = source.Load(); - using var aes = Aes.Create(); - using var decryptor = aes.CreateDecryptor(key, iv); - var payload = Convert.FromBase64String(encrypted); - var plaintext = decryptor.TransformFinalBlock(payload, 0, payload.Length); - return StrictUtf8.GetString(plaintext); - } - catch (Exception e) - { - log.Verbose(e.Message); - errors.Add(e); - } + return decrypted; } throw new CryptographicException("Unable to decrypt a value that was protected by an earlier version of Tentacle with any of the keys it could have used. " diff --git a/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs index 6a7db8cd4..2d105f740 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Diagnostics; using Octopus.Tentacle.Util; @@ -13,31 +12,18 @@ public static class MachineKeyEncryptor public static IMachineKeyEncryptor ForKeyFile(IOctopusFileSystem fileSystem, string? keyFilePath) => PlatformDetection.IsRunningOnWindows ? new WindowsMachineKeyEncryptor() - : keyFilePath == null - ? CreateLinuxEncryptor(Log, fileSystem, new NoConfigurationEncryptionKey()) - : CreateLinuxEncryptor(Log, fileSystem, keyFilePath); + : CreateLinuxEncryptor(Log, fileSystem, keyFilePath); - internal static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, string keyFilePath) - => CreateLinuxEncryptor(log, fileSystem, new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath)); - - static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, ICryptoKeyNixSource generatedKey) + internal static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, string? keyFilePath) { // The keys earlier versions used, in the order they tried them. Only read, never created or changed. var legacyKeySources = new List { new LinuxMachineIdKey(fileSystem), - new LinuxGeneratedMachineKey(log, fileSystem, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost) + new LinuxGeneratedMachineKey(fileSystem) }; - return new LinuxMachineKeyEncryptor(log, generatedKey, legacyKeySources); - } - - class NoConfigurationEncryptionKey : ICryptoKeyNixSource - { - public (byte[] Key, byte[] IV) Load() - => throw new InvalidOperationException("The configuration encryption key for this configuration is not available. Register the configuration with `create-instance --instance `."); - - public (byte[] Key, byte[] IV)? TryLoad() => null; + return new LinuxMachineKeyEncryptor(log, new ConfigurationEncryptionKey(log, fileSystem, keyFilePath), legacyKeySources); } } } diff --git a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs index b1e8ff781..354246a98 100644 --- a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs @@ -22,7 +22,6 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti if (name == null) throw new ArgumentNullException(nameof(name)); string? valueAsString = null; - var decrypting = false; try { var data = Read(name); @@ -33,11 +32,7 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti return defaultValue; if (protectionLevel == ProtectionLevel.MachineKey) - { - decrypting = true; - data = Encryptor.Decrypt(valueAsString); - decrypting = false; - } + data = Decrypt(name, valueAsString); if (typeof(TData) == typeof(string)) return (TData)data; @@ -48,13 +43,8 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti return JsonConvert.DeserializeObject((string)data, JsonSerializerSettings); } - catch (Exception e) + catch (Exception e) when (e is not DecryptionFailedException) { - // The console does not always print inner messages, and this one says how to recover. - if (decrypting) - { - throw new FormatException($"Unable to decrypt the protected configuration setting '{name}'. {e.Message}", e); - } if (protectionLevel == ProtectionLevel.None) throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'. Value was '{valueAsString}'.", e); throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'.", e); @@ -66,7 +56,6 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti if (name == null) throw new ArgumentNullException(nameof(name)); string? valueAsString = null; - var decrypting = false; try { var data = Read(name); @@ -77,11 +66,7 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti return (false, default!); if (protectionLevel == ProtectionLevel.MachineKey) - { - decrypting = true; - data = Encryptor.Decrypt(valueAsString); - decrypting = false; - } + data = Decrypt(name, valueAsString); if (typeof(TData) == typeof(string)) return (true, (TData)data); @@ -92,18 +77,34 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti return (true, JsonConvert.DeserializeObject((string)data, JsonSerializerSettings)); } - catch (Exception e) + catch (Exception e) when (e is not DecryptionFailedException) { - if (decrypting) - { - throw new FormatException($"Unable to decrypt the protected configuration setting '{name}'. {e.Message}", e); - } if (protectionLevel == ProtectionLevel.None) throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'. Value was '{valueAsString}'.", e); throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'.", e); } } + string Decrypt(string name, string value) + { + try + { + return Encryptor.Decrypt(value); + } + catch (Exception e) + { + // The console does not always print inner messages, and this one says how to recover. + throw new DecryptionFailedException($"Unable to decrypt the protected configuration setting '{name}'. {e.Message}", e); + } + } + + class DecryptionFailedException : FormatException + { + public DecryptionFailedException(string message, Exception inner) : base(message, inner) + { + } + } + public override bool Set(string name, TData value, ProtectionLevel protectionLevel = ProtectionLevel.None) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -134,7 +135,7 @@ public override bool Set(string name, TData value, ProtectionLevel protec string EncryptWithoutDowngrading(string name, string raw) { var encrypted = Encryptor.Encrypt(raw); - if (Encryptor.RequiresReEncryption(encrypted) && Read(name) is string previous && !string.IsNullOrWhiteSpace(previous) && !Encryptor.RequiresReEncryption(previous)) + if (Encryptor.RequiresReEncryption(encrypted) && Read(name) is string previous && !Encryptor.RequiresReEncryption(previous)) { throw new CryptographicException($"Unable to update the protected setting '{name}': it is protected with the configuration encryption key, which is not available. Make sure the key file exists and is readable."); } diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs index 8ceeb90c0..14f50c9d8 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs @@ -87,7 +87,7 @@ ApplicationInstanceConfiguration LoadInstance() } var name = appInstance.instanceName ?? RegisteredInstanceNameFor(appInstance.configurationpath); - return name == null ? null : LinuxGeneratedMachineKey.KeyFilePathFor(name); + return name == null ? null : ConfigurationEncryptionKey.KeyFilePathFor(name); } string? RegisteredInstanceNameFor(string? configurationPath) @@ -124,7 +124,7 @@ ApplicationInstanceConfiguration LoadInstance() EnsureConfigurationExists(appInstance.instanceName, appInstance.configurationpath); log.Verbose($"Loading configuration from {appInstance.configurationpath}"); - var writable = new XmlFileKeyValueStore(fileSystem, appInstance.configurationpath!, keyFilePath: keyFilePath); + var writable = new XmlFileKeyValueStore(fileSystem, appInstance.configurationpath!, MachineKeyEncryptor.ForKeyFile(fileSystem, keyFilePath)); return (ContributeAdditionalConfiguration(writable), writable); } diff --git a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs index 05cf2ebfd..daa7272a7 100644 --- a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs +++ b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.InteropServices; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Configuration.Instances; using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Configuration @@ -14,17 +14,15 @@ public interface ITentacleConfigurationUpgrade // Creates the configuration encryption key if it is missing, and gives it to the configuration's owner when running as root. void PrepareKey(); - // As PrepareKey, but fails when the key cannot be created. - void CreateKey(); - // Prepares the key, then re-encrypts protected settings written with the keys earlier versions used. - void Run(); + void Upgrade(); - // As Run, but fails when the key cannot be created or a setting cannot be re-encrypted. - void RunOrThrow(); + // As PrepareKey and Upgrade, but a failure is logged as a warning and Tentacle carries on with the keys earlier versions used. + void TryPrepareKey(); + void TryUpgrade(); } - // Until Run succeeds, Tentacle keeps working on the keys earlier versions used. + // Until Upgrade succeeds, Tentacle keeps working on the keys earlier versions used. public class TentacleConfigurationUpgrade : ITentacleConfigurationUpgrade { public static readonly IReadOnlyList ProtectedSettingNames = new[] @@ -48,36 +46,29 @@ public TentacleConfigurationUpgrade(IApplicationInstanceSelector instanceSelecto } public void PrepareKey() - { - try - { - TryPrepareKey(); - } - catch (Exception e) - { - log.Warn(e, "Unable to prepare the configuration encryption key, " + StillOnLegacyKeys); - } - } + => PrepareInstanceKey(); + + public void TryPrepareKey() + => WarnOnFailure(PrepareKey, "Unable to prepare the configuration encryption key"); - public void CreateKey() - => TryPrepareKey(); + public void TryUpgrade() + => WarnOnFailure(Upgrade, "Unable to move the configuration to its own encryption key"); - public void Run() + void WarnOnFailure(Action action, string failure) { try { - RunOrThrow(); + action(); } catch (Exception e) { - log.Warn(e, "Unable to move the configuration to its own encryption key, " + StillOnLegacyKeys); + log.Warn(e, $"{failure}, {StillOnLegacyKeys}"); } } - public void RunOrThrow() + public void Upgrade() { -#if NET - var prepared = TryPrepareKey(); + var prepared = PrepareInstanceKey(); if (prepared == null) { return; @@ -92,13 +83,12 @@ public void RunOrThrow() log.Info($"Re-encrypted the protected setting '{name}' with the configuration encryption key."); } } -#endif } -#if NET - (LinuxGeneratedMachineKey Key, XmlFileKeyValueStore Store)? TryPrepareKey() + // Null when the instance has no key to prepare. + (ConfigurationEncryptionKey Key, XmlFileKeyValueStore Store)? PrepareInstanceKey() { - if (OperatingSystem.IsWindows()) + if (PlatformDetection.IsRunningOnWindows) { return null; } @@ -117,78 +107,16 @@ public void RunOrThrow() return null; } - var key = new LinuxGeneratedMachineKey(log, fileSystem, instance.KeyFilePath); + var key = new ConfigurationEncryptionKey(log, fileSystem, instance.KeyFilePath); key.CreateIfMissing(); - var configurationOwner = UnixOwnership.OwnerOf(instance.ConfigurationPath); - UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyDirectory); - UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyFilePath); - - return (key, store); - } -#else - void TryPrepareKey() - { - } -#endif - #if NET - static class UnixOwnership - { - const uint UnchangedGroup = uint.MaxValue; - - public static uint OwnerOf(string path) - { - return SystemNative_Stat(path, out var status) == 0 - ? status.Uid - : throw new IOException($"Unable to find the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}"); - } - - public static void GiveToIfRoot(uint owner, string path) - { - if (geteuid() != 0 || OwnerOf(path) == owner) - { - return; - } - - if (lchown(path, owner, UnchangedGroup) != 0) - { - throw new IOException($"Unable to change the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}"); - } - } - - [DllImport("libc")] - static extern uint geteuid(); - - [DllImport("libc", SetLastError = true)] - static extern int lchown(string path, uint owner, uint group); - - // The .NET runtime's own stat shim: one struct layout on every libc and architecture. - [DllImport("libSystem.Native", SetLastError = true)] - static extern int SystemNative_Stat(string path, out FileStatus output); + var configurationOwner = UnixFile.OwnerOf(instance.ConfigurationPath); + UnixFile.SetOwnerIfRunningAsRoot(configurationOwner, key.KeyDirectory!); + UnixFile.SetOwnerIfRunningAsRoot(configurationOwner, key.KeyFilePath!); +#endif - [StructLayout(LayoutKind.Sequential)] - struct FileStatus - { - public int Flags; - public int Mode; - public uint Uid; - public uint Gid; - public long Size; - public long ATime; - public long ATimeNsec; - public long MTime; - public long MTimeNsec; - public long CTime; - public long CTimeNsec; - public long BirthTime; - public long BirthTimeNsec; - public long Dev; - public long RDev; - public long Ino; - public uint UserFlags; - } + return (key, store); } -#endif } } diff --git a/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs index 841375f0b..ab1d365ad 100644 --- a/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs @@ -13,10 +13,9 @@ public class XmlFileKeyValueStore : XmlKeyValueStore public XmlFileKeyValueStore(IOctopusFileSystem fileSystem, string configurationFile, + IMachineKeyEncryptor encryptor, bool autoSaveOnSet = true, - bool isWriteOnly = false, - IMachineKeyEncryptor? encryptor = null, - string? keyFilePath = null) : base(encryptor ?? MachineKeyEncryptor.ForKeyFile(fileSystem, keyFilePath), autoSaveOnSet, isWriteOnly) + bool isWriteOnly = false) : base(encryptor, autoSaveOnSet, isWriteOnly) { this.fileSystem = fileSystem; this.configurationFile = fileSystem.GetFullPath(configurationFile); diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs index c3bf502ca..3eb479805 100644 --- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs +++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs @@ -129,7 +129,7 @@ protected override void Start() ConfigurationFilePermissions.RestrictToServiceUser(instanceSelector.Current.ConfigurationPath, serviceConfigurationState.Username, log); // A non-root service cannot create its key under /var/octopus, so it is created here while running as root. - configurationUpgrade.Value.PrepareKey(); + configurationUpgrade.Value.TryPrepareKey(); } } } From da6126ceec6b6f875822a145b18ff4ea0e84eec5 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 12:21:43 +1100 Subject: [PATCH 003/124] Tell the user how to recover when the configuration encryption key is lost --- .../Configuration/Crypto/ConfigurationEncryptionKey.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index 6b25c530b..cad8fb834 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -17,6 +17,10 @@ public class ConfigurationEncryptionKey const int KeySizeInBytes = 32; + const string RecoveryWithoutBackup = "If there is no backup, the Tentacle's certificate is lost and it needs a new identity: " + + "recreate the instance with `delete-instance` and `create-instance`, run `new-certificate`, " + + "then re-register it with `register-with --force` (or `register-worker --force`) using an API key."; + static string KeysDirectory => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory) is { Length: > 0 } directory ? directory : DefaultKeysDirectory; @@ -52,7 +56,7 @@ public static string KeyFilePathFor(string instanceName) public byte[] Load() => TryLoad() ?? throw new InvalidOperationException(KeyFilePath == null ? "The configuration encryption key for this configuration is not available. Register the configuration with `create-instance --instance `." - : $"The configuration encryption key file `{KeyFilePath}` does not exist, so the values it protected cannot be decrypted. Restore it from a backup."); + : $"The configuration encryption key file `{KeyFilePath}` does not exist, so the values it protected cannot be decrypted. Restore it from a backup. " + RecoveryWithoutBackup); public byte[]? TryLoad() { @@ -129,7 +133,7 @@ byte[] LoadFromFile(string path) } throw new InvalidOperationException($"The configuration encryption key file `{path}` is corrupt: it must hold a base64-encoded {KeySizeInBytes * 8}-bit key. " - + "Restore it from a backup; values encrypted with a lost key cannot be recovered."); + + "Restore it from a backup; values encrypted with a lost key cannot be recovered. " + RecoveryWithoutBackup); } // Always Linux paths, even when unit tests run on Windows. From ba4b99643c4a21411a50e606514dc53cb9157360 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 12:23:55 +1100 Subject: [PATCH 004/124] Tell the user to keep the machine's name when re-registering after losing the key --- .../Configuration/Crypto/ConfigurationEncryptionKey.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index cad8fb834..1765cfb26 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -19,7 +19,8 @@ public class ConfigurationEncryptionKey const string RecoveryWithoutBackup = "If there is no backup, the Tentacle's certificate is lost and it needs a new identity: " + "recreate the instance with `delete-instance` and `create-instance`, run `new-certificate`, " - + "then re-register it with `register-with --force` (or `register-worker --force`) using an API key."; + + "then re-register it using an API key with `register-with` (or `register-worker`), passing `--force` and `--name` set to its existing name in Octopus " + + "so that the existing machine is updated rather than a new one added."; static string KeysDirectory => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory) is { Length: > 0 } directory ? directory : DefaultKeysDirectory; From 2b4e1ca20f8738590d154e39d324d67f75d3882d Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 14:07:02 +1100 Subject: [PATCH 005/124] Add replace-certificate to recover a Tentacle whose certificate or key is lost --- .../Commands/ReplaceCertificateCommandFixture.cs | 1 + .../Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs | 5 +++++ .../Configuration/Crypto/ConfigurationEncryptionKey.cs | 7 +++---- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs index 80720309d..48997c091 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs @@ -100,6 +100,7 @@ static void ReplaceCertificate(TemporaryTentacleConfiguration tentacle, FakeOcto => new ReplaceCertificateCommand( new Lazy(() => tentacle.Configuration), new Lazy(() => new CertificateGenerator(new NullLog())), + new Lazy(() => Substitute.For()), octopus.ClientInitializer, Substitute.For(), Substitute.For(), diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs index 768938a07..e2c26cc00 100644 --- a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -20,6 +20,7 @@ public class ReplaceCertificateCommand : AbstractStandardCommand { readonly Lazy configuration; readonly Lazy certificateGenerator; + readonly Lazy configurationUpgrade; readonly IOctopusClientInitializer octopusClientInitializer; readonly IProxyConfigParser proxyConfig; readonly ISystemLog log; @@ -29,6 +30,7 @@ public class ReplaceCertificateCommand : AbstractStandardCommand public ReplaceCertificateCommand( Lazy configuration, Lazy certificateGenerator, + Lazy configurationUpgrade, IOctopusClientInitializer octopusClientInitializer, IProxyConfigParser proxyConfig, ISystemLog log, @@ -38,6 +40,7 @@ public ReplaceCertificateCommand( { this.configuration = configuration; this.certificateGenerator = certificateGenerator; + this.configurationUpgrade = configurationUpgrade; this.octopusClientInitializer = octopusClientInitializer; this.proxyConfig = proxyConfig; this.log = log; @@ -71,6 +74,8 @@ async Task StartAsync() if (!keepCurrentCertificate) { + // Creates a fresh configuration encryption key if it was lost, so the new certificate can be saved. + configurationUpgrade.Value.PrepareKey(); 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}"); diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index 1765cfb26..5af1b96b4 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -17,10 +17,9 @@ public class ConfigurationEncryptionKey const int KeySizeInBytes = 32; - const string RecoveryWithoutBackup = "If there is no backup, the Tentacle's certificate is lost and it needs a new identity: " - + "recreate the instance with `delete-instance` and `create-instance`, run `new-certificate`, " - + "then re-register it using an API key with `register-with` (or `register-worker`), passing `--force` and `--name` set to its existing name in Octopus " - + "so that the existing machine is updated rather than a new one added."; + const string RecoveryWithoutBackup = "If there is no backup, the Tentacle's certificate is lost and it needs a new one: " + + "run `replace-certificate` with an API key. " + + "This creates a new key and certificate, and updates every deployment target and worker registered with the old certificate to trust it."; static string KeysDirectory => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory) is { Length: > 0 } directory ? directory : DefaultKeysDirectory; From cf743687cd6c4ba612a4186ea2447e5606197444 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 14:29:20 +1100 Subject: [PATCH 006/124] Create the configuration encryption key before creating the instance --- .../ApplicationInstanceManagerFixture.cs | 42 +++++++++++++++++++ .../Commands/CreateInstanceCommand.cs | 1 + .../Crypto/ConfigurationEncryptionKey.cs | 1 - .../Instances/ApplicationInstanceManager.cs | 23 ++++++++++ 4 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerFixture.cs diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerFixture.cs new file mode 100644 index 000000000..2b8e0ba27 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerFixture.cs @@ -0,0 +1,42 @@ +using System; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Tests.Support.TestAttributes; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Tests.Configuration +{ + [TestFixture] + [LinuxTest] + public class ApplicationInstanceManagerFixture + { + [Test] + public void WhenTheConfigurationEncryptionKeyCannotBeCreatedThenNoInstanceIsCreated() + { + // Arrange + var fileSystem = Substitute.For(); + fileSystem.When(f => f.EnsureDirectoryExists(Arg.Is(d => d.EndsWith("/keys/Tentacle")))) + .Do(_ => throw new UnauthorizedAccessException("Permission denied")); + var instanceStore = Substitute.For(); + var manager = new ApplicationInstanceManager( + ApplicationName.Tentacle, + new StartUpRegistryInstanceRequest("Tentacle"), + fileSystem, + Substitute.For(), + instanceStore, + new Lazy(() => Substitute.For())); + + // Act + Action create = () => manager.CreateInstance("Tentacle", "/etc/octopus/Tentacle/tentacle.config", "/etc/octopus/Tentacle"); + + // Assert + create.Should().Throw().WithMessage("*Permission denied*"); + fileSystem.DidNotReceive().EnsureDirectoryExists("/etc/octopus/Tentacle"); + instanceStore.DidNotReceiveWithAnyArgs().RegisterInstance(default!); + } + } +} diff --git a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs index f1e1adef7..c3cfd45c5 100644 --- a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs +++ b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs @@ -33,6 +33,7 @@ protected override void Start() instanceManager.CreateInstance(instanceName, config, home); } + // The key already exists; this gives it to the owner of a configuration file that was already there. configurationUpgrade.Value.PrepareKey(); } } diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index 5af1b96b4..9ed08112b 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -74,7 +74,6 @@ public byte[] Load() return loaded; } - // Only the configuration upgrade creates the key, so that it can then give the key to the configuration's owner. public void CreateIfMissing() { var path = KeyFilePath ?? throw new InvalidOperationException("There is no key file path to create the configuration encryption key at."); diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs index 16b8a5026..98466f33c 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs @@ -1,6 +1,8 @@ using System; using System.IO; +using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Kubernetes; using Octopus.Tentacle.Util; @@ -39,6 +41,7 @@ public void CreateDefaultInstance(string configurationFile, string? homeDirector public void CreateInstance(string instanceName, string configurationFile, string? homeDirectory = null) { (configurationFile, homeDirectory) = ValidateConfigDirectory(configurationFile, homeDirectory); + EnsureConfigurationEncryptionKeyExists(instanceName); EnsureConfigurationFileExists(configurationFile, homeDirectory); RegisterInstanceInIndex(instanceName, configurationFile); WriteHomeDirectory(homeDirectory); @@ -49,6 +52,26 @@ public void DeleteInstance(string instanceName) instanceStore.DeleteInstance(instanceName); } + // Created before anything else, so that a failure leaves no half-made instance behind. + void EnsureConfigurationEncryptionKeyExists(string instanceName) + { + if (PlatformDetection.IsRunningOnWindows || KubernetesSupportDetection.IsRunningAsKubernetesAgent || startUpInstanceRequest is StartUpDynamicInstanceRequest) + { + return; + } + + var keyFilePath = ConfigurationEncryptionKey.KeyFilePathFor(instanceName); + try + { + new ConfigurationEncryptionKey(log, fileSystem, keyFilePath).CreateIfMissing(); + } + catch (Exception e) + { + throw new ControlledFailureException($"Unable to create the configuration encryption key `{keyFilePath}` for the instance `{instanceName}`, so the instance was not created: {e.Message} " + + $"Run this command as a user that can write to that directory, such as root, or set the environment variable `{EnvironmentVariables.TentacleConfigurationKeysDirectory}` to a directory this user can write to.", e); + } + } + void RegisterInstanceInIndex(string instanceName, string configurationFile) { // If completely dynamic (no instance or configFile provided) then dont bother setting anything From ac98d5fc33e66b6b35b15be1e9bb759e71335b37 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 14:37:58 +1100 Subject: [PATCH 007/124] Fix the net48 build of the unit tests --- .../Support/TestMachineKeyEncryptor.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs b/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs index 9e13874bb..35116c013 100644 --- a/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs @@ -45,8 +45,16 @@ public static ConfigurationEncryptionKey Create() const string path = "/in-memory/config-encryption.key"; var fileSystem = Substitute.For(); fileSystem.FileExists(path).Returns(true); - fileSystem.ReadAllText(path).Returns(Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))); + fileSystem.ReadAllText(path).Returns(Convert.ToBase64String(RandomKey())); return new ConfigurationEncryptionKey(Substitute.For(), fileSystem, path); } + + static byte[] RandomKey() + { + var key = new byte[32]; + using var random = RandomNumberGenerator.Create(); + random.GetBytes(key); + return key; + } } } From 7abe3738aa8f761fd5c505a14b8a2bda21a59f4b Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 15:38:08 +1100 Subject: [PATCH 008/124] Don't point users at the test-only keys directory override --- .../Configuration/Instances/ApplicationInstanceManager.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs index 98466f33c..ecb3c8276 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs @@ -61,14 +61,17 @@ void EnsureConfigurationEncryptionKeyExists(string instanceName) } var keyFilePath = ConfigurationEncryptionKey.KeyFilePathFor(instanceName); + var key = new ConfigurationEncryptionKey(log, fileSystem, keyFilePath); try { - new ConfigurationEncryptionKey(log, fileSystem, keyFilePath).CreateIfMissing(); + key.CreateIfMissing(); } catch (Exception e) { + var user = Environment.UserName; + var directory = key.KeyDirectory; throw new ControlledFailureException($"Unable to create the configuration encryption key `{keyFilePath}` for the instance `{instanceName}`, so the instance was not created: {e.Message} " - + $"Run this command as a user that can write to that directory, such as root, or set the environment variable `{EnvironmentVariables.TentacleConfigurationKeysDirectory}` to a directory this user can write to.", e); + + $"Run this command as root, or give the user ({user}) access to the directory, for example: `sudo mkdir -p {directory} && sudo chown -R {user} {directory} && sudo chmod 700 {directory}`.", e); } } From 5f818a8497ed23ceae81860eb51f282691e511d7 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 15:49:00 +1100 Subject: [PATCH 009/124] Point the legacy decrypt failure at replace-certificate --- .../Configuration/Crypto/LinuxMachineKeyEncryptor.cs | 10 ++++------ testing/docker-linux/test-config-encryption-upgrade.sh | 2 +- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs index 74777b9cd..5f78156d8 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs @@ -154,12 +154,10 @@ string DecryptLegacy(string encrypted) return decrypted; } - throw new CryptographicException("Unable to decrypt a value that was protected by an earlier version of Tentacle with any of the keys it could have used. " - + "Earlier versions derived the key from /etc/machine-id, so this happens when the configuration was moved from another machine, " - + "or is on a volume mounted into a container whose image has since changed. " - + "If the machine-id it was written with is still available (for a container, `docker run --rm --entrypoint cat /etc/machine-id`), " - + "make it available read-only at /etc/machine-id for one start and Tentacle will re-encrypt the configuration with its own key. " - + "Otherwise run 'tentacle new-certificate' and re-establish trust with the Octopus Server, or restore the configuration file from a backup taken on the original machine.", + throw new CryptographicException("Unable to decrypt a value protected by an earlier version of Tentacle. " + + "Earlier versions derived the key from /etc/machine-id, so this happens when the configuration came from another machine or the machine-id has changed. " + + "If the /etc/machine-id it was written with is still available, put it back at /etc/machine-id for one start and Tentacle will re-encrypt the configuration with its own key. " + + "Otherwise restore the configuration file from a backup taken on the original machine, or run 'tentacle replace-certificate' to create a new certificate and update the thumbprint Octopus Server trusts.", new AggregateException(errors)); } diff --git a/testing/docker-linux/test-config-encryption-upgrade.sh b/testing/docker-linux/test-config-encryption-upgrade.sh index c43cd9c72..00daa1248 100755 --- a/testing/docker-linux/test-config-encryption-upgrade.sh +++ b/testing/docker-linux/test-config-encryption-upgrade.sh @@ -31,7 +31,7 @@ in_container "$PREVIOUS_IMAGE" 'cat /etc/machine-id' > "$WORK_DIR/machine-id" OUTPUT=$(in_container "$NEW_IMAGE" 'tentacle show-thumbprint --instance Tentacle' || true) check "the new image cannot decrypt without the previous machine-id" \ - "$(grep -c 'docker run --rm --entrypoint cat /etc/machine-id' <<<"$OUTPUT")" "1" + "$(grep -c 'If the /etc/machine-id it was written with is still available' <<<"$OUTPUT")" "1" OUTPUT=$(in_container "$NEW_IMAGE" 'timeout 30 tentacle run --instance Tentacle' -v "$WORK_DIR/machine-id:/etc/machine-id:ro" || true) check "the agent re-encrypts with the previous machine-id mounted" \ From 727f7ff34fb00523565c0ad82c5d18a18b477a73 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 16:16:05 +1100 Subject: [PATCH 010/124] Make shared key directories traversable under a hardened umask --- .../LinuxConfigurationFileSecurityFixture.cs | 57 +++++++++++++++++++ .../Crypto/ConfigurationEncryptionKey.cs | 33 ++++++++++- 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs index b5f4d9b14..83137a7f5 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs @@ -1,7 +1,9 @@ #if !NETFRAMEWORK using System; +using System.Diagnostics; using System.IO; using System.Linq; +using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; @@ -10,6 +12,7 @@ using NUnit.Framework; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Tests.Support.TestAttributes; using Octopus.Tentacle.Util; @@ -87,6 +90,60 @@ public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() keys.Should().AllSatisfy(k => k.Should().Equal(onDisk)); Directory.GetFiles(directory).Should().ContainSingle("no racer's temporary file is left behind"); } + + [Test] + public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillReadIt() + { + if (geteuid() != 0) + { + Assert.Ignore("Creating a key for another user needs root."); + } + + // Arrange + var user = "octo-key-" + Guid.NewGuid().ToString("N").Substring(0, 8); + Run("useradd", $"--no-create-home {user}").Should().Be(0); + var instanceKeyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); + var keySource = new ConfigurationEncryptionKey(log, fileSystem, instanceKeyFilePath); + var previousUmask = umask(Convert.ToUInt32("027", 8)); + try + { + // Act + keySource.CreateIfMissing(); + var owner = uint.Parse(RunAndRead("id", $"-u {user}")); + UnixFile.SetOwnerIfRunningAsRoot(owner, keySource.KeyDirectory!); + UnixFile.SetOwnerIfRunningAsRoot(owner, instanceKeyFilePath); + + // Assert + Run("su", $"-s /bin/sh -c \"cat {instanceKeyFilePath}\" {user}").Should().Be(0, "the owner must be able to traverse the shared directories to its key"); + File.GetUnixFileMode(keySource.KeyDirectory!).Should().Be(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + finally + { + umask(previousUmask); + Run("userdel", user); + } + } + + static int Run(string fileName, string arguments) + { + using var process = Process.Start(fileName, arguments); + process.WaitForExit(); + return process.ExitCode; + } + + static string RunAndRead(string fileName, string arguments) + { + using var process = Process.Start(new ProcessStartInfo(fileName, arguments) { RedirectStandardOutput = true })!; + var output = process.StandardOutput.ReadToEnd().Trim(); + process.WaitForExit(); + return output; + } + + [DllImport("libc")] + static extern uint geteuid(); + + [DllImport("libc")] + static extern uint umask(uint mask); } } #endif diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index 9ed08112b..e2e37c28b 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.IO; using System.Security.Cryptography; using System.Text; using Octopus.Tentacle.Core.Diagnostics; @@ -17,6 +19,11 @@ public class ConfigurationEncryptionKey const int KeySizeInBytes = 32; +#if NET + const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; + const UnixFileMode TraversableByAll = OwnerOnly | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute; +#endif + const string RecoveryWithoutBackup = "If there is no backup, the Tentacle's certificate is lost and it needs a new one: " + "run `replace-certificate` with an API key. " + "This creates a new key and certificate, and updates every deployment target and worker registered with the old certificate to trust it."; @@ -84,7 +91,7 @@ public void CreateIfMissing() var raw = Convert.ToBase64String(RandomKey()); - fileSystem.EnsureDirectoryExists(KeyDirectory!); + CreateKeyDirectory(KeyDirectory!); // Several instances starting at once after an upgrade must all end up with the same key. if (!fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(path, Encoding.ASCII.GetBytes(raw))) @@ -96,6 +103,30 @@ public void CreateIfMissing() log.Info($"Generated a new configuration encryption key at `{path}`. Back it up with the configuration file it protects: the configuration cannot be decrypted without it."); } + // Ancestors are shared by every instance's service user, so they must stay traversable whatever the umask. + void CreateKeyDirectory(string keyDirectory) + { + var missing = new List(); + for (var directory = keyDirectory; directory.Length > 1 && !fileSystem.DirectoryExists(directory); directory = LinuxDirectoryOf(directory)) + { + missing.Add(directory); + } + + fileSystem.EnsureDirectoryExists(keyDirectory); + +#if NET + if (OperatingSystem.IsWindows()) + { + return; + } + + foreach (var directory in missing) + { + File.SetUnixFileMode(directory, directory == keyDirectory ? OwnerOnly : TraversableByAll); + } +#endif + } + static byte[] RandomKey() { var key = new byte[KeySizeInBytes]; From 47c0e6daa02b7a839131252c9785be3f57c12e8d Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 16:27:15 +1100 Subject: [PATCH 011/124] Refuse to start when only the configuration file is persisted --- docker/linux/scripts/configure-and-run.sh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docker/linux/scripts/configure-and-run.sh b/docker/linux/scripts/configure-and-run.sh index 1462129c5..5c449fcde 100644 --- a/docker/linux/scripts/configure-and-run.sh +++ b/docker/linux/scripts/configure-and-run.sh @@ -2,9 +2,11 @@ set -eu # A path on the same device as / lives in the container's own layer and is lost when the container is re-created. -is_persisted() { mkdir -p "$1" && [ "$(stat -c %d "$1")" != "$(stat -c %d /)" ]; } -if is_persisted /etc/octopus && ! is_persisted /var/octopus/tentacle/keys; then - echo "/etc/octopus is persisted but /var/octopus/tentacle/keys is not. The configuration cannot be decrypted without its key once this container is re-created. Mount /var/octopus/tentacle/keys on a volume too." >&2 +is_on_volume() { [ "$(stat -c %d "$1")" != "$(stat -c %d /)" ]; } +is_persisted() { mkdir -p "$1" && is_on_volume "$1"; } +is_file_persisted() { [ -e "$1" ] && is_on_volume "$1"; } +if { is_persisted /etc/octopus || is_file_persisted /etc/octopus/tentacle.config; } && ! is_persisted /var/octopus/tentacle/keys; then + echo "/etc/octopus or /etc/octopus/tentacle.config is persisted but /var/octopus/tentacle/keys is not. The configuration cannot be decrypted without its key once this container is re-created. Mount /var/octopus/tentacle/keys on a volume too." >&2 exit 1 fi From d69cd1b4c50a8f0b1f7fc6285e12dc7981031c7d Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 17:15:33 +1100 Subject: [PATCH 012/124] Use the nobody user in the hardened umask test so it runs on Alpine --- .../Crypto/LinuxConfigurationFileSecurityFixture.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs index 83137a7f5..82d96a273 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs @@ -100,8 +100,8 @@ public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillRea } // Arrange - var user = "octo-key-" + Guid.NewGuid().ToString("N").Substring(0, 8); - Run("useradd", $"--no-create-home {user}").Should().Be(0); + // Present on every distribution, unlike useradd, which Alpine does not have. + const string user = "nobody"; var instanceKeyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); var keySource = new ConfigurationEncryptionKey(log, fileSystem, instanceKeyFilePath); var previousUmask = umask(Convert.ToUInt32("027", 8)); @@ -120,7 +120,6 @@ public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillRea finally { umask(previousUmask); - Run("userdel", user); } } From 8b14d76448d11fcab440c5dd1a6927258d95948a Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 18 Nov 2026 17:17:39 +1100 Subject: [PATCH 013/124] Create a real user in the hardened umask test, with adduser on Alpine --- .../LinuxConfigurationFileSecurityFixture.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs index 82d96a273..45747af51 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs @@ -100,8 +100,8 @@ public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillRea } // Arrange - // Present on every distribution, unlike useradd, which Alpine does not have. - const string user = "nobody"; + var user = "octo-key-" + Guid.NewGuid().ToString("N").Substring(0, 8); + CreateUser(user).Should().Be(0); var instanceKeyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); var keySource = new ConfigurationEncryptionKey(log, fileSystem, instanceKeyFilePath); var previousUmask = umask(Convert.ToUInt32("027", 8)); @@ -120,9 +120,19 @@ public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillRea finally { umask(previousUmask); + DeleteUser(user); } } + // Alpine has BusyBox's adduser and deluser rather than useradd and userdel. + static bool IsAlpine => File.Exists("/etc/alpine-release"); + + static int CreateUser(string user) + => IsAlpine ? Run("adduser", $"-D -H {user}") : Run("useradd", $"--no-create-home {user}"); + + static int DeleteUser(string user) + => IsAlpine ? Run("deluser", user) : Run("userdel", user); + static int Run(string fileName, string arguments) { using var process = Process.Start(fileName, arguments); From eeeacfb6e7b27834755cb3746b9115ed1e6b34a9 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Fri, 20 Nov 2026 10:20:59 +1100 Subject: [PATCH 014/124] Store Linux machine-key values as AES256-GCM$nonce$ciphertext --- .../test-scripts/test-linux-package.sh | 2 +- .../Crypto/LinuxMachineKeyEncryptorFixture.cs | 18 ++++++- .../TentacleConfigurationUpgradeFixture.cs | 6 +-- .../Crypto/LinuxMachineKeyEncryptor.cs | 48 ++++++++++++++----- .../test-config-encryption-upgrade.sh | 2 +- 5 files changed, 57 insertions(+), 19 deletions(-) diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh index 77bc67d3e..b63625fc0 100644 --- a/linux-packages/test-scripts/test-linux-package.sh +++ b/linux-packages/test-scripts/test-linux-package.sh @@ -65,7 +65,7 @@ mkdir -p "$(dirname "$CONFIGURATION_FILE")" Tentacle create-instance --instance "$INSTANCE_NAME" --config "$CONFIGURATION_FILE" Tentacle new-certificate --instance "$INSTANCE_NAME" -if ! grep -qF 'key="Tentacle.Certificate">$OctopusMachineKeyV1$' "$CONFIGURATION_FILE"; then +if ! grep -qF 'key="Tentacle.Certificate">AES256-GCM$' "$CONFIGURATION_FILE"; then echo "The Tentacle certificate in $CONFIGURATION_FILE was not encrypted with the versioned machine key scheme." exit 1 fi diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs index 5aee06c92..cd6eb47e5 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs @@ -29,7 +29,7 @@ public void WhenAValueIsEncryptedThenItIsVersionedAndDecrypts() var encrypted = encryptor.Encrypt("FooBar"); // Assert - encrypted.Should().StartWith(LinuxMachineKeyEncryptor.ProtectedValuePrefix); + encrypted.Should().MatchRegex(@"^AES256-GCM\$[A-Za-z0-9+/=]+\$[A-Za-z0-9+/=]+$"); encryptor.RequiresReEncryption(encrypted).Should().BeFalse(); encryptor.Decrypt(encrypted).Should().Be("FooBar"); } @@ -48,6 +48,22 @@ public void WhenACurrentValueWasEncryptedWithAnotherKeyThenALegacyKeyIsNotTried( // Assert decrypt.Should().Throw(); } + + [TestCase("AES128-GCM")] + [TestCase("aes256-gcm")] + public void WhenTheSpecifierIsAlteredThenDecryptionFails(string alteredSpecifier) + { + // Arrange + var encryptor = CreateEncryptor(); + var encrypted = encryptor.Encrypt("FooBar"); + var tampered = alteredSpecifier + encrypted.Substring(LinuxMachineKeyEncryptor.Specifier.Length); + + // Act + Action decrypt = () => encryptor.Decrypt(tampered); + + // Assert + decrypt.Should().Throw().WithMessage("*Unknown encryption specifier*"); + } } } #endif diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs index 249dcb482..40ae3f573 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs @@ -55,14 +55,14 @@ public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted() var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); var store = CreateStore(keyFilePath); store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - RawCertificate().Should().NotStartWith(LinuxMachineKeyEncryptor.ProtectedValuePrefix, "without a key, values are written the way earlier versions wrote them"); + RawCertificate().Should().NotStartWith(LinuxMachineKeyEncryptor.Specifier + "$", "without a key, values are written the way earlier versions wrote them"); // Act CreateUpgrade(store, keyFilePath).Upgrade(); // Assert File.Exists(keyFilePath).Should().BeTrue(); - RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.ProtectedValuePrefix); + RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); } @@ -133,7 +133,7 @@ public void UpgradeConfigurationEncryptionCreatesTheKeyAndReEncryptsLegacyValues // Assert File.Exists(keyFilePath).Should().BeTrue(); - RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.ProtectedValuePrefix); + RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); } diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs index 5f78156d8..b58bdb4a8 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs @@ -7,17 +7,18 @@ namespace Octopus.Tentacle.Configuration.Crypto { - // Stored as $OctopusMachineKeyV1$base64(nonce || ciphertext || tag), AES-256-GCM with the prefix as associated data. - // Values without the prefix were written by earlier versions with AES-CBC and a fixed IV. + // Stored as AES256-GCM$base64(nonce)$base64(ciphertext || tag), with the specifier as associated data. + // Values without a $ were written by earlier versions with AES-CBC and a fixed IV. public class LinuxMachineKeyEncryptor : IMachineKeyEncryptor { - // $ is not a base64 character, so a value without this prefix is unambiguously a legacy one. - public const string ProtectedValuePrefix = "$OctopusMachineKeyV1$"; + public const string Specifier = "AES256-GCM"; + // $ is not a base64 character, so a value without one is unambiguously a legacy one. + const char FieldSeparator = '$'; const int NonceSizeInBytes = 12; const int TagSizeInBytes = 16; - static readonly byte[] AssociatedData = Encoding.ASCII.GetBytes(ProtectedValuePrefix); + static readonly byte[] AssociatedData = Encoding.ASCII.GetBytes(Specifier); // A wrong legacy key passes the AES-CBC padding check about 1 time in 256; the garbage it yields is rarely valid UTF-8. static readonly Encoding StrictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); @@ -34,7 +35,7 @@ public LinuxMachineKeyEncryptor(ISystemLog log, ConfigurationEncryptionKey confi } static bool IsLegacyCiphertext(string encrypted) - => !encrypted.StartsWith(ProtectedValuePrefix, StringComparison.Ordinal); + => encrypted.IndexOf(FieldSeparator) < 0; public bool RequiresReEncryption(string encrypted) => IsLegacyCiphertext(encrypted); @@ -66,7 +67,9 @@ static string EncryptCurrent(byte[] key, string raw) Gcm.Encrypt(key, plaintext, payload, AssociatedData); - return ProtectedValuePrefix + Convert.ToBase64String(payload); + var nonceBase64 = Convert.ToBase64String(payload, 0, NonceSizeInBytes); + var ciphertextBase64 = Convert.ToBase64String(payload, NonceSizeInBytes, payload.Length - NonceSizeInBytes); + return string.Join(FieldSeparator.ToString(), Specifier, nonceBase64, ciphertextBase64); } string EncryptLegacy(string raw) @@ -120,24 +123,43 @@ string DecryptCurrent(string encrypted) try { - var payload = Convert.FromBase64String(encrypted.Substring(ProtectedValuePrefix.Length)); - if (payload.Length < NonceSizeInBytes + TagSizeInBytes) - { - throw new FormatException("The encrypted value is too short to contain a nonce and an authentication tag."); - } + var payload = ParsePayload(encrypted); var plaintext = Gcm.Decrypt(key, payload, AssociatedData); return StrictUtf8.GetString(plaintext); } catch (Exception e) { - // No fallback to the legacy keys: they could never have written a value with the prefix. + // No fallback to the legacy keys: they could never have written a value in this format. throw new CryptographicException("Unable to decrypt a value protected with the Tentacle machine key. " + "Either the value has been altered, or the machine key file it was encrypted with has been replaced or removed. " + $"Details: {e.Message}", e); } } + static byte[] ParsePayload(string encrypted) + { + var fields = encrypted.Split(FieldSeparator); + if (fields.Length != 3) + { + throw new FormatException($"Expected 3 '{FieldSeparator}'-separated fields but found {fields.Length}."); + } + + if (fields[0] != Specifier) + { + throw new FormatException($"Unknown encryption specifier '{fields[0]}'; expected '{Specifier}'."); + } + + var nonce = Convert.FromBase64String(fields[1]); + var ciphertextAndTag = Convert.FromBase64String(fields[2]); + if (nonce.Length != NonceSizeInBytes || ciphertextAndTag.Length < TagSizeInBytes) + { + throw new FormatException("The nonce or authentication tag has the wrong length."); + } + + return nonce.Concat(ciphertextAndTag).ToArray(); + } + string DecryptLegacy(string encrypted) { var (decrypted, errors) = TryEachLegacyKey(legacy => diff --git a/testing/docker-linux/test-config-encryption-upgrade.sh b/testing/docker-linux/test-config-encryption-upgrade.sh index 00daa1248..44c0dacc5 100755 --- a/testing/docker-linux/test-config-encryption-upgrade.sh +++ b/testing/docker-linux/test-config-encryption-upgrade.sh @@ -38,7 +38,7 @@ check "the agent re-encrypts with the previous machine-id mounted" \ "$(grep -c "Re-encrypted the protected setting 'Tentacle.Certificate'" <<<"$OUTPUT")" "1" check "the certificate carries the versioned prefix" \ - "$(in_container "$NEW_IMAGE" 'grep -cF "key=\"Tentacle.Certificate\">\$OctopusMachineKeyV1\$" /etc/octopus/tentacle.config')" "1" + "$(in_container "$NEW_IMAGE" 'grep -cF "key=\"Tentacle.Certificate\">AES256-GCM\$" /etc/octopus/tentacle.config')" "1" check "the key is owner-only" "$(in_container "$NEW_IMAGE" 'stat -c %a /var/octopus/tentacle/keys/Tentacle/config-encryption.key')" "600" check "the key is not beside the configuration" "$(in_container "$NEW_IMAGE" 'test -e /etc/octopus/config-encryption.key && echo present || echo absent')" "absent" check "the thumbprint is unchanged without the previous machine-id" "$(in_container "$NEW_IMAGE" 'tentacle show-thumbprint --instance Tentacle')" "$THUMBPRINT" From fa7f5cb9ec0b13aad552b81f30b4099b8e298c2a Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 09:42:11 +1100 Subject: [PATCH 015/124] Store tag in its own field: AESGCM-V1$nonce$tag$ciphertext --- .../test-scripts/test-linux-package.sh | 2 +- .../Crypto/LinuxMachineKeyEncryptorFixture.cs | 6 +-- .../Crypto/LinuxMachineKeyEncryptor.cs | 54 ++++++++----------- .../test-config-encryption-upgrade.sh | 2 +- 4 files changed, 26 insertions(+), 38 deletions(-) diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh index b63625fc0..22a4faf3c 100644 --- a/linux-packages/test-scripts/test-linux-package.sh +++ b/linux-packages/test-scripts/test-linux-package.sh @@ -65,7 +65,7 @@ mkdir -p "$(dirname "$CONFIGURATION_FILE")" Tentacle create-instance --instance "$INSTANCE_NAME" --config "$CONFIGURATION_FILE" Tentacle new-certificate --instance "$INSTANCE_NAME" -if ! grep -qF 'key="Tentacle.Certificate">AES256-GCM$' "$CONFIGURATION_FILE"; then +if ! grep -qF 'key="Tentacle.Certificate">AESGCM-V1$' "$CONFIGURATION_FILE"; then echo "The Tentacle certificate in $CONFIGURATION_FILE was not encrypted with the versioned machine key scheme." exit 1 fi diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs index cd6eb47e5..d10a79460 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs @@ -29,7 +29,7 @@ public void WhenAValueIsEncryptedThenItIsVersionedAndDecrypts() var encrypted = encryptor.Encrypt("FooBar"); // Assert - encrypted.Should().MatchRegex(@"^AES256-GCM\$[A-Za-z0-9+/=]+\$[A-Za-z0-9+/=]+$"); + encrypted.Should().MatchRegex(@"^AESGCM-V1\$[A-Za-z0-9+/=]{16}\$[A-Za-z0-9+/=]{24}\$[A-Za-z0-9+/=]+$"); encryptor.RequiresReEncryption(encrypted).Should().BeFalse(); encryptor.Decrypt(encrypted).Should().Be("FooBar"); } @@ -49,8 +49,8 @@ public void WhenACurrentValueWasEncryptedWithAnotherKeyThenALegacyKeyIsNotTried( decrypt.Should().Throw(); } - [TestCase("AES128-GCM")] - [TestCase("aes256-gcm")] + [TestCase("AESGCM-V2")] + [TestCase("aesgcm-v1")] public void WhenTheSpecifierIsAlteredThenDecryptionFails(string alteredSpecifier) { // Arrange diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs index b58bdb4a8..682529aa7 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs @@ -7,11 +7,11 @@ namespace Octopus.Tentacle.Configuration.Crypto { - // Stored as AES256-GCM$base64(nonce)$base64(ciphertext || tag), with the specifier as associated data. + // Stored as AESGCM-V1$base64(nonce)$base64(tag)$base64(ciphertext), with the specifier as associated data. // Values without a $ were written by earlier versions with AES-CBC and a fixed IV. public class LinuxMachineKeyEncryptor : IMachineKeyEncryptor { - public const string Specifier = "AES256-GCM"; + public const string Specifier = "AESGCM-V1"; // $ is not a base64 character, so a value without one is unambiguously a legacy one. const char FieldSeparator = '$'; @@ -56,20 +56,18 @@ public string Encrypt(string raw) static string EncryptCurrent(byte[] key, string raw) { - var plaintext = Encoding.UTF8.GetBytes(raw); - var payload = new byte[NonceSizeInBytes + plaintext.Length + TagSizeInBytes]; + var nonce = new byte[NonceSizeInBytes]; using (var random = RandomNumberGenerator.Create()) { - var nonce = new byte[NonceSizeInBytes]; random.GetBytes(nonce); - Buffer.BlockCopy(nonce, 0, payload, 0, NonceSizeInBytes); } - Gcm.Encrypt(key, plaintext, payload, AssociatedData); + var plaintext = Encoding.UTF8.GetBytes(raw); + var ciphertext = new byte[plaintext.Length]; + var tag = new byte[TagSizeInBytes]; + Gcm.Encrypt(key, nonce, plaintext, ciphertext, tag, AssociatedData); - var nonceBase64 = Convert.ToBase64String(payload, 0, NonceSizeInBytes); - var ciphertextBase64 = Convert.ToBase64String(payload, NonceSizeInBytes, payload.Length - NonceSizeInBytes); - return string.Join(FieldSeparator.ToString(), Specifier, nonceBase64, ciphertextBase64); + return string.Join(FieldSeparator.ToString(), Specifier, Convert.ToBase64String(nonce), Convert.ToBase64String(tag), Convert.ToBase64String(ciphertext)); } string EncryptLegacy(string raw) @@ -123,9 +121,8 @@ string DecryptCurrent(string encrypted) try { - var payload = ParsePayload(encrypted); - - var plaintext = Gcm.Decrypt(key, payload, AssociatedData); + var (nonce, tag, ciphertext) = ParsePayload(encrypted); + var plaintext = Gcm.Decrypt(key, nonce, ciphertext, tag, AssociatedData); return StrictUtf8.GetString(plaintext); } catch (Exception e) @@ -137,12 +134,12 @@ string DecryptCurrent(string encrypted) } } - static byte[] ParsePayload(string encrypted) + static (byte[] Nonce, byte[] Tag, byte[] Ciphertext) ParsePayload(string encrypted) { var fields = encrypted.Split(FieldSeparator); - if (fields.Length != 3) + if (fields.Length != 4) { - throw new FormatException($"Expected 3 '{FieldSeparator}'-separated fields but found {fields.Length}."); + throw new FormatException($"Expected 4 '{FieldSeparator}'-separated fields but found {fields.Length}."); } if (fields[0] != Specifier) @@ -151,13 +148,13 @@ static byte[] ParsePayload(string encrypted) } var nonce = Convert.FromBase64String(fields[1]); - var ciphertextAndTag = Convert.FromBase64String(fields[2]); - if (nonce.Length != NonceSizeInBytes || ciphertextAndTag.Length < TagSizeInBytes) + var tag = Convert.FromBase64String(fields[2]); + if (nonce.Length != NonceSizeInBytes || tag.Length != TagSizeInBytes) { throw new FormatException("The nonce or authentication tag has the wrong length."); } - return nonce.Concat(ciphertextAndTag).ToArray(); + return (nonce, tag, Convert.FromBase64String(fields[3])); } string DecryptLegacy(string encrypted) @@ -186,35 +183,26 @@ string DecryptLegacy(string encrypted) // Only reachable on .NET (Core): the .NET Framework build only runs on Windows, which uses DPAPI instead. static class Gcm { - public static void Encrypt(byte[] key, byte[] plaintext, byte[] payload, byte[] associatedData) + public static void Encrypt(byte[] key, byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[] associatedData) { #if NETFRAMEWORK throw new PlatformNotSupportedException("The Linux machine key scheme is not available on .NET Framework."); #else EnsureSupported(); using var aes = new AesGcm(key, TagSizeInBytes); - aes.Encrypt(payload.AsSpan(0, NonceSizeInBytes), - plaintext, - payload.AsSpan(NonceSizeInBytes, plaintext.Length), - payload.AsSpan(NonceSizeInBytes + plaintext.Length, TagSizeInBytes), - associatedData); + aes.Encrypt(nonce, plaintext, ciphertext, tag, associatedData); #endif } - public static byte[] Decrypt(byte[] key, byte[] payload, byte[] associatedData) + public static byte[] Decrypt(byte[] key, byte[] nonce, byte[] ciphertext, byte[] tag, byte[] associatedData) { #if NETFRAMEWORK throw new PlatformNotSupportedException("The Linux machine key scheme is not available on .NET Framework."); #else EnsureSupported(); - var ciphertextLength = payload.Length - NonceSizeInBytes - TagSizeInBytes; - var plaintext = new byte[ciphertextLength]; + var plaintext = new byte[ciphertext.Length]; using var aes = new AesGcm(key, TagSizeInBytes); - aes.Decrypt(payload.AsSpan(0, NonceSizeInBytes), - payload.AsSpan(NonceSizeInBytes, ciphertextLength), - payload.AsSpan(NonceSizeInBytes + ciphertextLength, TagSizeInBytes), - plaintext, - associatedData); + aes.Decrypt(nonce, ciphertext, tag, plaintext, associatedData); return plaintext; #endif } diff --git a/testing/docker-linux/test-config-encryption-upgrade.sh b/testing/docker-linux/test-config-encryption-upgrade.sh index 44c0dacc5..1e25daa49 100755 --- a/testing/docker-linux/test-config-encryption-upgrade.sh +++ b/testing/docker-linux/test-config-encryption-upgrade.sh @@ -38,7 +38,7 @@ check "the agent re-encrypts with the previous machine-id mounted" \ "$(grep -c "Re-encrypted the protected setting 'Tentacle.Certificate'" <<<"$OUTPUT")" "1" check "the certificate carries the versioned prefix" \ - "$(in_container "$NEW_IMAGE" 'grep -cF "key=\"Tentacle.Certificate\">AES256-GCM\$" /etc/octopus/tentacle.config')" "1" + "$(in_container "$NEW_IMAGE" 'grep -cF "key=\"Tentacle.Certificate\">AESGCM-V1\$" /etc/octopus/tentacle.config')" "1" check "the key is owner-only" "$(in_container "$NEW_IMAGE" 'stat -c %a /var/octopus/tentacle/keys/Tentacle/config-encryption.key')" "600" check "the key is not beside the configuration" "$(in_container "$NEW_IMAGE" 'test -e /etc/octopus/config-encryption.key && echo present || echo absent')" "absent" check "the thumbprint is unchanged without the previous machine-id" "$(in_container "$NEW_IMAGE" 'tentacle show-thumbprint --instance Tentacle')" "$THUMBPRINT" From 7a9e934c2438f3dc2cbbb1277dacaefb85675087 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 09:52:41 +1100 Subject: [PATCH 016/124] Keep the configuration encryption key under each instance's data directory --- docker/linux/scripts/configure-and-run.sh | 4 ++-- docker/readme.md | 2 +- linux-packages/test-scripts/test-linux-package.sh | 2 +- source/Octopus.Tentacle.Core/Util/EnvironmentVariables.cs | 2 +- .../Support/TentacleBuilder.cs | 2 +- .../TentacleCommandLineTests.cs | 4 ++-- .../Crypto/LinuxGeneratedMachineKeyFixture.cs | 2 +- .../Configuration/Crypto/ConfigurationEncryptionKey.cs | 8 ++++---- source/Octopus.Tentacle/Startup/ServiceCommand.cs | 2 +- testing/docker-linux/test-config-encryption-upgrade.sh | 8 ++++---- 10 files changed, 18 insertions(+), 18 deletions(-) diff --git a/docker/linux/scripts/configure-and-run.sh b/docker/linux/scripts/configure-and-run.sh index 5c449fcde..6689e10e0 100644 --- a/docker/linux/scripts/configure-and-run.sh +++ b/docker/linux/scripts/configure-and-run.sh @@ -5,8 +5,8 @@ set -eu is_on_volume() { [ "$(stat -c %d "$1")" != "$(stat -c %d /)" ]; } is_persisted() { mkdir -p "$1" && is_on_volume "$1"; } is_file_persisted() { [ -e "$1" ] && is_on_volume "$1"; } -if { is_persisted /etc/octopus || is_file_persisted /etc/octopus/tentacle.config; } && ! is_persisted /var/octopus/tentacle/keys; then - echo "/etc/octopus or /etc/octopus/tentacle.config is persisted but /var/octopus/tentacle/keys is not. The configuration cannot be decrypted without its key once this container is re-created. Mount /var/octopus/tentacle/keys on a volume too." >&2 +if { is_persisted /etc/octopus || is_file_persisted /etc/octopus/tentacle.config; } && ! is_persisted /var/lib/octopus/tentacle; then + echo "/etc/octopus or /etc/octopus/tentacle.config is persisted but /var/lib/octopus/tentacle is not. The configuration cannot be decrypted without its key once this container is re-created. Mount /var/lib/octopus/tentacle on a volume too." >&2 exit 1 fi diff --git a/docker/readme.md b/docker/readme.md index 41dda7e9b..c71cd5bda 100644 --- a/docker/readme.md +++ b/docker/readme.md @@ -75,7 +75,7 @@ Mount these to keep the Tentacle's identity when the container is re-created: | Path | Contains | | --- | --- | | `/etc/octopus` | Configuration, including the certificate | -| `/var/octopus/tentacle/keys` | Key that encrypts the configuration | +| `/var/lib/octopus/tentacle` | Keys that encrypt the configuration of every instance | Mount both or neither: the configuration can't be decrypted without its key. Configuration persisted by an earlier image can't be upgraded; start on new volumes. diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh index 22a4faf3c..c5c72bdd5 100644 --- a/linux-packages/test-scripts/test-linux-package.sh +++ b/linux-packages/test-scripts/test-linux-package.sh @@ -59,7 +59,7 @@ echo "" # A new certificate must be encrypted with the instance's generated key, not one derived from /etc/machine-id. INSTANCE_NAME="package-test" CONFIGURATION_FILE="/etc/octopus/$INSTANCE_NAME/tentacle.config" -MACHINE_KEY_FILE="/var/octopus/tentacle/keys/$INSTANCE_NAME/config-encryption.key" +MACHINE_KEY_FILE="/var/lib/octopus/tentacle/$INSTANCE_NAME/keys/config-encryption.key" mkdir -p "$(dirname "$CONFIGURATION_FILE")" Tentacle create-instance --instance "$INSTANCE_NAME" --config "$CONFIGURATION_FILE" diff --git a/source/Octopus.Tentacle.Core/Util/EnvironmentVariables.cs b/source/Octopus.Tentacle.Core/Util/EnvironmentVariables.cs index 616441848..a66e43850 100644 --- a/source/Octopus.Tentacle.Core/Util/EnvironmentVariables.cs +++ b/source/Octopus.Tentacle.Core/Util/EnvironmentVariables.cs @@ -27,7 +27,7 @@ public static class EnvironmentVariables public const string TentacleTcpKeepAliveEnabled = "TentacleTcpKeepAliveEnabled"; public const string TentacleEnableDataStreamLengthChecks = "TentacleEnableDataStreamLengthChecks"; public const string TentacleMachineConfigurationHomeDirectory = "TentacleMachineConfigurationHomeDirectory"; - public const string TentacleConfigurationKeysDirectory = "TentacleConfigurationKeysDirectory"; + public const string TentacleInstancesDataDirectory = "TentacleInstancesDataDirectory"; public const string TentaclePollingConnectionCount = "TentaclePollingConnectionCount"; public const string TentaclePowerShellStartupTimeout = "TentaclePowerShellStartupTimeout"; public const string NfsWatchdogDirectory = "watchdog_directory"; diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs index 3f7924426..061ad766b 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs @@ -323,7 +323,7 @@ protected void ConfigureTentacleMachineConfigurationHomeDirectory() WithRunTentacleEnvironmentVariable(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, directory); } - WithRunTentacleEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory, Path.Combine(HomeDirectory.DirectoryPath, "keys")); + WithRunTentacleEnvironmentVariable(EnvironmentVariables.TentacleInstancesDataDirectory, Path.Combine(HomeDirectory.DirectoryPath, "data")); } async Task SetEnvironmentVariablesForService(string instanceName, TemporaryDirectory tempDirectory, ILogger logger, CancellationToken cancellationToken) diff --git a/source/Octopus.Tentacle.Tests.Integration/TentacleCommandLineTests.cs b/source/Octopus.Tentacle.Tests.Integration/TentacleCommandLineTests.cs index 96389ff5f..e5fa80baf 100644 --- a/source/Octopus.Tentacle.Tests.Integration/TentacleCommandLineTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/TentacleCommandLineTests.cs @@ -725,9 +725,9 @@ FileVersionInfo GetVersionInfo(TentacleConfigurationTestCase tentacleConfigurati environmentVariablesToRunTentacleWith.Add(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, tempDirectory.DirectoryPath); } - if (!environmentVariablesToRunTentacleWith.ContainsKey(EnvironmentVariables.TentacleConfigurationKeysDirectory)) + if (!environmentVariablesToRunTentacleWith.ContainsKey(EnvironmentVariables.TentacleInstancesDataDirectory)) { - environmentVariablesToRunTentacleWith.Add(EnvironmentVariables.TentacleConfigurationKeysDirectory, Path.Combine(tempDirectory.DirectoryPath, "keys")); + environmentVariablesToRunTentacleWith.Add(EnvironmentVariables.TentacleInstancesDataDirectory, Path.Combine(tempDirectory.DirectoryPath, "data")); } var tentacleExe = TentacleExeFinder.FindTentacleExe(tentacleConfigurationTestCase.TentacleRuntime); diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs index 3be7b2b4b..4db41b01e 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs @@ -53,7 +53,7 @@ public void GivenMachineIdFileIsValidLength_ThenReturnsKeys() [Test] public void KeyFileIsKeptPerInstanceOutsideTheConfigurationDirectory() { - ConfigurationEncryptionKey.KeyFilePathFor("Tentacle").Should().Be("/var/octopus/tentacle/keys/Tentacle/config-encryption.key"); + ConfigurationEncryptionKey.KeyFilePathFor("Tentacle").Should().Be("/var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key"); } [TestCase("")] diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index e2e37c28b..5c7d0904d 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -15,7 +15,7 @@ public class ConfigurationEncryptionKey public const string KeyFileName = "config-encryption.key"; // Kept apart from /etc/octopus so that a copy of the configuration does not also carry the key that decrypts it. - public const string DefaultKeysDirectory = "/var/octopus/tentacle/keys"; + public const string DefaultInstancesDataDirectory = "/var/lib/octopus/tentacle"; const int KeySizeInBytes = 32; @@ -28,8 +28,8 @@ public class ConfigurationEncryptionKey + "run `replace-certificate` with an API key. " + "This creates a new key and certificate, and updates every deployment target and worker registered with the old certificate to trust it."; - static string KeysDirectory - => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory) is { Length: > 0 } directory ? directory : DefaultKeysDirectory; + static string InstancesDataDirectory + => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleInstancesDataDirectory) is { Length: > 0 } directory ? directory : DefaultInstancesDataDirectory; readonly ISystemLog log; readonly IOctopusFileSystem fileSystem; @@ -57,7 +57,7 @@ public static string KeyFilePathFor(string instanceName) throw new ArgumentException($"The instance name `{instanceName}` cannot be used as a key directory name.", nameof(instanceName)); } - return JoinLinuxPath(JoinLinuxPath(KeysDirectory, instanceName), KeyFileName); + return JoinLinuxPath(JoinLinuxPath(JoinLinuxPath(InstancesDataDirectory, instanceName), "keys"), KeyFileName); } public byte[] Load() diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs index 3eb479805..a3949bce0 100644 --- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs +++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs @@ -128,7 +128,7 @@ protected override void Start() { ConfigurationFilePermissions.RestrictToServiceUser(instanceSelector.Current.ConfigurationPath, serviceConfigurationState.Username, log); - // A non-root service cannot create its key under /var/octopus, so it is created here while running as root. + // A non-root service cannot create its key under /var/lib/octopus, so it is created here while running as root. configurationUpgrade.Value.TryPrepareKey(); } } diff --git a/testing/docker-linux/test-config-encryption-upgrade.sh b/testing/docker-linux/test-config-encryption-upgrade.sh index 1e25daa49..bc6b7a5b9 100755 --- a/testing/docker-linux/test-config-encryption-upgrade.sh +++ b/testing/docker-linux/test-config-encryption-upgrade.sh @@ -10,9 +10,9 @@ set -euo pipefail NEW_IMAGE=$1 PREVIOUS_IMAGE=${2:-octopusdeploy/tentacle:latest} VOLUME="tentacle-config-upgrade-$$" -KEYS_VOLUME="tentacle-keys-upgrade-$$" +DATA_VOLUME="tentacle-data-upgrade-$$" WORK_DIR=$(mktemp -d) -trap 'docker volume rm -f "$VOLUME" "$KEYS_VOLUME" >/dev/null; rm -rf "$WORK_DIR"' EXIT +trap 'docker volume rm -f "$VOLUME" "$DATA_VOLUME" >/dev/null; rm -rf "$WORK_DIR"' EXIT FAILURES=0 check() { @@ -22,7 +22,7 @@ check() { in_container() { local image=$1 command=$2 shift 2 - docker run --rm -v "$VOLUME:/etc/octopus" -v "$KEYS_VOLUME:/var/octopus/tentacle/keys" "$@" --entrypoint bash "$image" -c "$command" 2>&1 + docker run --rm -v "$VOLUME:/etc/octopus" -v "$DATA_VOLUME:/var/lib/octopus/tentacle" "$@" --entrypoint bash "$image" -c "$command" 2>&1 } in_container "$PREVIOUS_IMAGE" 'tentacle create-instance --instance Tentacle --config /etc/octopus/tentacle.config >/dev/null && tentacle new-certificate --instance Tentacle >/dev/null' @@ -39,7 +39,7 @@ check "the agent re-encrypts with the previous machine-id mounted" \ check "the certificate carries the versioned prefix" \ "$(in_container "$NEW_IMAGE" 'grep -cF "key=\"Tentacle.Certificate\">AESGCM-V1\$" /etc/octopus/tentacle.config')" "1" -check "the key is owner-only" "$(in_container "$NEW_IMAGE" 'stat -c %a /var/octopus/tentacle/keys/Tentacle/config-encryption.key')" "600" +check "the key is owner-only" "$(in_container "$NEW_IMAGE" 'stat -c %a /var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key')" "600" check "the key is not beside the configuration" "$(in_container "$NEW_IMAGE" 'test -e /etc/octopus/config-encryption.key && echo present || echo absent')" "absent" check "the thumbprint is unchanged without the previous machine-id" "$(in_container "$NEW_IMAGE" 'tentacle show-thumbprint --instance Tentacle')" "$THUMBPRINT" From 6793c4c2292e8ffd0f1dd1e62685e8ceea4ccddf Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 10:30:45 +1100 Subject: [PATCH 017/124] Test that a lost key leaves migrated values untouched; run upgrade fixture on macOS --- .../TentacleConfigurationUpgradeFixture.cs | 21 +++++++++++++++- .../TestAttributes/LinuxOrMacTestAttribute.cs | 24 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 source/Octopus.Tentacle.Tests/Support/TestAttributes/LinuxOrMacTestAttribute.cs diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs index 40ae3f573..ac88e370b 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs @@ -21,7 +21,7 @@ namespace Octopus.Tentacle.Tests.Configuration { [TestFixture] - [LinuxTest] + [LinuxOrMacTest] public class TentacleConfigurationUpgradeFixture { const string Certificate = "MIIC...the certificate..."; @@ -171,6 +171,25 @@ public void AValueProtectedWithTheKeyIsNeverRewrittenWithALegacyKey() RawCertificate().Should().Be(protectedValue); } + [Test] + public void WhenTheKeyIsLostAfterMigrationThenStartLeavesProtectedValuesUntouched() + { + // Arrange + var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); + var store = CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + CreateUpgrade(store, keyFilePath).Upgrade(); + var protectedValue = RawCertificate(); + File.Delete(keyFilePath); + + // Act + CreateUpgrade(CreateStore(keyFilePath), keyFilePath).Upgrade(); + + // Assert + RawCertificate().Should().Be(protectedValue); + RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); + } + readonly InMemoryCryptoKeyNixSource legacyKey = new(); XmlFileKeyValueStore CreateStore(string keyFilePath) diff --git a/source/Octopus.Tentacle.Tests/Support/TestAttributes/LinuxOrMacTestAttribute.cs b/source/Octopus.Tentacle.Tests/Support/TestAttributes/LinuxOrMacTestAttribute.cs new file mode 100644 index 000000000..c13618721 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Support/TestAttributes/LinuxOrMacTestAttribute.cs @@ -0,0 +1,24 @@ +using System; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Tests.Support.TestAttributes +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] + public class LinuxOrMacTestAttribute : NUnitAttribute, IApplyToTest + { + public void ApplyToTest(Test test) + { + if (test.RunState == RunState.NotRunnable || test.RunState == RunState.Ignored) + return; + + if (!PlatformDetection.IsRunningOnNix && !PlatformDetection.IsRunningOnMac) + { + test.RunState = RunState.Skipped; + test.Properties.Add("_SKIPREASON", "This test only runs on Linux or macOS"); + } + } + } +} From 3e06c128a721ebc9d1beb83cd14a4a0391d08109 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 11:29:56 +1100 Subject: [PATCH 018/124] Pass the test encryptor to the configuration builder's store --- .../Support/TentacleConfigurationBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs index c4c93919c..e2b289604 100644 --- a/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs +++ b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs @@ -26,7 +26,7 @@ public TemporaryTentacleConfiguration Build() var directory = new TemporaryDirectory(fileSystem); var configFile = Path.Combine(directory.DirectoryPath, "Tentacle.config"); File.WriteAllText(configFile, $"{settings}"); - var store = new XmlFileKeyValueStore(fileSystem, configFile); + var store = new XmlFileKeyValueStore(fileSystem, configFile, encryptor: TestMachineKeyEncryptor.Current); var selector = Substitute.For(); selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, configFile, store, store)); From 8f6b238426b5798585d98a8a7d56bfa7a8884566 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 12:12:44 +1100 Subject: [PATCH 019/124] Mark the user-only atomic file create as unsupported on Windows Renames it to AtomicCreateFileWithOnlyUserReadWritePermissions, marks it and its callers [UnsupportedOSPlatform("windows")] so an unguarded caller fails to compile, and throws on Windows instead of writing a file with inherited permissions. --- .../PlatformDetection.cs | 4 ++ .../Util/FileSystem/IOctopusFileSystem.cs | 9 ++- .../Util/OctopusPhysicalFileSystem.cs | 56 ++++++++----------- .../Util/PlatformDetection.cs | 4 ++ .../Support/SharedTentacleCryptoState.cs | 4 +- .../LegacyCiphertextCompatibilityFixture.cs | 2 - .../TentacleConfigurationUpgradeFixture.cs | 2 + .../Crypto/ConfigurationEncryptionKey.cs | 6 +- .../RetryingKubernetesPhysicalFileSystem.cs | 8 ++- 9 files changed, 55 insertions(+), 40 deletions(-) diff --git a/source/Octopus.Tentacle.CommonTestUtils/PlatformDetection.cs b/source/Octopus.Tentacle.CommonTestUtils/PlatformDetection.cs index d2200fd70..1fcd238c3 100644 --- a/source/Octopus.Tentacle.CommonTestUtils/PlatformDetection.cs +++ b/source/Octopus.Tentacle.CommonTestUtils/PlatformDetection.cs @@ -1,11 +1,15 @@ using System; using System.Runtime.InteropServices; +using System.Runtime.Versioning; namespace Octopus.Tentacle.CommonTestUtils { public static class PlatformDetection { public static bool IsRunningOnNix => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); +#if NET + [SupportedOSPlatformGuard("windows")] +#endif public static bool IsRunningOnWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); public static bool IsRunningOnMac => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); diff --git a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs index f75710d0a..f004248bb 100644 --- a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -40,10 +41,14 @@ public interface IOctopusFileSystem /// /// Creates a file at filePath with contents IF it doesn't exist. /// The operation is as atomic as it can be for the FileSystem. - /// The resulting file has permissions 0600 for linux. + /// The resulting file has permissions 0600. + /// Unix only: throws on Windows. /// /// True if this call created the file, false if it already existed, in which case the existing file is left untouched. - bool AtomicCreateFileWithUserReadWriteAccessOnly(string filePath, byte[] contents); +#if NET + [UnsupportedOSPlatform("windows")] +#endif + bool AtomicCreateFileWithOnlyUserReadWritePermissions(string filePath, byte[] contents); string ReadAllText(string scriptFile); string[] ReadAllLines(string scriptFile); diff --git a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs index edeca02b6..c2f45cfab 100644 --- a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Reflection; +using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -15,6 +16,7 @@ namespace Octopus.Tentacle.Core.Util public class CorePhysicalFileSystem : IOctopusFileSystem { const long FiveHundredMegabytes = 500 * 1024 * 1024; + const string UserOnlyFilesAreUnixOnly = "Creating a file that only its owner can read and write is only supported on Linux and macOS."; public CorePhysicalFileSystem(ISystemLog log, bool isRunningAsKubernetesAgent) { @@ -250,13 +252,21 @@ public void WriteAllText(string path, string contents) File.WriteAllText(path, contents); } - public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) +#if NET + [UnsupportedOSPlatform("windows")] + public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents) { + if (OperatingSystem.IsWindows()) + { + throw new PlatformNotSupportedException(UserOnlyFilesAreUnixOnly); + } + var temporaryPath = TemporaryPathBeside(path); try { CreateFileWithUserReadWriteAccessOnly(temporaryPath, contents); - return PublishWithoutReplacing(temporaryPath, path); + // Unlike File.Move, link(2) is atomic about not replacing: two racing processes cannot each keep their own file. + return UnixFile.TryLinkWithoutReplacing(temporaryPath, path); } finally { @@ -264,44 +274,22 @@ public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] cont } } + [UnsupportedOSPlatform("windows")] static void CreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) { -#if NETFRAMEWORK - using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); -#else - var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None }; - if (!OperatingSystem.IsWindows()) + var options = new FileStreamOptions { - options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; - } + Mode = FileMode.CreateNew, + Access = FileAccess.Write, + Share = FileShare.None, + UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite + }; using var stream = new FileStream(path, options); -#endif stream.Write(contents, 0, contents.Length); stream.Flush(flushToDisk: true); } - static bool PublishWithoutReplacing(string temporaryPath, string path) - { -#if !NETFRAMEWORK - if (!PlatformDetection.IsRunningOnWindows) - { - // Unlike File.Move, link(2) is atomic about not replacing: two racing processes cannot each keep their own file. - return UnixFile.TryLinkWithoutReplacing(temporaryPath, path); - } -#endif - try - { - // MoveFile never replaces an existing file. - File.Move(temporaryPath, path); - return true; - } - catch (IOException) when (File.Exists(path)) - { - return false; - } - } - static void DeleteIfExists(string path) { if (File.Exists(path)) @@ -310,9 +298,13 @@ static void DeleteIfExists(string path) } } - // In the same directory, so it is on the same file system and can be moved into place atomically. + // In the same directory, so it is on the same file system and can be linked into place atomically. static string TemporaryPathBeside(string path) => path + "." + Guid.NewGuid().ToString("N") + ".tmp"; +#else + public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents) + => throw new PlatformNotSupportedException(UserOnlyFilesAreUnixOnly); +#endif public void EnsureDirectoryExists(string directoryPath) { diff --git a/source/Octopus.Tentacle.Core/Util/PlatformDetection.cs b/source/Octopus.Tentacle.Core/Util/PlatformDetection.cs index 3d7b219d7..c536b6b2c 100644 --- a/source/Octopus.Tentacle.Core/Util/PlatformDetection.cs +++ b/source/Octopus.Tentacle.Core/Util/PlatformDetection.cs @@ -1,11 +1,15 @@ using System; using System.Runtime.InteropServices; +using System.Runtime.Versioning; namespace Octopus.Tentacle.Util { public static class PlatformDetection { public static bool IsRunningOnNix => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); +#if NET + [SupportedOSPlatformGuard("windows")] +#endif public static bool IsRunningOnWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); public static bool IsRunningOnMac => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs index 0a52bdb51..b6a622e7d 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using System.Runtime.Versioning; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; @@ -81,6 +82,7 @@ static void CreateTheFallbackKeyEarlierVersionsShare(SystemLog log) } } + [UnsupportedOSPlatform("windows")] static void CreateLegacyMachineKeyIfMissing(OctopusPhysicalFileSystem fileSystem, string path) { if (fileSystem.FileExists(path)) @@ -93,7 +95,7 @@ static void CreateLegacyMachineKeyIfMissing(OctopusPhysicalFileSystem fileSystem aes.GenerateKey(); var contents = Convert.ToBase64String(aes.Key) + "." + Convert.ToBase64String(aes.IV); fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(path)!); - fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(path, Encoding.ASCII.GetBytes(contents)); + fileSystem.AtomicCreateFileWithOnlyUserReadWritePermissions(path, Encoding.ASCII.GetBytes(contents)); } // A Tentacle only reuses the stored certificate when it comes back with its private key. diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs index cd6a9a4bc..792fa3aa8 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using FluentAssertions; using NSubstitute; using NUnit.Framework; @@ -112,7 +111,6 @@ public IOctopusFileSystem CreateFileSystem() var fileSystem = Substitute.For(); fileSystem.FileExists(Arg.Any()).Returns(ci => Contents.ContainsKey(ci.ArgAt(0))); fileSystem.ReadAllText(Arg.Any()).Returns(ci => Contents[ci.ArgAt(0)]); - fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(Arg.Any(), Arg.Any()).Returns(ci => Contents.TryAdd(ci.ArgAt(0), Encoding.ASCII.GetString(ci.ArgAt(1)))); return fileSystem; } } diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs index ac88e370b..56cc29528 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs @@ -2,6 +2,7 @@ using System; using System.IO; using System.Linq; +using System.Runtime.Versioning; using System.Security.Cryptography; using System.Xml.Linq; using FluentAssertions; @@ -22,6 +23,7 @@ namespace Octopus.Tentacle.Tests.Configuration { [TestFixture] [LinuxOrMacTest] + [UnsupportedOSPlatform("windows")] public class TentacleConfigurationUpgradeFixture { const string Certificate = "MIIC...the certificate..."; diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index 5c7d0904d..797d6cbd1 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using Octopus.Tentacle.Core.Diagnostics; @@ -81,6 +82,9 @@ public byte[] Load() return loaded; } +#if NET + [UnsupportedOSPlatform("windows")] +#endif public void CreateIfMissing() { var path = KeyFilePath ?? throw new InvalidOperationException("There is no key file path to create the configuration encryption key at."); @@ -94,7 +98,7 @@ public void CreateIfMissing() CreateKeyDirectory(KeyDirectory!); // Several instances starting at once after an upgrade must all end up with the same key. - if (!fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(path, Encoding.ASCII.GetBytes(raw))) + if (!fileSystem.AtomicCreateFileWithOnlyUserReadWritePermissions(path, Encoding.ASCII.GetBytes(raw))) { log.Verbose($"Another process created the configuration encryption key `{path}` first; using its key."); return; diff --git a/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs b/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs index f2bb10ad5..6cdc1f477 100644 --- a/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -139,9 +140,12 @@ public void WriteAllText(string filePath, string contents) syncRetryPolicy.Execute(() => inner.WriteAllText(filePath, contents)); } - public bool AtomicCreateFileWithUserReadWriteAccessOnly(string filePath, byte[] contents) +#if NET + [UnsupportedOSPlatform("windows")] +#endif + public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string filePath, byte[] contents) { - return syncRetryPolicy.Execute(() => inner.AtomicCreateFileWithUserReadWriteAccessOnly(filePath, contents)); + return syncRetryPolicy.Execute(() => inner.AtomicCreateFileWithOnlyUserReadWritePermissions(filePath, contents)); } public string ReadAllText(string scriptFile) From 804a0f5a145bbd6a79ae0eae5d98434a0e4cb05e Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 12:21:44 +1100 Subject: [PATCH 020/124] Replace the config encryption shell test with Docker integration tests --- .../LinuxTentacleConfigEncryptionTests.cs | 76 +++++++++++++++++++ .../Setup/DockerCli.cs | 10 +++ .../Setup/DockerVolume.cs | 33 ++++++++ .../Setup/TentacleContainerBuilder.cs | 12 +++ testing/README.md | 2 +- .../build-and-test-linux-docker-image.sh | 7 -- .../test-config-encryption-upgrade.sh | 49 ------------ 7 files changed, 132 insertions(+), 57 deletions(-) create mode 100644 source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs create mode 100644 source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerVolume.cs delete mode 100755 testing/docker-linux/test-config-encryption-upgrade.sh diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs new file mode 100644 index 000000000..c28aa60a1 --- /dev/null +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs @@ -0,0 +1,76 @@ +using FluentAssertions; +using Octopus.Tentacle.Docker.Tests.Integration.Setup; + +namespace Octopus.Tentacle.Docker.Tests.Integration; + +/// +/// The image encrypts tentacle.config with a key generated in /var/lib/octopus/tentacle, so both must be persisted for +/// a re-created container to read its configuration. +/// +public class LinuxTentacleConfigEncryptionTests +{ + const string ConfigDirectory = "/etc/octopus"; + const string DataDirectory = "/var/lib/octopus/tentacle"; + const string KeyFile = DataDirectory + "/Tentacle/keys/config-encryption.key"; + + static readonly TimeSpan DockerCommandTimeout = TimeSpan.FromMinutes(10); + + [Test] + public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey() + { + await using var config = await DockerVolume.Create(CancellationToken.None); + await using var data = await DockerVolume.Create(CancellationToken.None); + await using var server = await new FakeOctopusServerBuilder().Build(); + + string? thumbprint; + await using (var tentacle = await new TentacleContainerBuilder(server) + .WithVolume(config, ConfigDirectory) + .WithVolume(data, DataDirectory) + .Build()) + { + thumbprint = tentacle.RegisteredMachine.Thumbprint; + } + + var image = TentacleImage.Resolve(); + (await RunInImage(image, $"stat -c %a {KeyFile}", config, data)).Should().Be("600"); + (await RunInImage(image, $"grep -cF 'key=\"Tentacle.Certificate\">AESGCM-V1$' {ConfigDirectory}/tentacle.config", config, data)).Should().Be("1"); + (await RunInImage(image, "tentacle show-thumbprint --instance Tentacle", config, data)).Should().Be(thumbprint); + } + + [Test] + public async Task TheContainerRefusesToStartWhenOnlyTheConfigurationIsPersisted() + { + await using var config = await DockerVolume.Create(CancellationToken.None); + using var cancellationTokenSource = new CancellationTokenSource(DockerCommandTimeout); + + var (exitCode, output) = await DockerCli.RunUnchecked(new[] + { + "run", "--rm", "--label", DockerCli.ContainerLabel, + "--volume", config.MountAt(ConfigDirectory), + "--env", "ACCEPT_EULA=Y", + TentacleImage.Resolve() + }, cancellationTokenSource.Token); + + exitCode.Should().NotBe(0); + output.Should().Contain($"{DataDirectory} is not"); + } + + static async Task RunInImage(string image, string command, DockerVolume config, DockerVolume data) + { + using var cancellationTokenSource = new CancellationTokenSource(DockerCommandTimeout); + var arguments = new List + { + "run", "--rm", "--label", DockerCli.ContainerLabel, + "--volume", config.MountAt(ConfigDirectory), + "--volume", data.MountAt(DataDirectory), + "--entrypoint", "bash" + }; + arguments.AddRange(new[] { image, "-c", command }); + + var (exitCode, output) = await DockerCli.RunUnchecked(arguments, cancellationTokenSource.Token); + TestContext.Out.WriteLine($"$ {command} (exit code {exitCode})\n{output}"); + exitCode.Should().Be(0, output); + + return output.Trim(); + } +} diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs index 1122f1ed6..3c96384e3 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs @@ -29,6 +29,16 @@ public static async Task Run(IEnumerable arguments, Cancellation return result.StandardOutput.Trim(); } + /// Runs a docker command that may fail, returning its exit code and combined output. + public static async Task<(int ExitCode, string Output)> RunUnchecked(IEnumerable arguments, CancellationToken cancellationToken) + { + var result = await Cli.Wrap("docker") + .WithArguments(arguments.ToArray()) + .WithValidation(CommandResultValidation.None) + .ExecuteBufferedAsync(Encoding.UTF8, cancellationToken); + return (result.ExitCode, result.StandardOutput + result.StandardError); + } + /// /// `docker logs` writes the container's stdout and stderr to its own stdout and stderr, so ask for both and /// return them together. Never throws: this is called while reporting other failures. diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerVolume.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerVolume.cs new file mode 100644 index 000000000..a800123cc --- /dev/null +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerVolume.cs @@ -0,0 +1,33 @@ +namespace Octopus.Tentacle.Docker.Tests.Integration.Setup; + +/// A named volume, removed when disposed. +public sealed class DockerVolume : IAsyncDisposable +{ + DockerVolume(string name) + { + Name = name; + } + + public string Name { get; } + + public static async Task Create(CancellationToken cancellationToken) + { + var name = $"tentacle-docker-test-{Guid.NewGuid():N}"; + await DockerCli.Run(new[] { "volume", "create", "--label", DockerCli.ContainerLabel, name }, cancellationToken); + return new DockerVolume(name); + } + + public string MountAt(string containerPath) => $"{Name}:{containerPath}"; + + public async ValueTask DisposeAsync() + { + try + { + await DockerCli.Run(new[] { "volume", "rm", "--force", Name }, CancellationToken.None); + } + catch (Exception e) + { + TestContext.Progress.WriteLine($"Could not remove volume {Name}: {e.Message}"); + } + } +} diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs index 566c53d87..d36a8f178 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs @@ -20,6 +20,7 @@ public class TentacleContainerBuilder TentacleCommunicationStyle communicationStyle = TentacleCommunicationStyle.Listening; string? workerPoolName; Dictionary credentials = new() { ["ServerApiKey"] = ApiKey }; + readonly List volumeMounts = new(); public TentacleContainerBuilder(FakeOctopusServer server) { @@ -51,6 +52,12 @@ public TentacleContainerBuilder WithUsernameAndPassword(string username, string return this; } + public TentacleContainerBuilder WithVolume(DockerVolume volume, string containerPath) + { + volumeMounts.Add(volume.MountAt(containerPath)); + return this; + } + public async Task Build() { using var cancellationTokenSource = new CancellationTokenSource(DockerCommandTimeout); @@ -85,6 +92,11 @@ IEnumerable RunOptions(string machineName) "--add-host", $"{TentacleContainer.DockerHost}:host-gateway" }; + foreach (var mount in volumeMounts) + { + options.AddRange(new[] { "--volume", mount }); + } + if (communicationStyle == TentacleCommunicationStyle.Listening) { // Publish to a random loopback port: the tests connect to Tentacle from the host. diff --git a/testing/README.md b/testing/README.md index 15d7b157d..3d3ea44b8 100644 --- a/testing/README.md +++ b/testing/README.md @@ -26,7 +26,7 @@ The script runs in four stages, each of which can be skipped: |---|---| | `deb` | Builds the linux-x64 `.deb` via NUKE (`--target PackDebianPackage`) | | `image` | Builds the image with the same `docker-compose.build.yml` command TeamCity runs | -| `smoke` | Asserts the image's contents and behaviour - base image, .NET runtime dependencies, docker-in-docker, entrypoint guards, labels - and upgrades a configuration written by the previous image ([`test-config-encryption-upgrade.sh`](./docker-linux/test-config-encryption-upgrade.sh)) | +| `smoke` | Asserts the image's contents and behaviour - base image, .NET runtime dependencies, docker-in-docker, entrypoint guards, labels | | `e2e` | Stands up SQL Server and an Octopus Server, then registers a listening and a polling Tentacle built from the fresh image | ``` diff --git a/testing/docker-linux/build-and-test-linux-docker-image.sh b/testing/docker-linux/build-and-test-linux-docker-image.sh index ca462c860..78fd391a2 100755 --- a/testing/docker-linux/build-and-test-linux-docker-image.sh +++ b/testing/docker-linux/build-and-test-linux-docker-image.sh @@ -410,13 +410,6 @@ if [[ $SKIP_SMOKE -eq 0 ]]; then NOSERVER_OUT=$(docker run --rm --platform "$PLATFORM" -e ACCEPT_EULA=Y -e ServerApiKey=API-FAKE "$IMAGE" 2>&1 || true) assert_contains "container refuses to start without ServerUrl" "$NOSERVER_OUT" "Please specify an Octopus Server" - - # --- configuration encryption upgrade ------------------------------------ - if UPGRADE_OUT=$("$REPO_DIR/testing/docker-linux/test-config-encryption-upgrade.sh" "$IMAGE" 2>&1); then - pass "configuration from the previous image upgrades to the generated key" - else - fail "configuration from the previous image upgrades to the generated key" "$UPGRADE_OUT" - fi fi ############################################################################### diff --git a/testing/docker-linux/test-config-encryption-upgrade.sh b/testing/docker-linux/test-config-encryption-upgrade.sh deleted file mode 100755 index bc6b7a5b9..000000000 --- a/testing/docker-linux/test-config-encryption-upgrade.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env bash -# -# Upgrades a Tentacle configuration written by a previous image, whose key came from its /etc/machine-id, to a new -# image on the same /etc/octopus and key volumes, following the recovery steps in docker/readme.md. -# -# Usage: ./testing/docker-linux/test-config-encryption-upgrade.sh [previous image] -# -set -euo pipefail - -NEW_IMAGE=$1 -PREVIOUS_IMAGE=${2:-octopusdeploy/tentacle:latest} -VOLUME="tentacle-config-upgrade-$$" -DATA_VOLUME="tentacle-data-upgrade-$$" -WORK_DIR=$(mktemp -d) -trap 'docker volume rm -f "$VOLUME" "$DATA_VOLUME" >/dev/null; rm -rf "$WORK_DIR"' EXIT - -FAILURES=0 -check() { - if [[ "$2" == "$3" ]]; then echo "PASS $1"; else echo "FAIL $1: expected '$3', got '$2'"; FAILURES=$((FAILURES + 1)); fi -} - -in_container() { - local image=$1 command=$2 - shift 2 - docker run --rm -v "$VOLUME:/etc/octopus" -v "$DATA_VOLUME:/var/lib/octopus/tentacle" "$@" --entrypoint bash "$image" -c "$command" 2>&1 -} - -in_container "$PREVIOUS_IMAGE" 'tentacle create-instance --instance Tentacle --config /etc/octopus/tentacle.config >/dev/null && tentacle new-certificate --instance Tentacle >/dev/null' -THUMBPRINT=$(in_container "$PREVIOUS_IMAGE" 'tentacle show-thumbprint --instance Tentacle') -in_container "$PREVIOUS_IMAGE" 'cat /etc/machine-id' > "$WORK_DIR/machine-id" - -OUTPUT=$(in_container "$NEW_IMAGE" 'tentacle show-thumbprint --instance Tentacle' || true) -check "the new image cannot decrypt without the previous machine-id" \ - "$(grep -c 'If the /etc/machine-id it was written with is still available' <<<"$OUTPUT")" "1" - -OUTPUT=$(in_container "$NEW_IMAGE" 'timeout 30 tentacle run --instance Tentacle' -v "$WORK_DIR/machine-id:/etc/machine-id:ro" || true) -check "the agent re-encrypts with the previous machine-id mounted" \ - "$(grep -c "Re-encrypted the protected setting 'Tentacle.Certificate'" <<<"$OUTPUT")" "1" - -check "the certificate carries the versioned prefix" \ - "$(in_container "$NEW_IMAGE" 'grep -cF "key=\"Tentacle.Certificate\">AESGCM-V1\$" /etc/octopus/tentacle.config')" "1" -check "the key is owner-only" "$(in_container "$NEW_IMAGE" 'stat -c %a /var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key')" "600" -check "the key is not beside the configuration" "$(in_container "$NEW_IMAGE" 'test -e /etc/octopus/config-encryption.key && echo present || echo absent')" "absent" -check "the thumbprint is unchanged without the previous machine-id" "$(in_container "$NEW_IMAGE" 'tentacle show-thumbprint --instance Tentacle')" "$THUMBPRINT" - -OUTPUT=$(in_container "$NEW_IMAGE" 'timeout 30 tentacle run --instance Tentacle' || true) -check "the agent starts again without the previous machine-id" "$(grep -c 'Unable to decrypt' <<<"$OUTPUT")" "0" - -exit $((FAILURES > 0)) From ce2e8516e3143e8b0b59708976950beaf0d0b613 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 12:31:44 +1100 Subject: [PATCH 021/124] Mark UnixFile as unsupported on Windows --- source/Octopus.Tentacle.Core/Util/UnixFile.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs index 6b6227f08..6a6cec2c4 100644 --- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -1,10 +1,12 @@ #if !NETFRAMEWORK using System.IO; using System.Runtime.InteropServices; +using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; namespace Octopus.Tentacle.Core.Util { + [UnsupportedOSPlatform("windows")] public static class UnixFile { const uint UnchangedGroup = uint.MaxValue; From b58bba26ae36e186f4b9ae4d2413ad5e833cb24f Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 12:34:45 +1100 Subject: [PATCH 022/124] Inline paths in the config encryption Docker tests --- .../LinuxTentacleConfigEncryptionTests.cs | 41 ++++++++----------- 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs index c28aa60a1..6ab298849 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs @@ -9,12 +9,6 @@ namespace Octopus.Tentacle.Docker.Tests.Integration; /// public class LinuxTentacleConfigEncryptionTests { - const string ConfigDirectory = "/etc/octopus"; - const string DataDirectory = "/var/lib/octopus/tentacle"; - const string KeyFile = DataDirectory + "/Tentacle/keys/config-encryption.key"; - - static readonly TimeSpan DockerCommandTimeout = TimeSpan.FromMinutes(10); - [Test] public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey() { @@ -24,53 +18,50 @@ public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey string? thumbprint; await using (var tentacle = await new TentacleContainerBuilder(server) - .WithVolume(config, ConfigDirectory) - .WithVolume(data, DataDirectory) + .WithVolume(config, "/etc/octopus") + .WithVolume(data, "/var/lib/octopus/tentacle") .Build()) { thumbprint = tentacle.RegisteredMachine.Thumbprint; } - var image = TentacleImage.Resolve(); - (await RunInImage(image, $"stat -c %a {KeyFile}", config, data)).Should().Be("600"); - (await RunInImage(image, $"grep -cF 'key=\"Tentacle.Certificate\">AESGCM-V1$' {ConfigDirectory}/tentacle.config", config, data)).Should().Be("1"); - (await RunInImage(image, "tentacle show-thumbprint --instance Tentacle", config, data)).Should().Be(thumbprint); + (await RunInImage("stat -c %a /var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key", config, data)).Should().Be("600"); + (await RunInImage("grep -cF 'key=\"Tentacle.Certificate\">AESGCM-V1$' /etc/octopus/tentacle.config", config, data)).Should().Be("1"); + (await RunInImage("tentacle show-thumbprint --instance Tentacle", config, data)).Should().Be(thumbprint); } [Test] public async Task TheContainerRefusesToStartWhenOnlyTheConfigurationIsPersisted() { await using var config = await DockerVolume.Create(CancellationToken.None); - using var cancellationTokenSource = new CancellationTokenSource(DockerCommandTimeout); + using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(10)); var (exitCode, output) = await DockerCli.RunUnchecked(new[] { "run", "--rm", "--label", DockerCli.ContainerLabel, - "--volume", config.MountAt(ConfigDirectory), + "--volume", config.MountAt("/etc/octopus"), "--env", "ACCEPT_EULA=Y", TentacleImage.Resolve() }, cancellationTokenSource.Token); exitCode.Should().NotBe(0); - output.Should().Contain($"{DataDirectory} is not"); + output.Should().Contain("/var/lib/octopus/tentacle is not"); } - static async Task RunInImage(string image, string command, DockerVolume config, DockerVolume data) + static async Task RunInImage(string command, DockerVolume config, DockerVolume data) { - using var cancellationTokenSource = new CancellationTokenSource(DockerCommandTimeout); - var arguments = new List + using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(10)); + var (exitCode, output) = await DockerCli.RunUnchecked(new[] { "run", "--rm", "--label", DockerCli.ContainerLabel, - "--volume", config.MountAt(ConfigDirectory), - "--volume", data.MountAt(DataDirectory), - "--entrypoint", "bash" - }; - arguments.AddRange(new[] { image, "-c", command }); + "--volume", config.MountAt("/etc/octopus"), + "--volume", data.MountAt("/var/lib/octopus/tentacle"), + "--entrypoint", "bash", + TentacleImage.Resolve(), "-c", command + }, cancellationTokenSource.Token); - var (exitCode, output) = await DockerCli.RunUnchecked(arguments, cancellationTokenSource.Token); TestContext.Out.WriteLine($"$ {command} (exit code {exitCode})\n{output}"); exitCode.Should().Be(0, output); - return output.Trim(); } } From 3ed61fe9c867ecf2dff31f30c4eae0cf11b55a5b Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:28:48 +1100 Subject: [PATCH 023/124] Start re-created and refusing Tentacles through the container builder --- .../LinuxTentacleConfigEncryptionTests.cs | 60 +++++++++---------- .../Setup/DockerCli.cs | 10 ---- .../Setup/TentacleContainer.cs | 9 +++ .../Setup/TentacleContainerBuilder.cs | 33 +++++++++- 4 files changed, 68 insertions(+), 44 deletions(-) diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs index 6ab298849..4d0205a00 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs @@ -1,4 +1,7 @@ using FluentAssertions; +using Octopus.Tentacle.Client.Scripts.Models.Builders; +using Octopus.Tentacle.CommonTestUtils; +using Octopus.Tentacle.Contracts; using Octopus.Tentacle.Docker.Tests.Integration.Setup; namespace Octopus.Tentacle.Docker.Tests.Integration; @@ -16,52 +19,45 @@ public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey await using var data = await DockerVolume.Create(CancellationToken.None); await using var server = await new FakeOctopusServerBuilder().Build(); - string? thumbprint; + RegisteredMachine registeredMachine; await using (var tentacle = await new TentacleContainerBuilder(server) .WithVolume(config, "/etc/octopus") .WithVolume(data, "/var/lib/octopus/tentacle") .Build()) { - thumbprint = tentacle.RegisteredMachine.Thumbprint; + registeredMachine = tentacle.RegisteredMachine; } - (await RunInImage("stat -c %a /var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key", config, data)).Should().Be("600"); - (await RunInImage("grep -cF 'key=\"Tentacle.Certificate\">AESGCM-V1$' /etc/octopus/tentacle.config", config, data)).Should().Be("1"); - (await RunInImage("tentacle show-thumbprint --instance Tentacle", config, data)).Should().Be(thumbprint); + var inspectEncryption = new ExecuteShellScriptCommandBuilder(LoggingUtils.CurrentTestHash(), ScriptIsolationLevel.NoIsolation) + .WithScriptBody(""" + echo "key permissions $(stat -c %a /var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key)" + echo "encrypted certificates $(grep -cF 'key="Tentacle.Certificate">AESGCM-V1$' /etc/octopus/tentacle.config)" + """) + .Build(); + + await using var recreatedTentacle = await new TentacleContainerBuilder(server) + .WithVolume(config, "/etc/octopus") + .WithVolume(data, "/var/lib/octopus/tentacle") + .WithStartingAlreadyConfiguredTentacle(registeredMachine) + .Build(); + var (result, output) = await recreatedTentacle.ExecuteScript(inspectEncryption); + + result.ExitCode.Should().Be(0, output); + output.Should().Contain("key permissions 600"); + output.Should().Contain("encrypted certificates 1"); } [Test] public async Task TheContainerRefusesToStartWhenOnlyTheConfigurationIsPersisted() { await using var config = await DockerVolume.Create(CancellationToken.None); - using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(10)); - - var (exitCode, output) = await DockerCli.RunUnchecked(new[] - { - "run", "--rm", "--label", DockerCli.ContainerLabel, - "--volume", config.MountAt("/etc/octopus"), - "--env", "ACCEPT_EULA=Y", - TentacleImage.Resolve() - }, cancellationTokenSource.Token); - - exitCode.Should().NotBe(0); - output.Should().Contain("/var/lib/octopus/tentacle is not"); - } + await using var server = await new FakeOctopusServerBuilder().Build(); - static async Task RunInImage(string command, DockerVolume config, DockerVolume data) - { - using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(10)); - var (exitCode, output) = await DockerCli.RunUnchecked(new[] - { - "run", "--rm", "--label", DockerCli.ContainerLabel, - "--volume", config.MountAt("/etc/octopus"), - "--volume", data.MountAt("/var/lib/octopus/tentacle"), - "--entrypoint", "bash", - TentacleImage.Resolve(), "-c", command - }, cancellationTokenSource.Token); + await using var tentacle = await new TentacleContainerBuilder(server) + .WithVolume(config, "/etc/octopus") + .WithTentacleThatRefusesToStart() + .Build(); - TestContext.Out.WriteLine($"$ {command} (exit code {exitCode})\n{output}"); - exitCode.Should().Be(0, output); - return output.Trim(); + (await tentacle.Docker.GetLogs()).Should().Contain("/var/lib/octopus/tentacle is not"); } } diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs index 3c96384e3..1122f1ed6 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs @@ -29,16 +29,6 @@ public static async Task Run(IEnumerable arguments, Cancellation return result.StandardOutput.Trim(); } - /// Runs a docker command that may fail, returning its exit code and combined output. - public static async Task<(int ExitCode, string Output)> RunUnchecked(IEnumerable arguments, CancellationToken cancellationToken) - { - var result = await Cli.Wrap("docker") - .WithArguments(arguments.ToArray()) - .WithValidation(CommandResultValidation.None) - .ExecuteBufferedAsync(Encoding.UTF8, cancellationToken); - return (result.ExitCode, result.StandardOutput + result.StandardError); - } - /// /// `docker logs` writes the container's stdout and stderr to its own stdout and stderr, so ask for both and /// return them together. Never throws: this is called while reporting other failures. diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs index aeed8d1a4..3fb888ca6 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs @@ -68,6 +68,15 @@ internal async Task Start(Task registration, CancellationToke tentacleClient = await BuildTentacleClient(cancellationToken); } + internal async Task WaitForRefusalToStart() + { + using var timeout = new CancellationTokenSource(RegistrationTimeout); + if (await WaitForContainerToStop(timeout.Token) is null) + { + throw new TimeoutException($"The Tentacle container was expected to refuse to start, but is still {await Docker.DescribeState()} after {RegistrationTimeout.TotalSeconds:0} seconds."); + } + } + async Task WaitForRegistration(Task registration) { var timeout = Task.Delay(RegistrationTimeout); diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs index d36a8f178..6d4a1dd93 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs @@ -21,6 +21,8 @@ public class TentacleContainerBuilder string? workerPoolName; Dictionary credentials = new() { ["ServerApiKey"] = ApiKey }; readonly List volumeMounts = new(); + RegisteredMachine? alreadyRegistered; + bool refusesToStart; public TentacleContainerBuilder(FakeOctopusServer server) { @@ -58,6 +60,23 @@ public TentacleContainerBuilder WithVolume(DockerVolume volume, string container return this; } + /// + /// Starts on volumes a previous container configured, so it skips registration. The TentacleClient trusts the + /// previous registration's thumbprint. + /// + public TentacleContainerBuilder WithStartingAlreadyConfiguredTentacle(RegisteredMachine registeredMachine) + { + alreadyRegistered = registeredMachine; + return this; + } + + /// Expects the entrypoint to exit before configuring, so waits for it to stop. + public TentacleContainerBuilder WithTentacleThatRefusesToStart() + { + refusesToStart = true; + return this; + } + public async Task Build() { using var cancellationTokenSource = new CancellationTokenSource(DockerCommandTimeout); @@ -67,13 +86,23 @@ public async Task Build() var image = TentacleImage.Resolve(); TestContext.Out.WriteLine($"Testing {image} as a {communicationStyle} Tentacle named {machineName}"); - var registration = server.WaitForRegistration(FakeOctopusServerBuilder.SpaceName, machineName); + var registration = alreadyRegistered is null + ? server.WaitForRegistration(FakeOctopusServerBuilder.SpaceName, machineName) + : Task.FromResult(alreadyRegistered); var docker = await DockerContainer.Run(image, machineName, RunOptions(machineName), cancellationToken); var tentacle = new TentacleContainer(docker, server, machineName, communicationStyle); try { - await tentacle.Start(registration, cancellationToken); + if (refusesToStart) + { + await tentacle.WaitForRefusalToStart(); + } + else + { + await tentacle.Start(registration, cancellationToken); + } + return tentacle; } catch From a2e8ffc15bc78ef0244c007a45b6f12ede31ee14 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:29:41 +1100 Subject: [PATCH 024/124] Mark arrange, act and assert in the config encryption Docker tests --- .../LinuxTentacleConfigEncryptionTests.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs index 4d0205a00..b80fd20a3 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs @@ -15,6 +15,7 @@ public class LinuxTentacleConfigEncryptionTests [Test] public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey() { + // Arrange await using var config = await DockerVolume.Create(CancellationToken.None); await using var data = await DockerVolume.Create(CancellationToken.None); await using var server = await new FakeOctopusServerBuilder().Build(); @@ -35,6 +36,7 @@ public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey """) .Build(); + // Act await using var recreatedTentacle = await new TentacleContainerBuilder(server) .WithVolume(config, "/etc/octopus") .WithVolume(data, "/var/lib/octopus/tentacle") @@ -42,6 +44,7 @@ public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey .Build(); var (result, output) = await recreatedTentacle.ExecuteScript(inspectEncryption); + // Assert result.ExitCode.Should().Be(0, output); output.Should().Contain("key permissions 600"); output.Should().Contain("encrypted certificates 1"); @@ -50,14 +53,17 @@ public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey [Test] public async Task TheContainerRefusesToStartWhenOnlyTheConfigurationIsPersisted() { + // Arrange await using var config = await DockerVolume.Create(CancellationToken.None); await using var server = await new FakeOctopusServerBuilder().Build(); + // Act await using var tentacle = await new TentacleContainerBuilder(server) .WithVolume(config, "/etc/octopus") .WithTentacleThatRefusesToStart() .Build(); + // Assert (await tentacle.Docker.GetLogs()).Should().Contain("/var/lib/octopus/tentacle is not"); } } From 36d03cca681f26c17a1820cabfbbe5ae77159743 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:30:56 +1100 Subject: [PATCH 025/124] Test config encryption separately from container re-creation --- .../LinuxTentacleConfigEncryptionTests.cs | 38 +++++++++++++++---- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs index b80fd20a3..09a99eb6f 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs @@ -12,6 +12,32 @@ namespace Octopus.Tentacle.Docker.Tests.Integration; /// public class LinuxTentacleConfigEncryptionTests { + [Test] + public async Task TheConfigurationIsEncryptedWithAKeyOnlyItsOwnerCanRead() + { + // Arrange + await using var server = await new FakeOctopusServerBuilder().Build(); + var inspectEncryption = new ExecuteShellScriptCommandBuilder(LoggingUtils.CurrentTestHash(), ScriptIsolationLevel.NoIsolation) + .WithScriptBody(""" + echo "key permissions $(stat -c %a /var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key)" + echo "encrypted certificates $(grep -cF 'key="Tentacle.Certificate">AESGCM-V1$' /etc/octopus/tentacle.config)" + """) + .Build(); + + // Act + await using var tentacle = await new TentacleContainerBuilder(server).Build(); + var (result, output) = await tentacle.ExecuteScript(inspectEncryption); + + // Assert + result.ExitCode.Should().Be(0, output); + output.Should().Contain("key permissions 600"); + output.Should().Contain("encrypted certificates 1"); + } + + /// + /// The re-created Tentacle only runs the script if it decrypted its certificate: the client trusts the first + /// container's thumbprint. + /// [Test] public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey() { @@ -29,11 +55,8 @@ public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey registeredMachine = tentacle.RegisteredMachine; } - var inspectEncryption = new ExecuteShellScriptCommandBuilder(LoggingUtils.CurrentTestHash(), ScriptIsolationLevel.NoIsolation) - .WithScriptBody(""" - echo "key permissions $(stat -c %a /var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key)" - echo "encrypted certificates $(grep -cF 'key="Tentacle.Certificate">AESGCM-V1$' /etc/octopus/tentacle.config)" - """) + var command = new ExecuteShellScriptCommandBuilder(LoggingUtils.CurrentTestHash(), ScriptIsolationLevel.NoIsolation) + .WithScriptBody("echo 'running after being re-created'\n") .Build(); // Act @@ -42,12 +65,11 @@ public async Task ARecreatedContainerDecryptsTheConfigurationWithThePersistedKey .WithVolume(data, "/var/lib/octopus/tentacle") .WithStartingAlreadyConfiguredTentacle(registeredMachine) .Build(); - var (result, output) = await recreatedTentacle.ExecuteScript(inspectEncryption); + var (result, output) = await recreatedTentacle.ExecuteScript(command); // Assert result.ExitCode.Should().Be(0, output); - output.Should().Contain("key permissions 600"); - output.Should().Contain("encrypted certificates 1"); + output.Should().Contain("running after being re-created"); } [Test] From fe27a9a7c9402e1aee826939888b4749d3bf0146 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:38:28 +1100 Subject: [PATCH 026/124] Rename WithRunTentacleEnvironmentVariable to WithEnvironmentVariable --- .../MachineConfigurationHomeDirectoryTests.cs | 2 +- .../Support/TentacleBuilder.cs | 8 ++++---- .../Support/TentacleBuilderExtensionMethods.cs | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/MachineConfigurationHomeDirectoryTests.cs b/source/Octopus.Tentacle.Tests.Integration/MachineConfigurationHomeDirectoryTests.cs index 5c042b380..ad973c593 100644 --- a/source/Octopus.Tentacle.Tests.Integration/MachineConfigurationHomeDirectoryTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/MachineConfigurationHomeDirectoryTests.cs @@ -42,7 +42,7 @@ public async Task ShouldUseTheCustomMachineConfigurationHomeDirectoryWhenACustom .UseDefaultMachineConfigurationHomeDirectory() .WithTentacle(x => { - x.WithRunTentacleEnvironmentVariable(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, tempDirectory.DirectoryPath); + x.WithEnvironmentVariable(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, tempDirectory.DirectoryPath); }) .Build(CancellationToken); diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs index 061ad766b..6e1e929ed 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs @@ -25,7 +25,7 @@ namespace Octopus.Tentacle.Tests.Integration.Support { public interface ITentacleBuilder { - ITentacleBuilder WithRunTentacleEnvironmentVariable(string environmentVariable, TValue value); + ITentacleBuilder WithEnvironmentVariable(string environmentVariable, TValue value); ITentacleBuilder WithHomeDirectory(TemporaryDirectory homeDirectory); } @@ -110,7 +110,7 @@ public T WithTentacleExe(string tentacleExe) return (T)this; } - public ITentacleBuilder WithRunTentacleEnvironmentVariable(string environmentVariable, TValue value) + public ITentacleBuilder WithEnvironmentVariable(string environmentVariable, TValue value) { runTentacleEnvironmentVariables[environmentVariable] = value?.ToString(); @@ -320,10 +320,10 @@ protected void ConfigureTentacleMachineConfigurationHomeDirectory() { var directory = Path.Combine(HomeDirectory.DirectoryPath, "Octopus", "Tentacle", "Instances"); - WithRunTentacleEnvironmentVariable(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, directory); + WithEnvironmentVariable(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, directory); } - WithRunTentacleEnvironmentVariable(EnvironmentVariables.TentacleInstancesDataDirectory, Path.Combine(HomeDirectory.DirectoryPath, "data")); + WithEnvironmentVariable(EnvironmentVariables.TentacleInstancesDataDirectory, Path.Combine(HomeDirectory.DirectoryPath, "data")); } async Task SetEnvironmentVariablesForService(string instanceName, TemporaryDirectory tempDirectory, ILogger logger, CancellationToken cancellationToken) diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilderExtensionMethods.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilderExtensionMethods.cs index 0fad2ad35..011cf4553 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilderExtensionMethods.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilderExtensionMethods.cs @@ -8,8 +8,8 @@ public static class TentacleBuilderExtensionMethods public static ITentacleBuilder WithWorkspaceCleaningSettings(this ITentacleBuilder builder, TimeSpan cleanerDelay, TimeSpan deleteWorkspacesOlderThan) { return builder - .WithRunTentacleEnvironmentVariable(WorkspaceCleanerConfiguration.CleanerDelayEnvironmentVariableName, cleanerDelay) - .WithRunTentacleEnvironmentVariable(WorkspaceCleanerConfiguration.DeleteWorkspacesOlderThanTimeSpanEnvironmentVariableName, deleteWorkspacesOlderThan); + .WithEnvironmentVariable(WorkspaceCleanerConfiguration.CleanerDelayEnvironmentVariableName, cleanerDelay) + .WithEnvironmentVariable(WorkspaceCleanerConfiguration.DeleteWorkspacesOlderThanTimeSpanEnvironmentVariableName, deleteWorkspacesOlderThan); } } } \ No newline at end of file From 2481066ca74c0a509484f79101895b1e355413a4 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:42:30 +1100 Subject: [PATCH 027/124] Make key tests self-contained instead of inheriting fixture setup --- .../Commands/CreateInstanceCommandFixture.cs | 37 --------------- .../Commands/CreateInstanceCommandTests.cs | 36 +++++++++++++++ ... => LegacyCiphertextCompatibilityTests.cs} | 46 +++++-------------- 3 files changed, 48 insertions(+), 71 deletions(-) delete mode 100644 source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs create mode 100644 source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs rename source/Octopus.Tentacle.Tests/Configuration/Crypto/{LegacyCiphertextCompatibilityFixture.cs => LegacyCiphertextCompatibilityTests.cs} (80%) diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs deleted file mode 100644 index c1356222d..000000000 --- a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.IO; -using FluentAssertions; -using NSubstitute; -using NUnit.Framework; -using Octopus.Tentacle.Commands; -using Octopus.Tentacle.Configuration; -using Octopus.Tentacle.Configuration.Instances; -using Octopus.Tentacle.Startup; -using Octopus.Tentacle.Tests.Support.TestAttributes; - -namespace Octopus.Tentacle.Tests.Commands -{ - [TestFixture] - [LinuxTest] - public class CreateInstanceCommandFixture : CommandFixture - { - readonly ITentacleConfigurationUpgrade configurationUpgrade = Substitute.For(); - - [SetUp] - public override void SetUp() - { - base.SetUp(); - Command = new CreateInstanceCommand(Substitute.For(), Substitute.For(), new Lazy(() => configurationUpgrade)); - } - - [Test] - public void ANamedInstanceFailsWhenItsKeyCannotBeCreated() - { - configurationUpgrade.When(u => u.PrepareKey()).Do(_ => throw new IOException("Permission denied")); - - Action start = () => Start("--instance=Tentacle", "--config=/etc/octopus/tentacle.config"); - - start.Should().Throw(); - } - } -} diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs new file mode 100644 index 000000000..c075a4b1c --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs @@ -0,0 +1,36 @@ +using System; +using System.IO; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Commands; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Internals.Options; +using Octopus.Tentacle.Startup; +using Octopus.Tentacle.Tests.Support.TestAttributes; + +namespace Octopus.Tentacle.Tests.Commands +{ + [LinuxOrMacTest] + public class CreateInstanceCommandTests + { + [Test] + public void ANamedInstanceFailsWhenItsKeyCannotBeCreated() + { + var configurationUpgrade = Substitute.For(); + configurationUpgrade.When(u => u.PrepareKey()).Do(_ => throw new IOException("Permission denied")); + var command = new CreateInstanceCommand( + Substitute.For(), + Substitute.For(), + new Lazy(() => configurationUpgrade)); + + Action start = () => command.Start( + new[] { "--instance=Tentacle", "--config=/etc/octopus/tentacle.config" }, + Substitute.For(), + new OptionSet()); + + start.Should().Throw(); + } + } +} diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs similarity index 80% rename from source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs rename to source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs index 792fa3aa8..179466f1d 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs @@ -8,6 +8,7 @@ using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Kubernetes; +using Octopus.Tentacle.Tests.Support.TestAttributes; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Configuration.Crypto @@ -15,8 +16,8 @@ namespace Octopus.Tentacle.Tests.Configuration.Crypto // The ciphertext below was captured from the encryptor as it was before the versioned format (commit 7b1504e), which // used a fixed IV and so is deterministic. Do not regenerate it with the current code: that would only prove the // current code agrees with itself. - [TestFixture] - public class LegacyCiphertextCompatibilityFixture + [LinuxOrMacTest] + public class LegacyCiphertextCompatibilityTests { const string MachineId = "816490f117f14c7a8fa2697781ed795b"; const string GeneratedKeyFileContents = "MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=.ZmVkY2JhOTg3NjU0MzIxMA=="; @@ -49,26 +50,17 @@ public static IEnumerable WrittenWithTheGeneratedKey() .SetName("{m}(generated, certificate-sized)"); } - - FakeKeyFiles files; - - [SetUp] - public void SetUp() + static IMachineKeyEncryptor CreateEncryptorAsComposedInProduction(bool machineIdPresent, bool generatedKeyPresent) { Environment.SetEnvironmentVariable(KubernetesConfig.NamespaceVariableName, null); - files = new FakeKeyFiles(); - files.Contents[LinuxGeneratedMachineKey.LegacyKeyFilePath] = GeneratedKeyFileContents; - } - [TearDown] - public void TearDown() - { - Environment.SetEnvironmentVariable(KubernetesConfig.NamespaceVariableName, null); - } + var files = new Dictionary(); + if (generatedKeyPresent) + files[LinuxGeneratedMachineKey.LegacyKeyFilePath] = GeneratedKeyFileContents; - IMachineKeyEncryptor CreateEncryptorAsComposedInProduction(bool machineIdPresent) - { - var fileSystem = files.CreateFileSystem(); + var fileSystem = Substitute.For(); + fileSystem.FileExists(Arg.Any()).Returns(ci => files.ContainsKey(ci.ArgAt(0))); + fileSystem.ReadAllText(Arg.Any()).Returns(ci => files[ci.ArgAt(0)]); fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(machineIdPresent); fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { MachineId }); @@ -79,8 +71,7 @@ IMachineKeyEncryptor CreateEncryptorAsComposedInProduction(bool machineIdPresent public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string plaintext, string legacyCiphertext) { // Arrange - files.Contents.Remove(LinuxGeneratedMachineKey.LegacyKeyFilePath); - var encryptor = CreateEncryptorAsComposedInProduction(machineIdPresent: true); + var encryptor = CreateEncryptorAsComposedInProduction(machineIdPresent: true, generatedKeyPresent: false); // Act var decrypted = encryptor.Decrypt(legacyCiphertext); @@ -93,7 +84,7 @@ public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string pl public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plaintext, string legacyCiphertext) { // Arrange - var encryptor = CreateEncryptorAsComposedInProduction(machineIdPresent: false); + var encryptor = CreateEncryptorAsComposedInProduction(machineIdPresent: false, generatedKeyPresent: true); // Act var decrypted = encryptor.Decrypt(legacyCiphertext); @@ -101,19 +92,6 @@ public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plai // Assert decrypted.Should().Be(plaintext); } - - class FakeKeyFiles - { - public Dictionary Contents { get; } = new(); - - public IOctopusFileSystem CreateFileSystem() - { - var fileSystem = Substitute.For(); - fileSystem.FileExists(Arg.Any()).Returns(ci => Contents.ContainsKey(ci.ArgAt(0))); - fileSystem.ReadAllText(Arg.Any()).Returns(ci => Contents[ci.ArgAt(0)]); - return fileSystem; - } - } } } #endif From d98236303f3bd08db2b6938745985db93752db72 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:47:12 +1100 Subject: [PATCH 028/124] Tell the user to run as root when the configuration encryption key cannot be created --- .../Commands/CreateInstanceCommandTests.cs | 36 ------------------- .../Crypto/ConfigurationEncryptionKeyTests.cs | 31 ++++++++++++++++ .../Crypto/ConfigurationEncryptionKey.cs | 17 +++++++-- 3 files changed, 45 insertions(+), 39 deletions(-) delete mode 100644 source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs create mode 100644 source/Octopus.Tentacle.Tests/Configuration/Crypto/ConfigurationEncryptionKeyTests.cs diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs deleted file mode 100644 index c075a4b1c..000000000 --- a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.IO; -using FluentAssertions; -using NSubstitute; -using NUnit.Framework; -using Octopus.Tentacle.Commands; -using Octopus.Tentacle.Configuration; -using Octopus.Tentacle.Configuration.Instances; -using Octopus.Tentacle.Internals.Options; -using Octopus.Tentacle.Startup; -using Octopus.Tentacle.Tests.Support.TestAttributes; - -namespace Octopus.Tentacle.Tests.Commands -{ - [LinuxOrMacTest] - public class CreateInstanceCommandTests - { - [Test] - public void ANamedInstanceFailsWhenItsKeyCannotBeCreated() - { - var configurationUpgrade = Substitute.For(); - configurationUpgrade.When(u => u.PrepareKey()).Do(_ => throw new IOException("Permission denied")); - var command = new CreateInstanceCommand( - Substitute.For(), - Substitute.For(), - new Lazy(() => configurationUpgrade)); - - Action start = () => command.Start( - new[] { "--instance=Tentacle", "--config=/etc/octopus/tentacle.config" }, - Substitute.For(), - new OptionSet()); - - start.Should().Throw(); - } - } -} diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/ConfigurationEncryptionKeyTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/ConfigurationEncryptionKeyTests.cs new file mode 100644 index 000000000..f0278a147 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/ConfigurationEncryptionKeyTests.cs @@ -0,0 +1,31 @@ +using System; +using System.Runtime.Versioning; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Tests.Support.TestAttributes; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Tests.Configuration.Crypto +{ + [LinuxOrMacTest] + [UnsupportedOSPlatform("windows")] + public class ConfigurationEncryptionKeyTests + { + [Test] + public void TellsTheUserToRunAsRootWhenTheKeyCannotBeCreated() + { + const string keyFilePath = "/var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key"; + var fileSystem = Substitute.For(); + fileSystem.When(f => f.EnsureDirectoryExists(Arg.Any())).Do(_ => throw new UnauthorizedAccessException("Permission denied")); + var key = new ConfigurationEncryptionKey(Substitute.For(), fileSystem, keyFilePath); + + Action createKey = () => key.CreateIfMissing(); + + createKey.Should().Throw() + .WithMessage($"*cannot create the configuration encryption key file `{keyFilePath}`*Run this command again as root*"); + } + } +} diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index 797d6cbd1..a5bae5a90 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -95,10 +95,21 @@ public void CreateIfMissing() var raw = Convert.ToBase64String(RandomKey()); - CreateKeyDirectory(KeyDirectory!); + bool created; + try + { + CreateKeyDirectory(KeyDirectory!); + + // Several instances starting at once after an upgrade must all end up with the same key. + created = fileSystem.AtomicCreateFileWithOnlyUserReadWritePermissions(path, Encoding.ASCII.GetBytes(raw)); + } + catch (UnauthorizedAccessException e) + { + throw new InvalidOperationException($"The user Tentacle is running as ({Environment.UserName}) cannot create the configuration encryption key file `{path}`. " + + "Run this command again as root, for example with `sudo`.", e); + } - // Several instances starting at once after an upgrade must all end up with the same key. - if (!fileSystem.AtomicCreateFileWithOnlyUserReadWritePermissions(path, Encoding.ASCII.GetBytes(raw))) + if (!created) { log.Verbose($"Another process created the configuration encryption key `{path}` first; using its key."); return; From c12e27d8b1b0b425dd22ece00c46d4fd1076af5f Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:50:08 +1100 Subject: [PATCH 029/124] Revert "Tell the user to run as root when the configuration encryption key cannot be created" This reverts commit d98236303f3bd08db2b6938745985db93752db72. --- .../Commands/CreateInstanceCommandTests.cs | 36 +++++++++++++++++++ .../Crypto/ConfigurationEncryptionKeyTests.cs | 31 ---------------- .../Crypto/ConfigurationEncryptionKey.cs | 17 ++------- 3 files changed, 39 insertions(+), 45 deletions(-) create mode 100644 source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs delete mode 100644 source/Octopus.Tentacle.Tests/Configuration/Crypto/ConfigurationEncryptionKeyTests.cs diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs new file mode 100644 index 000000000..c075a4b1c --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs @@ -0,0 +1,36 @@ +using System; +using System.IO; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Commands; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Internals.Options; +using Octopus.Tentacle.Startup; +using Octopus.Tentacle.Tests.Support.TestAttributes; + +namespace Octopus.Tentacle.Tests.Commands +{ + [LinuxOrMacTest] + public class CreateInstanceCommandTests + { + [Test] + public void ANamedInstanceFailsWhenItsKeyCannotBeCreated() + { + var configurationUpgrade = Substitute.For(); + configurationUpgrade.When(u => u.PrepareKey()).Do(_ => throw new IOException("Permission denied")); + var command = new CreateInstanceCommand( + Substitute.For(), + Substitute.For(), + new Lazy(() => configurationUpgrade)); + + Action start = () => command.Start( + new[] { "--instance=Tentacle", "--config=/etc/octopus/tentacle.config" }, + Substitute.For(), + new OptionSet()); + + start.Should().Throw(); + } + } +} diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/ConfigurationEncryptionKeyTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/ConfigurationEncryptionKeyTests.cs deleted file mode 100644 index f0278a147..000000000 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/ConfigurationEncryptionKeyTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Runtime.Versioning; -using FluentAssertions; -using NSubstitute; -using NUnit.Framework; -using Octopus.Tentacle.Configuration.Crypto; -using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Tests.Support.TestAttributes; -using Octopus.Tentacle.Util; - -namespace Octopus.Tentacle.Tests.Configuration.Crypto -{ - [LinuxOrMacTest] - [UnsupportedOSPlatform("windows")] - public class ConfigurationEncryptionKeyTests - { - [Test] - public void TellsTheUserToRunAsRootWhenTheKeyCannotBeCreated() - { - const string keyFilePath = "/var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key"; - var fileSystem = Substitute.For(); - fileSystem.When(f => f.EnsureDirectoryExists(Arg.Any())).Do(_ => throw new UnauthorizedAccessException("Permission denied")); - var key = new ConfigurationEncryptionKey(Substitute.For(), fileSystem, keyFilePath); - - Action createKey = () => key.CreateIfMissing(); - - createKey.Should().Throw() - .WithMessage($"*cannot create the configuration encryption key file `{keyFilePath}`*Run this command again as root*"); - } - } -} diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index a5bae5a90..797d6cbd1 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -95,21 +95,10 @@ public void CreateIfMissing() var raw = Convert.ToBase64String(RandomKey()); - bool created; - try - { - CreateKeyDirectory(KeyDirectory!); - - // Several instances starting at once after an upgrade must all end up with the same key. - created = fileSystem.AtomicCreateFileWithOnlyUserReadWritePermissions(path, Encoding.ASCII.GetBytes(raw)); - } - catch (UnauthorizedAccessException e) - { - throw new InvalidOperationException($"The user Tentacle is running as ({Environment.UserName}) cannot create the configuration encryption key file `{path}`. " - + "Run this command again as root, for example with `sudo`.", e); - } + CreateKeyDirectory(KeyDirectory!); - if (!created) + // Several instances starting at once after an upgrade must all end up with the same key. + if (!fileSystem.AtomicCreateFileWithOnlyUserReadWritePermissions(path, Encoding.ASCII.GetBytes(raw))) { log.Verbose($"Another process created the configuration encryption key `{path}` first; using its key."); return; From e5509b7814d3035a49c059e830be18209bccdd1b Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:50:10 +1100 Subject: [PATCH 030/124] Pass legacy generated key path in rather than reading env var; inline legacy ciphertext test cases --- .../LegacyCiphertextCompatibilityTests.cs | 84 +++++++------------ .../Crypto/LinuxGeneratedMachineKey.cs | 5 +- .../Crypto/MachineKeyEncryptor.cs | 6 +- 3 files changed, 37 insertions(+), 58 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs index 179466f1d..26f911a57 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs @@ -1,77 +1,36 @@ #if !NETFRAMEWORK using System; using System.Collections.Generic; -using System.Linq; using FluentAssertions; using NSubstitute; using NUnit.Framework; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Kubernetes; using Octopus.Tentacle.Tests.Support.TestAttributes; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Configuration.Crypto { - // The ciphertext below was captured from the encryptor as it was before the versioned format (commit 7b1504e), which - // used a fixed IV and so is deterministic. Do not regenerate it with the current code: that would only prove the - // current code agrees with itself. + // Ciphertext captured from the pre-versioned encryptor (commit 7b1504e), which used a fixed IV. + // Do not regenerate it with the current code: that would only prove the current code agrees with itself. [LinuxOrMacTest] public class LegacyCiphertextCompatibilityTests { const string MachineId = "816490f117f14c7a8fa2697781ed795b"; + const string GeneratedKeyPath = "/etc/octopus/machinekey"; const string GeneratedKeyFileContents = "MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=.ZmVkY2JhOTg3NjU0MzIxMA=="; - const string ShortText = "FooBar"; - const string SerialisedBool = "true"; - const string SerialisedInt = "123"; - const string UnicodeText = "pässwörd 🐙 with spaces & symbols!"; - static readonly string CertificateSizedText = Convert.ToBase64String(Enumerable.Range(0, 300).Select(i => (byte)(i * 7)).ToArray()); + const string CertificateSizedText = "AAcOFRwjKjE4P0ZNVFtiaXB3foWMk5qhqK+2vcTL0tng5+71/AMKERgfJi00O0JJUFdeZWxzeoGIj5adpKuyucDHztXc4+rx+P8GDRQbIikwNz5FTFNaYWhvdn2Ei5KZoKeutbzDytHY3+bt9PsCCRAXHiUsMzpBSE9WXWRrcnmAh46VnKOqsbi/xs3U2+Lp8Pf+BQwTGiEoLzY9REtSWWBnbnV8g4qRmJ+mrbS7wsnQ197l7PP6AQgPFh0kKzI5QEdOVVxjanF4f4aNlJuiqbC3vsXM09rh6O/2/QQLEhkgJy41PENKUVhfZm10e4KJkJeepayzusHIz9bd5Ovy+QAHDhUcIyoxOD9GTVRbYmlwd36FjJOaoaivtr3Ey9LZ4Ofu9fwDChEYHyYt"; - public static IEnumerable WrittenWithTheMachineIdKey() - { - yield return new TestCaseData(ShortText, "yspqcK7xCvd5c+1OSB7kxw==").SetName("{m}(machine-id, short text)"); - yield return new TestCaseData(SerialisedBool, "lfWdFxOQukFHfUs767dBOA==").SetName("{m}(machine-id, serialised bool)"); - yield return new TestCaseData(SerialisedInt, "c5E+1E8Q73XGrrSEWenz/A==").SetName("{m}(machine-id, serialised int)"); - yield return new TestCaseData(UnicodeText, "nMmwC8Uzkg/bEwaDChRL86dTMzY4gCyveDi0qCjOWNENjQzd3wYS8lJwMeGXNdEy").SetName("{m}(machine-id, unicode)"); - yield return new TestCaseData(CertificateSizedText, - "2qbSDqJXa0/Bz1SzohM21m3dg3mIPBjj4mgbfve/WW1cZFNAgccjx+Hot6Qp8/TC8Su4rLS8yp6i+WY4J8x7ga6DbFVD4pQkjy8ag37nxwBos4llfCRhRqV0LZWol2U66+znAfTscepLI1nVWgtJtloYLGky/6QDjvMQQG9S/MmQsBzANfI3lQG8ftYK/ilU6xX7eJwvWViEG3HI/3loc7k9jbJT13JF4f8NpI3yEH4Q4VCWY9j3z+ZK/2kImeqRDfv9cl4roUdtBQ4I333taVovDwILKqq2a6QPRZiAVJ34in2CrrJv2dTWgaQHsU74upUlKiKrZs6LgpZVP7y+5W/o52te+dvwCBVBqFmxFUmpk/1gAMUiqZ0fEXrz8GlyS4dcIXlFUwUXcdUb1E2ldqDMRr2zDHP0ATwdBcKm9yM4sJKrGhrSksl7U7chM4CpRVTUf1tWvU3SjcQ00haPM+RZP2pWDnkDZhkrDRfpQke/qFL8wG9RySpzWDF+zsN0yUxZJgqUvy9cHb/yHphxTqyEmmoGcAuzOaA9a2yYGPs=") - .SetName("{m}(machine-id, certificate-sized)"); - } - - public static IEnumerable WrittenWithTheGeneratedKey() - { - yield return new TestCaseData(ShortText, "sU7FAsi9LrgjCISbdFN4Kg==").SetName("{m}(generated, short text)"); - yield return new TestCaseData(SerialisedBool, "ks2Nbbl8OonD1r2CFim+VA==").SetName("{m}(generated, serialised bool)"); - yield return new TestCaseData(SerialisedInt, "QL+mcAjSyVWEsVPlQeNvqA==").SetName("{m}(generated, serialised int)"); - yield return new TestCaseData(UnicodeText, "cVzJO4WpcDeZTWcG91jyln6rFJvjf08RkpiAb+FUMcOnzT8uB5emsPmEKS8vyg+p").SetName("{m}(generated, unicode)"); - yield return new TestCaseData(CertificateSizedText, - "NhUpBIgpSxmvYSXfn+cn5lKK5xB1LDf0NdKogqm1MAn4XQ8p84KJwVzEevn/T7Glk9Lirqa/RtUM9HuEEadDZ6XKhbnBdUJGLx1CFfHHw/3L3IProqBX/mD+W0SVIvnI54iq5PFdwtSSOH3a6PC+DT92rmXjy4/YoNzuGKkNcMoP/GG3g6URPHGdMq3NMs7t3wD7k8MbvU96F5qlTdqiwgILViruLJGZhECb99GmTdJ/PjCeFE87+up+vZllk1WVboGAIn6Vf+1Pgd7tDHgczDHZvgKIeP1k5gwH9dXzSd/OweG7eW7Yux0HIcI1oPMDcjx57ldDzYwhgIX5jPkMGFP3J4guwCIaSQTEyMLP85ZervJ0uWlAq/rlIK71dQ5c6wvFIVKkKeSo+qWReMRi9G4rMaelnagNTwUqBBfy+nff+tbvPrLV+CmKDCEgA+g1d7kF7+y/kBJ4NaZOpo6jBUVds/sV7ieVZhcUmHN2eML4/Zur5KyHvHsDnOWU3jgBxQ6oJJQB4yePmWivAXWlE4ISpIvM5i76XYqLbEJ+lbQ=") - .SetName("{m}(generated, certificate-sized)"); - } - - static IMachineKeyEncryptor CreateEncryptorAsComposedInProduction(bool machineIdPresent, bool generatedKeyPresent) - { - Environment.SetEnvironmentVariable(KubernetesConfig.NamespaceVariableName, null); - - var files = new Dictionary(); - if (generatedKeyPresent) - files[LinuxGeneratedMachineKey.LegacyKeyFilePath] = GeneratedKeyFileContents; - - var fileSystem = Substitute.For(); - fileSystem.FileExists(Arg.Any()).Returns(ci => files.ContainsKey(ci.ArgAt(0))); - fileSystem.ReadAllText(Arg.Any()).Returns(ci => files[ci.ArgAt(0)]); - fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(machineIdPresent); - fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { MachineId }); - - return MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle")); - } - - [TestCaseSource(nameof(WrittenWithTheMachineIdKey))] + [TestCase("FooBar", "yspqcK7xCvd5c+1OSB7kxw==")] + [TestCase("true", "lfWdFxOQukFHfUs767dBOA==")] + [TestCase("123", "c5E+1E8Q73XGrrSEWenz/A==")] + [TestCase("pässwörd 🐙 with spaces & symbols!", "nMmwC8Uzkg/bEwaDChRL86dTMzY4gCyveDi0qCjOWNENjQzd3wYS8lJwMeGXNdEy")] + [TestCase(CertificateSizedText, "2qbSDqJXa0/Bz1SzohM21m3dg3mIPBjj4mgbfve/WW1cZFNAgccjx+Hot6Qp8/TC8Su4rLS8yp6i+WY4J8x7ga6DbFVD4pQkjy8ag37nxwBos4llfCRhRqV0LZWol2U66+znAfTscepLI1nVWgtJtloYLGky/6QDjvMQQG9S/MmQsBzANfI3lQG8ftYK/ilU6xX7eJwvWViEG3HI/3loc7k9jbJT13JF4f8NpI3yEH4Q4VCWY9j3z+ZK/2kImeqRDfv9cl4roUdtBQ4I333taVovDwILKqq2a6QPRZiAVJ34in2CrrJv2dTWgaQHsU74upUlKiKrZs6LgpZVP7y+5W/o52te+dvwCBVBqFmxFUmpk/1gAMUiqZ0fEXrz8GlyS4dcIXlFUwUXcdUb1E2ldqDMRr2zDHP0ATwdBcKm9yM4sJKrGhrSksl7U7chM4CpRVTUf1tWvU3SjcQ00haPM+RZP2pWDnkDZhkrDRfpQke/qFL8wG9RySpzWDF+zsN0yUxZJgqUvy9cHb/yHphxTqyEmmoGcAuzOaA9a2yYGPs=")] public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string plaintext, string legacyCiphertext) { // Arrange - var encryptor = CreateEncryptorAsComposedInProduction(machineIdPresent: true, generatedKeyPresent: false); + var encryptor = CreateEncryptor(machineIdPresent: true, generatedKeyPresent: false); // Act var decrypted = encryptor.Decrypt(legacyCiphertext); @@ -80,11 +39,15 @@ public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string pl decrypted.Should().Be(plaintext); } - [TestCaseSource(nameof(WrittenWithTheGeneratedKey))] + [TestCase("FooBar", "sU7FAsi9LrgjCISbdFN4Kg==")] + [TestCase("true", "ks2Nbbl8OonD1r2CFim+VA==")] + [TestCase("123", "QL+mcAjSyVWEsVPlQeNvqA==")] + [TestCase("pässwörd 🐙 with spaces & symbols!", "cVzJO4WpcDeZTWcG91jyln6rFJvjf08RkpiAb+FUMcOnzT8uB5emsPmEKS8vyg+p")] + [TestCase(CertificateSizedText, "NhUpBIgpSxmvYSXfn+cn5lKK5xB1LDf0NdKogqm1MAn4XQ8p84KJwVzEevn/T7Glk9Lirqa/RtUM9HuEEadDZ6XKhbnBdUJGLx1CFfHHw/3L3IProqBX/mD+W0SVIvnI54iq5PFdwtSSOH3a6PC+DT92rmXjy4/YoNzuGKkNcMoP/GG3g6URPHGdMq3NMs7t3wD7k8MbvU96F5qlTdqiwgILViruLJGZhECb99GmTdJ/PjCeFE87+up+vZllk1WVboGAIn6Vf+1Pgd7tDHgczDHZvgKIeP1k5gwH9dXzSd/OweG7eW7Yux0HIcI1oPMDcjx57ldDzYwhgIX5jPkMGFP3J4guwCIaSQTEyMLP85ZervJ0uWlAq/rlIK71dQ5c6wvFIVKkKeSo+qWReMRi9G4rMaelnagNTwUqBBfy+nff+tbvPrLV+CmKDCEgA+g1d7kF7+y/kBJ4NaZOpo6jBUVds/sV7ieVZhcUmHN2eML4/Zur5KyHvHsDnOWU3jgBxQ6oJJQB4yePmWivAXWlE4ISpIvM5i76XYqLbEJ+lbQ=")] public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plaintext, string legacyCiphertext) { // Arrange - var encryptor = CreateEncryptorAsComposedInProduction(machineIdPresent: false, generatedKeyPresent: true); + var encryptor = CreateEncryptor(machineIdPresent: false, generatedKeyPresent: true); // Act var decrypted = encryptor.Decrypt(legacyCiphertext); @@ -92,6 +55,21 @@ public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plai // Assert decrypted.Should().Be(plaintext); } + + static IMachineKeyEncryptor CreateEncryptor(bool machineIdPresent, bool generatedKeyPresent) + { + var files = new Dictionary(); + if (generatedKeyPresent) + files[GeneratedKeyPath] = GeneratedKeyFileContents; + + var fileSystem = Substitute.For(); + fileSystem.FileExists(Arg.Any()).Returns(ci => files.ContainsKey(ci.ArgAt(0))); + fileSystem.ReadAllText(Arg.Any()).Returns(ci => files[ci.ArgAt(0)]); + fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(machineIdPresent); + fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { MachineId }); + + return MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle"), GeneratedKeyPath); + } } } #endif diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs index aac2ffc1f..5ce3821d4 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs @@ -13,10 +13,12 @@ public class LinuxGeneratedMachineKey : ICryptoKeyNixSource public const string LegacyKeyFilePath = "/etc/octopus/" + LegacyKeyFileName; readonly IOctopusFileSystem fileSystem; + readonly string path; - public LinuxGeneratedMachineKey(IOctopusFileSystem fileSystem) + public LinuxGeneratedMachineKey(IOctopusFileSystem fileSystem, string path) { this.fileSystem = fileSystem; + this.path = path; } public static string LegacyKeyFilePathForThisHost @@ -27,7 +29,6 @@ public static string LegacyKeyFilePathForThisHost public (byte[] Key, byte[] IV) Load() { - var path = LegacyKeyFilePathForThisHost; if (!fileSystem.FileExists(path)) { throw new InvalidOperationException($"There is no machine key file at `{path}`."); diff --git a/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs index 2d105f740..c20fe9cbc 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs @@ -12,15 +12,15 @@ public static class MachineKeyEncryptor public static IMachineKeyEncryptor ForKeyFile(IOctopusFileSystem fileSystem, string? keyFilePath) => PlatformDetection.IsRunningOnWindows ? new WindowsMachineKeyEncryptor() - : CreateLinuxEncryptor(Log, fileSystem, keyFilePath); + : CreateLinuxEncryptor(Log, fileSystem, keyFilePath, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost); - internal static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, string? keyFilePath) + internal static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, string? keyFilePath, string legacyGeneratedKeyFilePath) { // The keys earlier versions used, in the order they tried them. Only read, never created or changed. var legacyKeySources = new List { new LinuxMachineIdKey(fileSystem), - new LinuxGeneratedMachineKey(fileSystem) + new LinuxGeneratedMachineKey(fileSystem, legacyGeneratedKeyFilePath) }; return new LinuxMachineKeyEncryptor(log, new ConfigurationEncryptionKey(log, fileSystem, keyFilePath), legacyKeySources); From c7a1dbe5fda98622dd19be47b85187b69cf6e02f Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:50:18 +1100 Subject: [PATCH 031/124] Remove create-instance test covered by ApplicationInstanceManagerFixture --- .../Commands/CreateInstanceCommandTests.cs | 36 ------------------- 1 file changed, 36 deletions(-) delete mode 100644 source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs deleted file mode 100644 index c075a4b1c..000000000 --- a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.IO; -using FluentAssertions; -using NSubstitute; -using NUnit.Framework; -using Octopus.Tentacle.Commands; -using Octopus.Tentacle.Configuration; -using Octopus.Tentacle.Configuration.Instances; -using Octopus.Tentacle.Internals.Options; -using Octopus.Tentacle.Startup; -using Octopus.Tentacle.Tests.Support.TestAttributes; - -namespace Octopus.Tentacle.Tests.Commands -{ - [LinuxOrMacTest] - public class CreateInstanceCommandTests - { - [Test] - public void ANamedInstanceFailsWhenItsKeyCannotBeCreated() - { - var configurationUpgrade = Substitute.For(); - configurationUpgrade.When(u => u.PrepareKey()).Do(_ => throw new IOException("Permission denied")); - var command = new CreateInstanceCommand( - Substitute.For(), - Substitute.For(), - new Lazy(() => configurationUpgrade)); - - Action start = () => command.Start( - new[] { "--instance=Tentacle", "--config=/etc/octopus/tentacle.config" }, - Substitute.For(), - new OptionSet()); - - start.Should().Throw(); - } - } -} From ca12d6b5529188d1a799979b54b7452dbea616f8 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:51:30 +1100 Subject: [PATCH 032/124] Pass key file contents to CreateEncryptor instead of presence flags --- .../LegacyCiphertextCompatibilityTests.cs | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs index 26f911a57..3dc60d37c 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs @@ -1,6 +1,5 @@ #if !NETFRAMEWORK using System; -using System.Collections.Generic; using FluentAssertions; using NSubstitute; using NUnit.Framework; @@ -30,7 +29,7 @@ public class LegacyCiphertextCompatibilityTests public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string plaintext, string legacyCiphertext) { // Arrange - var encryptor = CreateEncryptor(machineIdPresent: true, generatedKeyPresent: false); + var encryptor = CreateEncryptor(machineId: MachineId, generatedKeyFileContents: null); // Act var decrypted = encryptor.Decrypt(legacyCiphertext); @@ -47,7 +46,7 @@ public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string pl public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plaintext, string legacyCiphertext) { // Arrange - var encryptor = CreateEncryptor(machineIdPresent: false, generatedKeyPresent: true); + var encryptor = CreateEncryptor(machineId: null, generatedKeyFileContents: GeneratedKeyFileContents); // Act var decrypted = encryptor.Decrypt(legacyCiphertext); @@ -56,17 +55,20 @@ public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plai decrypted.Should().Be(plaintext); } - static IMachineKeyEncryptor CreateEncryptor(bool machineIdPresent, bool generatedKeyPresent) + static IMachineKeyEncryptor CreateEncryptor(string? machineId, string? generatedKeyFileContents) { - var files = new Dictionary(); - if (generatedKeyPresent) - files[GeneratedKeyPath] = GeneratedKeyFileContents; - var fileSystem = Substitute.For(); - fileSystem.FileExists(Arg.Any()).Returns(ci => files.ContainsKey(ci.ArgAt(0))); - fileSystem.ReadAllText(Arg.Any()).Returns(ci => files[ci.ArgAt(0)]); - fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(machineIdPresent); - fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { MachineId }); + if (machineId != null) + { + fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(true); + fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { machineId }); + } + + if (generatedKeyFileContents != null) + { + fileSystem.FileExists(GeneratedKeyPath).Returns(true); + fileSystem.ReadAllText(GeneratedKeyPath).Returns(generatedKeyFileContents); + } return MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle"), GeneratedKeyPath); } From f5d302b8a13508595ce110a5b47fc3606805b737 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:52:58 +1100 Subject: [PATCH 033/124] Inline encryptor setup in legacy ciphertext tests --- .../LegacyCiphertextCompatibilityTests.cs | 32 +++++-------------- 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs index 3dc60d37c..eab9c4429 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs @@ -15,10 +15,6 @@ namespace Octopus.Tentacle.Tests.Configuration.Crypto [LinuxOrMacTest] public class LegacyCiphertextCompatibilityTests { - const string MachineId = "816490f117f14c7a8fa2697781ed795b"; - const string GeneratedKeyPath = "/etc/octopus/machinekey"; - const string GeneratedKeyFileContents = "MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=.ZmVkY2JhOTg3NjU0MzIxMA=="; - const string CertificateSizedText = "AAcOFRwjKjE4P0ZNVFtiaXB3foWMk5qhqK+2vcTL0tng5+71/AMKERgfJi00O0JJUFdeZWxzeoGIj5adpKuyucDHztXc4+rx+P8GDRQbIikwNz5FTFNaYWhvdn2Ei5KZoKeutbzDytHY3+bt9PsCCRAXHiUsMzpBSE9WXWRrcnmAh46VnKOqsbi/xs3U2+Lp8Pf+BQwTGiEoLzY9REtSWWBnbnV8g4qRmJ+mrbS7wsnQ197l7PP6AQgPFh0kKzI5QEdOVVxjanF4f4aNlJuiqbC3vsXM09rh6O/2/QQLEhkgJy41PENKUVhfZm10e4KJkJeepayzusHIz9bd5Ovy+QAHDhUcIyoxOD9GTVRbYmlwd36FjJOaoaivtr3Ey9LZ4Ofu9fwDChEYHyYt"; [TestCase("FooBar", "yspqcK7xCvd5c+1OSB7kxw==")] @@ -29,7 +25,10 @@ public class LegacyCiphertextCompatibilityTests public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string plaintext, string legacyCiphertext) { // Arrange - var encryptor = CreateEncryptor(machineId: MachineId, generatedKeyFileContents: null); + var fileSystem = Substitute.For(); + fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(true); + fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { "816490f117f14c7a8fa2697781ed795b" }); + var encryptor = MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle"), "/etc/octopus/machinekey"); // Act var decrypted = encryptor.Decrypt(legacyCiphertext); @@ -46,7 +45,10 @@ public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string pl public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plaintext, string legacyCiphertext) { // Arrange - var encryptor = CreateEncryptor(machineId: null, generatedKeyFileContents: GeneratedKeyFileContents); + var fileSystem = Substitute.For(); + fileSystem.FileExists("/etc/octopus/machinekey").Returns(true); + fileSystem.ReadAllText("/etc/octopus/machinekey").Returns("MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=.ZmVkY2JhOTg3NjU0MzIxMA=="); + var encryptor = MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle"), "/etc/octopus/machinekey"); // Act var decrypted = encryptor.Decrypt(legacyCiphertext); @@ -54,24 +56,6 @@ public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plai // Assert decrypted.Should().Be(plaintext); } - - static IMachineKeyEncryptor CreateEncryptor(string? machineId, string? generatedKeyFileContents) - { - var fileSystem = Substitute.For(); - if (machineId != null) - { - fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(true); - fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { machineId }); - } - - if (generatedKeyFileContents != null) - { - fileSystem.FileExists(GeneratedKeyPath).Returns(true); - fileSystem.ReadAllText(GeneratedKeyPath).Returns(generatedKeyFileContents); - } - - return MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle"), GeneratedKeyPath); - } } } #endif From 2bb4853fe627271656c58fc0e00c0b80234544b1 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:57:23 +1100 Subject: [PATCH 034/124] Remove LinuxConfigurationFileSecurityFixture --- .../LinuxConfigurationFileSecurityFixture.cs | 158 ------------------ 1 file changed, 158 deletions(-) delete mode 100644 source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs deleted file mode 100644 index 45747af51..000000000 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs +++ /dev/null @@ -1,158 +0,0 @@ -#if !NETFRAMEWORK -using System; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; -using System.Threading; -using System.Threading.Tasks; -using FluentAssertions; -using NSubstitute; -using NUnit.Framework; -using Octopus.Tentacle.Configuration.Crypto; -using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Core.Util; -using Octopus.Tentacle.Tests.Support.TestAttributes; -using Octopus.Tentacle.Util; - -namespace Octopus.Tentacle.Tests.Configuration.Crypto -{ - [TestFixture] - [LinuxTest] - [SupportedOSPlatform("linux")] - public class LinuxConfigurationFileSecurityFixture - { - const UnixFileMode OwnerReadWrite = UnixFileMode.UserRead | UnixFileMode.UserWrite; - - string directory; - string keyFilePath; - ISystemLog log; - OctopusPhysicalFileSystem fileSystem; - - [SetUp] - public void SetUp() - { - directory = Path.Combine(Path.GetTempPath(), "octopus-config-encryption-key-" + Guid.NewGuid()); - keyFilePath = Path.Combine(directory, ConfigurationEncryptionKey.KeyFileName); - log = Substitute.For(); - fileSystem = new OctopusPhysicalFileSystem(log); - } - - [TearDown] - public void TearDown() - { - if (Directory.Exists(directory)) - { - Directory.Delete(directory, recursive: true); - } - } - - [Test] - public void WhenTheKeyIsCreatedThenOnlyItsOwnerCanReadIt() - { - // Arrange - var keySource = new ConfigurationEncryptionKey(log, fileSystem, keyFilePath); - - // Act - keySource.CreateIfMissing(); - var key = keySource.Load(); - - // Assert - File.Exists(keyFilePath).Should().BeTrue("the directory is created on demand, as it always was"); - File.GetUnixFileMode(keyFilePath).Should().Be(OwnerReadWrite); - File.ReadAllText(keyFilePath).Should().Be(Convert.ToBase64String(key)); - Directory.GetFiles(directory).Should().ContainSingle("the temporary file the key is written to first is not left behind"); - } - - [Test] - public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() - { - // Arrange - const int racers = 32; - using var start = new ManualResetEventSlim(false); - var loads = Enumerable.Range(0, racers) - .Select(_ => Task.Run(() => - { - start.Wait(); - var keySource = new ConfigurationEncryptionKey(log, new OctopusPhysicalFileSystem(log), keyFilePath); - keySource.CreateIfMissing(); - return keySource.Load(); - })) - .ToArray(); - - // Act - start.Set(); - var keys = await Task.WhenAll(loads); - - // Assert - var onDisk = Convert.FromBase64String(File.ReadAllText(keyFilePath)); - keys.Should().AllSatisfy(k => k.Should().Equal(onDisk)); - Directory.GetFiles(directory).Should().ContainSingle("no racer's temporary file is left behind"); - } - - [Test] - public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillReadIt() - { - if (geteuid() != 0) - { - Assert.Ignore("Creating a key for another user needs root."); - } - - // Arrange - var user = "octo-key-" + Guid.NewGuid().ToString("N").Substring(0, 8); - CreateUser(user).Should().Be(0); - var instanceKeyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); - var keySource = new ConfigurationEncryptionKey(log, fileSystem, instanceKeyFilePath); - var previousUmask = umask(Convert.ToUInt32("027", 8)); - try - { - // Act - keySource.CreateIfMissing(); - var owner = uint.Parse(RunAndRead("id", $"-u {user}")); - UnixFile.SetOwnerIfRunningAsRoot(owner, keySource.KeyDirectory!); - UnixFile.SetOwnerIfRunningAsRoot(owner, instanceKeyFilePath); - - // Assert - Run("su", $"-s /bin/sh -c \"cat {instanceKeyFilePath}\" {user}").Should().Be(0, "the owner must be able to traverse the shared directories to its key"); - File.GetUnixFileMode(keySource.KeyDirectory!).Should().Be(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); - } - finally - { - umask(previousUmask); - DeleteUser(user); - } - } - - // Alpine has BusyBox's adduser and deluser rather than useradd and userdel. - static bool IsAlpine => File.Exists("/etc/alpine-release"); - - static int CreateUser(string user) - => IsAlpine ? Run("adduser", $"-D -H {user}") : Run("useradd", $"--no-create-home {user}"); - - static int DeleteUser(string user) - => IsAlpine ? Run("deluser", user) : Run("userdel", user); - - static int Run(string fileName, string arguments) - { - using var process = Process.Start(fileName, arguments); - process.WaitForExit(); - return process.ExitCode; - } - - static string RunAndRead(string fileName, string arguments) - { - using var process = Process.Start(new ProcessStartInfo(fileName, arguments) { RedirectStandardOutput = true })!; - var output = process.StandardOutput.ReadToEnd().Trim(); - process.WaitForExit(); - return output; - } - - [DllImport("libc")] - static extern uint geteuid(); - - [DllImport("libc")] - static extern uint umask(uint mask); - } -} -#endif From 76759de04ea1f90114144c281a0f8f63a175327b Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 13:59:38 +1100 Subject: [PATCH 035/124] Rename LinuxMachineKeyEncryptorFixture to Tests and inline setup --- ...re.cs => LinuxMachineKeyEncryptorTests.cs} | 21 ++++++------------- 1 file changed, 6 insertions(+), 15 deletions(-) rename source/Octopus.Tentacle.Tests/Configuration/Crypto/{LinuxMachineKeyEncryptorFixture.cs => LinuxMachineKeyEncryptorTests.cs} (64%) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorTests.cs similarity index 64% rename from source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs rename to source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorTests.cs index d10a79460..45a8ebc95 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorTests.cs @@ -10,20 +10,13 @@ namespace Octopus.Tentacle.Tests.Configuration.Crypto { - [TestFixture] - public class LinuxMachineKeyEncryptorFixture + public class LinuxMachineKeyEncryptorTests { - readonly ISystemLog systemLog = Substitute.For(); - readonly ConfigurationEncryptionKey generatedKey = InMemoryConfigurationEncryptionKey.Create(); - - LinuxMachineKeyEncryptor CreateEncryptor(params ICryptoKeyNixSource[] legacyKeySources) - => new(systemLog, generatedKey, legacyKeySources); - [Test] public void WhenAValueIsEncryptedThenItIsVersionedAndDecrypts() { // Arrange - var encryptor = CreateEncryptor(); + var encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), Array.Empty()); // Act var encrypted = encryptor.Encrypt("FooBar"); @@ -38,9 +31,8 @@ public void WhenAValueIsEncryptedThenItIsVersionedAndDecrypts() public void WhenACurrentValueWasEncryptedWithAnotherKeyThenALegacyKeyIsNotTried() { // Arrange - var otherKey = InMemoryConfigurationEncryptionKey.Create(); - var encryptedWithOtherKey = new LinuxMachineKeyEncryptor(systemLog, otherKey, Array.Empty()).Encrypt("FooBar"); - var encryptor = CreateEncryptor(new InMemoryCryptoKeyNixSource()); + var encryptedWithOtherKey = new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), Array.Empty()).Encrypt("FooBar"); + var encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), new ICryptoKeyNixSource[] { new InMemoryCryptoKeyNixSource() }); // Act Action decrypt = () => encryptor.Decrypt(encryptedWithOtherKey); @@ -54,9 +46,8 @@ public void WhenACurrentValueWasEncryptedWithAnotherKeyThenALegacyKeyIsNotTried( public void WhenTheSpecifierIsAlteredThenDecryptionFails(string alteredSpecifier) { // Arrange - var encryptor = CreateEncryptor(); - var encrypted = encryptor.Encrypt("FooBar"); - var tampered = alteredSpecifier + encrypted.Substring(LinuxMachineKeyEncryptor.Specifier.Length); + var encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), Array.Empty()); + var tampered = alteredSpecifier + encryptor.Encrypt("FooBar").Substring(LinuxMachineKeyEncryptor.Specifier.Length); // Act Action decrypt = () => encryptor.Decrypt(tampered); From e68809dd9db3444f79adcce4ca46525c9c269f7d Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:01:37 +1100 Subject: [PATCH 036/124] Convert fixtures added in this PR to Tests classes without shared setup --- ...s => ConfigurationFilePermissionsTests.cs} | 3 +- ...e.cs => ReplaceCertificateCommandTests.cs} | 3 +- ....cs => ApplicationInstanceManagerTests.cs} | 3 +- ...s => ConfigurationFilePermissionsTests.cs} | 14 +- .../TentacleConfigurationUpgradeFixture.cs | 222 ----------------- .../TentacleConfigurationUpgradeTests.cs | 228 ++++++++++++++++++ ... XmlFileKeyValueStoreReEncryptionTests.cs} | 39 +-- 7 files changed, 242 insertions(+), 270 deletions(-) rename source/Octopus.Tentacle.Tests.Integration/Configuration/{ConfigurationFilePermissionsFixture.cs => ConfigurationFilePermissionsTests.cs} (95%) rename source/Octopus.Tentacle.Tests/Commands/{ReplaceCertificateCommandFixture.cs => ReplaceCertificateCommandTests.cs} (99%) rename source/Octopus.Tentacle.Tests/Configuration/{ApplicationInstanceManagerFixture.cs => ApplicationInstanceManagerTests.cs} (96%) rename source/Octopus.Tentacle.Tests/Configuration/{ConfigurationFilePermissionsFixture.cs => ConfigurationFilePermissionsTests.cs} (87%) delete mode 100644 source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs create mode 100644 source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs rename source/Octopus.Tentacle.Tests/Configuration/{XmlFileKeyValueStoreReEncryptionFixture.cs => XmlFileKeyValueStoreReEncryptionTests.cs} (64%) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsTests.cs similarity index 95% rename from source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs rename to source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsTests.cs index 131e18043..7ae0b5e10 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsTests.cs @@ -14,11 +14,10 @@ namespace Octopus.Tentacle.Tests.Integration.Configuration { - [TestFixture] [LinuxTest] [NonParallelizable] [UnsupportedOSPlatform("windows")] - public class ConfigurationFilePermissionsFixture + public class ConfigurationFilePermissionsTests { [Test] [RequiresSudoOnLinux] diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs similarity index 99% rename from source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs rename to source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs index 48997c091..c19fb938d 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs @@ -22,8 +22,7 @@ namespace Octopus.Tentacle.Tests.Commands { - [TestFixture] - public class ReplaceCertificateCommandFixture + public class ReplaceCertificateCommandTests { [Test] public void ShouldUpdateEveryRegistrationWithTheOldThumbprintInEverySpace() diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerTests.cs similarity index 96% rename from source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerFixture.cs rename to source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerTests.cs index 2b8e0ba27..2a13331d1 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerTests.cs @@ -10,9 +10,8 @@ namespace Octopus.Tentacle.Tests.Configuration { - [TestFixture] [LinuxTest] - public class ApplicationInstanceManagerFixture + public class ApplicationInstanceManagerTests { [Test] public void WhenTheConfigurationEncryptionKeyCannotBeCreatedThenNoInstanceIsCreated() diff --git a/source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsTests.cs similarity index 87% rename from source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs rename to source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsTests.cs index 42ffaf598..fac43826f 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsTests.cs @@ -6,23 +6,15 @@ using NUnit.Framework; using Octopus.Tentacle.Configuration; using Octopus.Tentacle.Tests.Support; +using Octopus.Tentacle.Tests.Support.TestAttributes; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Configuration { - [TestFixture] + [LinuxOrMacTest] [UnsupportedOSPlatform("windows")] - public class ConfigurationFilePermissionsFixture + public class ConfigurationFilePermissionsTests { - [SetUp] - public void SkipOnWindows() - { - if (OperatingSystem.IsWindows()) - { - Assert.Ignore("Unix file modes only"); - } - } - [Test] public void WhenAWorldReadableConfigIsRestrictedThenOnlyItsOwnerCanReadIt() { diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs deleted file mode 100644 index 56cc29528..000000000 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs +++ /dev/null @@ -1,222 +0,0 @@ -#if NET -using System; -using System.IO; -using System.Linq; -using System.Runtime.Versioning; -using System.Security.Cryptography; -using System.Xml.Linq; -using FluentAssertions; -using NSubstitute; -using NUnit.Framework; -using Octopus.Tentacle.Commands; -using Octopus.Tentacle.Configuration; -using Octopus.Tentacle.Configuration.Crypto; -using Octopus.Tentacle.Configuration.Instances; -using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Internals.Options; -using Octopus.Tentacle.Startup; -using Octopus.Tentacle.Tests.Support; -using Octopus.Tentacle.Tests.Support.TestAttributes; -using Octopus.Tentacle.Util; - -namespace Octopus.Tentacle.Tests.Configuration -{ - [TestFixture] - [LinuxOrMacTest] - [UnsupportedOSPlatform("windows")] - public class TentacleConfigurationUpgradeFixture - { - const string Certificate = "MIIC...the certificate..."; - - string directory; - string configurationFile; - ISystemLog log; - OctopusPhysicalFileSystem fileSystem; - - [SetUp] - public void SetUp() - { - directory = Path.Combine(Path.GetTempPath(), "octopus-config-upgrade-" + Guid.NewGuid()); - Directory.CreateDirectory(directory); - configurationFile = Path.Combine(directory, "tentacle.config"); - log = Substitute.For(); - fileSystem = new OctopusPhysicalFileSystem(log); - fileSystem.OverwriteFile(configurationFile, @""); - } - - [TearDown] - public void TearDown() - { - Directory.Delete(directory, recursive: true); - } - - [Test] - public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted() - { - // Arrange - var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); - var store = CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - RawCertificate().Should().NotStartWith(LinuxMachineKeyEncryptor.Specifier + "$", "without a key, values are written the way earlier versions wrote them"); - - // Act - CreateUpgrade(store, keyFilePath).Upgrade(); - - // Assert - File.Exists(keyFilePath).Should().BeTrue(); - RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); - CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); - log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); - } - - [Test] - public void WhenOnlyTheKeyIsPreparedThenItIsCreatedAndValuesStayLegacy() - { - // Arrange - var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); - var store = CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - var legacyValue = RawCertificate(); - - // Act - CreateUpgrade(store, keyFilePath).PrepareKey(); - - // Assert - File.Exists(keyFilePath).Should().BeTrue(); - RawCertificate().Should().Be(legacyValue); - log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); - } - - [Test] - public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() - { - // Arrange - var keyFilePath = Path.Combine(configurationFile, "not-a-directory", ConfigurationEncryptionKey.KeyFileName); - var store = CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - var legacyValue = RawCertificate(); - - // Act - Action run = () => CreateUpgrade(store, keyFilePath).Upgrade(); - - // Assert - run.Should().Throw(); - RawCertificate().Should().Be(legacyValue); - } - - [Test] - public void WhenTheConfigurationIsNotInTheRegistryThenNoKeyIsCreatedAndValuesStayLegacy() - { - // Arrange - var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); - var store = CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - var legacyValue = RawCertificate(); - - // Act - CreateUpgrade(store, keyFilePath: null, instanceName: null).Upgrade(); - - // Assert - File.Exists(keyFilePath).Should().BeFalse(); - RawCertificate().Should().Be(legacyValue); - log.Received(1).Warn(Arg.Any()); - } - - [Test] - public void UpgradeConfigurationEncryptionCreatesTheKeyAndReEncryptsLegacyValues() - { - // Arrange - var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); - var store = CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - - // Act - StartUpgradeCommand(store, keyFilePath); - - // Assert - File.Exists(keyFilePath).Should().BeTrue(); - RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); - CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); - } - - [Test] - public void UpgradeConfigurationEncryptionFailsForAConfigurationNotInTheRegistry() - { - // Arrange - var store = CreateStore(Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName)); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - var legacyValue = RawCertificate(); - - // Act - Action start = () => StartUpgradeCommand(store, keyFilePath: null, instanceName: null); - - // Assert - start.Should().Throw().WithMessage("*create-instance --instance*"); - RawCertificate().Should().Be(legacyValue); - } - - [Test] - public void AValueProtectedWithTheKeyIsNeverRewrittenWithALegacyKey() - { - // Arrange - var keyFilePath = Path.Combine(directory, "my-key", ConfigurationEncryptionKey.KeyFileName); - new ConfigurationEncryptionKey(log, fileSystem, keyFilePath).CreateIfMissing(); - CreateStore(keyFilePath).Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - var protectedValue = RawCertificate(); - var storeWithoutKey = CreateStore(Path.Combine(directory, "missing", ConfigurationEncryptionKey.KeyFileName)); - - // Act - Action set = () => storeWithoutKey.Set(TentacleConfiguration.CertificateSettingName, "another certificate", ProtectionLevel.MachineKey); - - // Assert - set.Should().Throw(); - RawCertificate().Should().Be(protectedValue); - } - - [Test] - public void WhenTheKeyIsLostAfterMigrationThenStartLeavesProtectedValuesUntouched() - { - // Arrange - var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); - var store = CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - CreateUpgrade(store, keyFilePath).Upgrade(); - var protectedValue = RawCertificate(); - File.Delete(keyFilePath); - - // Act - CreateUpgrade(CreateStore(keyFilePath), keyFilePath).Upgrade(); - - // Assert - RawCertificate().Should().Be(protectedValue); - RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); - } - - readonly InMemoryCryptoKeyNixSource legacyKey = new(); - - XmlFileKeyValueStore CreateStore(string keyFilePath) - => new(fileSystem, configurationFile, encryptor: new LinuxMachineKeyEncryptor(log, new ConfigurationEncryptionKey(log, fileSystem, keyFilePath), new[] { legacyKey })); - - TentacleConfigurationUpgrade CreateUpgrade(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle") - => new(CreateSelector(store, keyFilePath, instanceName), fileSystem, log); - - void StartUpgradeCommand(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle") - { - var selector = CreateSelector(store, keyFilePath, instanceName); - var upgrade = new TentacleConfigurationUpgrade(selector, fileSystem, log); - var command = new UpgradeConfigurationEncryptionCommand(new Lazy(() => upgrade), selector, log, Substitute.For()); - command.Start(new string[0], Substitute.For(), new OptionSet()); - } - - IApplicationInstanceSelector CreateSelector(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName) - { - var selector = Substitute.For(); - selector.Current.Returns(new ApplicationInstanceConfiguration(instanceName, configurationFile, store, store, keyFilePath)); - return selector; - } - - string RawCertificate() - => XDocument.Load(configurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; - } -} -#endif diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs new file mode 100644 index 000000000..dee63de2c --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs @@ -0,0 +1,228 @@ +#if NET +using System; +using System.IO; +using System.Linq; +using System.Runtime.Versioning; +using System.Security.Cryptography; +using System.Xml.Linq; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Commands; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Internals.Options; +using Octopus.Tentacle.Startup; +using Octopus.Tentacle.Tests.Support; +using Octopus.Tentacle.Tests.Support.TestAttributes; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Tests.Configuration +{ + [LinuxOrMacTest] + [UnsupportedOSPlatform("windows")] + public class TentacleConfigurationUpgradeTests + { + const string Certificate = "MIIC...the certificate..."; + + [Test] + public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted() + { + // Arrange + using var sandbox = new ConfigurationSandbox(); + var keyFilePath = sandbox.DefaultKeyFilePath; + var store = sandbox.CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + sandbox.RawCertificate().Should().NotStartWith(LinuxMachineKeyEncryptor.Specifier + "$", "without a key, values are written the way earlier versions wrote them"); + + // Act + sandbox.CreateUpgrade(store, keyFilePath).Upgrade(); + + // Assert + File.Exists(keyFilePath).Should().BeTrue(); + sandbox.RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); + sandbox.CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); + sandbox.Log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); + } + + [Test] + public void WhenOnlyTheKeyIsPreparedThenItIsCreatedAndValuesStayLegacy() + { + // Arrange + using var sandbox = new ConfigurationSandbox(); + var keyFilePath = sandbox.DefaultKeyFilePath; + var store = sandbox.CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + var legacyValue = sandbox.RawCertificate(); + + // Act + sandbox.CreateUpgrade(store, keyFilePath).PrepareKey(); + + // Assert + File.Exists(keyFilePath).Should().BeTrue(); + sandbox.RawCertificate().Should().Be(legacyValue); + sandbox.Log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); + } + + [Test] + public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() + { + // Arrange + using var sandbox = new ConfigurationSandbox(); + var keyFilePath = Path.Combine(sandbox.ConfigurationFile, "not-a-directory", ConfigurationEncryptionKey.KeyFileName); + var store = sandbox.CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + var legacyValue = sandbox.RawCertificate(); + + // Act + Action run = () => sandbox.CreateUpgrade(store, keyFilePath).Upgrade(); + + // Assert + run.Should().Throw(); + sandbox.RawCertificate().Should().Be(legacyValue); + } + + [Test] + public void WhenTheConfigurationIsNotInTheRegistryThenNoKeyIsCreatedAndValuesStayLegacy() + { + // Arrange + using var sandbox = new ConfigurationSandbox(); + var keyFilePath = sandbox.DefaultKeyFilePath; + var store = sandbox.CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + var legacyValue = sandbox.RawCertificate(); + + // Act + sandbox.CreateUpgrade(store, keyFilePath: null, instanceName: null).Upgrade(); + + // Assert + File.Exists(keyFilePath).Should().BeFalse(); + sandbox.RawCertificate().Should().Be(legacyValue); + sandbox.Log.Received(1).Warn(Arg.Any()); + } + + [Test] + public void UpgradeConfigurationEncryptionCreatesTheKeyAndReEncryptsLegacyValues() + { + // Arrange + using var sandbox = new ConfigurationSandbox(); + var keyFilePath = sandbox.DefaultKeyFilePath; + var store = sandbox.CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + + // Act + sandbox.StartUpgradeCommand(store, keyFilePath); + + // Assert + File.Exists(keyFilePath).Should().BeTrue(); + sandbox.RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); + sandbox.CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); + } + + [Test] + public void UpgradeConfigurationEncryptionFailsForAConfigurationNotInTheRegistry() + { + // Arrange + using var sandbox = new ConfigurationSandbox(); + var store = sandbox.CreateStore(sandbox.DefaultKeyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + var legacyValue = sandbox.RawCertificate(); + + // Act + Action start = () => sandbox.StartUpgradeCommand(store, keyFilePath: null, instanceName: null); + + // Assert + start.Should().Throw().WithMessage("*create-instance --instance*"); + sandbox.RawCertificate().Should().Be(legacyValue); + } + + [Test] + public void AValueProtectedWithTheKeyIsNeverRewrittenWithALegacyKey() + { + // Arrange + using var sandbox = new ConfigurationSandbox(); + var keyFilePath = Path.Combine(sandbox.Directory, "my-key", ConfigurationEncryptionKey.KeyFileName); + new ConfigurationEncryptionKey(sandbox.Log, sandbox.FileSystem, keyFilePath).CreateIfMissing(); + sandbox.CreateStore(keyFilePath).Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + var protectedValue = sandbox.RawCertificate(); + var storeWithoutKey = sandbox.CreateStore(Path.Combine(sandbox.Directory, "missing", ConfigurationEncryptionKey.KeyFileName)); + + // Act + Action set = () => storeWithoutKey.Set(TentacleConfiguration.CertificateSettingName, "another certificate", ProtectionLevel.MachineKey); + + // Assert + set.Should().Throw(); + sandbox.RawCertificate().Should().Be(protectedValue); + } + + [Test] + public void WhenTheKeyIsLostAfterMigrationThenStartLeavesProtectedValuesUntouched() + { + // Arrange + using var sandbox = new ConfigurationSandbox(); + var keyFilePath = sandbox.DefaultKeyFilePath; + var store = sandbox.CreateStore(keyFilePath); + store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); + sandbox.CreateUpgrade(store, keyFilePath).Upgrade(); + var protectedValue = sandbox.RawCertificate(); + File.Delete(keyFilePath); + + // Act + sandbox.CreateUpgrade(sandbox.CreateStore(keyFilePath), keyFilePath).Upgrade(); + + // Assert + sandbox.RawCertificate().Should().Be(protectedValue); + sandbox.RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); + } + + sealed class ConfigurationSandbox : IDisposable + { + readonly InMemoryCryptoKeyNixSource legacyKey = new(); + + public ConfigurationSandbox() + { + Directory = Path.Combine(Path.GetTempPath(), "octopus-config-upgrade-" + Guid.NewGuid()); + System.IO.Directory.CreateDirectory(Directory); + ConfigurationFile = Path.Combine(Directory, "tentacle.config"); + FileSystem = new OctopusPhysicalFileSystem(Log); + FileSystem.OverwriteFile(ConfigurationFile, @""); + } + + public string Directory { get; } + public string ConfigurationFile { get; } + public ISystemLog Log { get; } = Substitute.For(); + public OctopusPhysicalFileSystem FileSystem { get; } + + public string DefaultKeyFilePath => Path.Combine(Directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); + + public XmlFileKeyValueStore CreateStore(string keyFilePath) + => new(FileSystem, ConfigurationFile, encryptor: new LinuxMachineKeyEncryptor(Log, new ConfigurationEncryptionKey(Log, FileSystem, keyFilePath), new[] { legacyKey })); + + public TentacleConfigurationUpgrade CreateUpgrade(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle") + => new(CreateSelector(store, keyFilePath, instanceName), FileSystem, Log); + + public void StartUpgradeCommand(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle") + { + var selector = CreateSelector(store, keyFilePath, instanceName); + var upgrade = new TentacleConfigurationUpgrade(selector, FileSystem, Log); + var command = new UpgradeConfigurationEncryptionCommand(new Lazy(() => upgrade), selector, Log, Substitute.For()); + command.Start(new string[0], Substitute.For(), new OptionSet()); + } + + public string RawCertificate() + => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; + + IApplicationInstanceSelector CreateSelector(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName) + { + var selector = Substitute.For(); + selector.Current.Returns(new ApplicationInstanceConfiguration(instanceName, ConfigurationFile, store, store, keyFilePath)); + return selector; + } + + public void Dispose() => System.IO.Directory.Delete(Directory, recursive: true); + } + } +} +#endif diff --git a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionTests.cs similarity index 64% rename from source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs rename to source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionTests.cs index c53a3983d..3f838e1bb 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionTests.cs @@ -14,42 +14,19 @@ namespace Octopus.Tentacle.Tests.Configuration { - [TestFixture] - public class XmlFileKeyValueStoreReEncryptionFixture + public class XmlFileKeyValueStoreReEncryptionTests { - string configurationFile; - OctopusPhysicalFileSystem fileSystem; - InMemoryCryptoKeyNixSource legacyKey; - LinuxMachineKeyEncryptor encryptor; - XmlFileKeyValueStore legacyStore; - XmlFileKeyValueStore store; - - [SetUp] - public void SetUp() - { - configurationFile = Path.GetTempFileName(); - fileSystem = new OctopusPhysicalFileSystem(Substitute.For()); - fileSystem.OverwriteFile(configurationFile, @""); - - legacyKey = new InMemoryCryptoKeyNixSource(); - encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), new[] { legacyKey }); - - // Writes what an earlier version would have left in the file... - legacyStore = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: new LegacySchemeEncryptor(legacyKey)); - // ...and this is the store the upgraded Tentacle opens it with. - store = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: encryptor); - } - - [TearDown] - public void TearDown() - { - File.Delete(configurationFile); - } - [Test] public void WhenSerialisedValuesAreReEncryptedThenTypedReadsStillWork() { // Arrange + var configurationFile = Path.GetTempFileName(); + var fileSystem = new OctopusPhysicalFileSystem(Substitute.For()); + fileSystem.OverwriteFile(configurationFile, @""); + var legacyKey = new InMemoryCryptoKeyNixSource(); + var encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), new[] { legacyKey }); + var legacyStore = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: new LegacySchemeEncryptor(legacyKey)); + var store = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: encryptor); var names = new[] { "a.bool", "an.int", "an.enum", "an.object" }; var configurationObject = new MyObject { IntField = 10, BooleanField = true, EnumField = SomeEnum.SomeOtherEnumValue, ArrayField = new[] { new MyNestedObject { Id = 1 } } }; legacyStore.Set("a.bool", true, ProtectionLevel.MachineKey); From 104afbd2b9063582f105322b0e3c4bd939d07a91 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:12:40 +1100 Subject: [PATCH 037/124] Test on each distro that a non-root create-instance is told the command that fixes it, and that it does --- .../test-scripts/test-linux-package.sh | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh index c5c72bdd5..1ff0db689 100644 --- a/linux-packages/test-scripts/test-linux-package.sh +++ b/linux-packages/test-scripts/test-linux-package.sh @@ -100,5 +100,48 @@ fi echo "The certificate decrypts in a new process and matches the recorded thumbprint." echo "" +# A non-root user that cannot create its key must be told the exact commands that fix it, and those commands must work. +NON_ROOT_USER="tentacle-test" +NON_ROOT_INSTANCE="non-root-test" +NON_ROOT_CONFIGURATION_FILE="/etc/octopus/$NON_ROOT_INSTANCE/tentacle.config" +# Minimal images may not have useradd. +echo "$NON_ROOT_USER:x:4322:4322::/tmp:/bin/sh" >> /etc/passwd +mkdir -p "$(dirname "$NON_ROOT_CONFIGURATION_FILE")" /etc/octopus/Tentacle/Instances +chown "$NON_ROOT_USER" "$(dirname "$NON_ROOT_CONFIGURATION_FILE")" /etc/octopus/Tentacle/Instances +TENTACLE=$(command -v Tentacle) + +# Amazon Linux's minimal image has neither setpriv nor su. +if ! command -v setpriv > /dev/null && ! command -v su > /dev/null; then + yum --quiet --assumeyes install util-linux +fi + +run_as_non_root() { + if command -v setpriv > /dev/null; then + HOME=/tmp setpriv --reuid=4322 --regid=4322 --clear-groups "$TENTACLE" "$@" + else + su -s /bin/sh "$NON_ROOT_USER" -c "$TENTACLE $*" + fi +} + +if CREATE_OUTPUT=$(run_as_non_root create-instance --instance "$NON_ROOT_INSTANCE" --config "$NON_ROOT_CONFIGURATION_FILE" 2>&1); then + echo "create-instance succeeded for a user that cannot create the key under /var/lib/octopus/tentacle." + exit 1 +fi +echo "$CREATE_OUTPUT" + +FIX_COMMAND=$(echo "$CREATE_OUTPUT" | grep -o 'sudo mkdir[^`]*' | head -n 1) +if [[ -z "$FIX_COMMAND" ]]; then + echo "The create-instance error did not tell the user which command fixes it." + exit 1 +fi + +# This script already runs as root, and minimal images may not have sudo. +sudo() { "$@"; } +eval "$FIX_COMMAND" + +run_as_non_root create-instance --instance "$NON_ROOT_INSTANCE" --config "$NON_ROOT_CONFIGURATION_FILE" +echo "Running the command from the error message let the non-root user create its instance." +echo "" + echo "All tests passed." echo "" From eaeabd31df064f687129c9365658ed1fc0de37a2 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:13:37 +1100 Subject: [PATCH 038/124] Revert "Test on each distro that a non-root create-instance is told the command that fixes it, and that it does" This reverts commit 104afbd2b9063582f105322b0e3c4bd939d07a91. --- .../test-scripts/test-linux-package.sh | 43 ------------------- 1 file changed, 43 deletions(-) diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh index 1ff0db689..c5c72bdd5 100644 --- a/linux-packages/test-scripts/test-linux-package.sh +++ b/linux-packages/test-scripts/test-linux-package.sh @@ -100,48 +100,5 @@ fi echo "The certificate decrypts in a new process and matches the recorded thumbprint." echo "" -# A non-root user that cannot create its key must be told the exact commands that fix it, and those commands must work. -NON_ROOT_USER="tentacle-test" -NON_ROOT_INSTANCE="non-root-test" -NON_ROOT_CONFIGURATION_FILE="/etc/octopus/$NON_ROOT_INSTANCE/tentacle.config" -# Minimal images may not have useradd. -echo "$NON_ROOT_USER:x:4322:4322::/tmp:/bin/sh" >> /etc/passwd -mkdir -p "$(dirname "$NON_ROOT_CONFIGURATION_FILE")" /etc/octopus/Tentacle/Instances -chown "$NON_ROOT_USER" "$(dirname "$NON_ROOT_CONFIGURATION_FILE")" /etc/octopus/Tentacle/Instances -TENTACLE=$(command -v Tentacle) - -# Amazon Linux's minimal image has neither setpriv nor su. -if ! command -v setpriv > /dev/null && ! command -v su > /dev/null; then - yum --quiet --assumeyes install util-linux -fi - -run_as_non_root() { - if command -v setpriv > /dev/null; then - HOME=/tmp setpriv --reuid=4322 --regid=4322 --clear-groups "$TENTACLE" "$@" - else - su -s /bin/sh "$NON_ROOT_USER" -c "$TENTACLE $*" - fi -} - -if CREATE_OUTPUT=$(run_as_non_root create-instance --instance "$NON_ROOT_INSTANCE" --config "$NON_ROOT_CONFIGURATION_FILE" 2>&1); then - echo "create-instance succeeded for a user that cannot create the key under /var/lib/octopus/tentacle." - exit 1 -fi -echo "$CREATE_OUTPUT" - -FIX_COMMAND=$(echo "$CREATE_OUTPUT" | grep -o 'sudo mkdir[^`]*' | head -n 1) -if [[ -z "$FIX_COMMAND" ]]; then - echo "The create-instance error did not tell the user which command fixes it." - exit 1 -fi - -# This script already runs as root, and minimal images may not have sudo. -sudo() { "$@"; } -eval "$FIX_COMMAND" - -run_as_non_root create-instance --instance "$NON_ROOT_INSTANCE" --config "$NON_ROOT_CONFIGURATION_FILE" -echo "Running the command from the error message let the non-root user create its instance." -echo "" - echo "All tests passed." echo "" From f93926c0b1daebdcca27272ffd2da233db544e1a Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:15:01 +1100 Subject: [PATCH 039/124] Test config encryption key failures through agent start and create-instance --- .../Commands/CreateInstanceCommandTests.cs | 63 +++++++++++++++++++ .../TentacleConfigurationUpgradeTests.cs | 20 +++--- 2 files changed, 74 insertions(+), 9 deletions(-) create mode 100644 source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs new file mode 100644 index 000000000..4583db82e --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs @@ -0,0 +1,63 @@ +#if NET +using System; +using System.IO; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Commands; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Core.Util; +using Octopus.Tentacle.Internals.Options; +using Octopus.Tentacle.Startup; +using Octopus.Tentacle.Tests.Support.TestAttributes; +using Octopus.Tentacle.Tests.Util; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Tests.Commands +{ + [LinuxOrMacTest] + [NonParallelizable] + public class CreateInstanceCommandTests + { + [Test] + public void WhenTheConfigurationEncryptionKeyCannotBeCreatedThenNoInstanceIsCreated() + { + // Arrange + var directory = Path.Combine(Path.GetTempPath(), "octopus-create-instance-" + Guid.NewGuid()); + Directory.CreateDirectory(directory); + var blockingFile = Path.Combine(directory, "not-a-directory"); + File.WriteAllText(blockingFile, ""); + using var _ = new TemporaryEnvironmentVariable(EnvironmentVariables.TentacleInstancesDataDirectory, blockingFile); + var configurationFile = Path.Combine(directory, "Tentacle", "tentacle.config"); + var log = Substitute.For(); + var fileSystem = new OctopusPhysicalFileSystem(log); + var instanceStore = Substitute.For(); + var manager = new ApplicationInstanceManager( + ApplicationName.Tentacle, + new StartUpRegistryInstanceRequest("Tentacle"), + fileSystem, + log, + instanceStore, + new Lazy(() => Substitute.For())); + var command = new CreateInstanceCommand(manager, Substitute.For(), new Lazy(() => Substitute.For())); + + try + { + // Act + Action create = () => command.Start(new[] { "--instance=Tentacle", $"--config={configurationFile}" }, Substitute.For(), new OptionSet()); + + // Assert + create.Should().Throw().WithMessage("*so the instance was not created*"); + File.Exists(configurationFile).Should().BeFalse(); + instanceStore.DidNotReceiveWithAnyArgs().RegisterInstance(default!); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + } +} +#endif diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs index dee63de2c..37cfed237 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs @@ -13,6 +13,7 @@ using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Configuration.Instances; using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Internals.Options; using Octopus.Tentacle.Startup; using Octopus.Tentacle.Tests.Support; @@ -41,33 +42,33 @@ public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted() sandbox.CreateUpgrade(store, keyFilePath).Upgrade(); // Assert - File.Exists(keyFilePath).Should().BeTrue(); + File.GetUnixFileMode(keyFilePath).Should().Be(UnixFileMode.UserRead | UnixFileMode.UserWrite); + UnixFile.OwnerOf(keyFilePath).Should().Be(UnixFile.OwnerOf(sandbox.ConfigurationFile)); sandbox.RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); sandbox.CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); sandbox.Log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); } [Test] - public void WhenOnlyTheKeyIsPreparedThenItIsCreatedAndValuesStayLegacy() + public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() { // Arrange using var sandbox = new ConfigurationSandbox(); - var keyFilePath = sandbox.DefaultKeyFilePath; + var keyFilePath = Path.Combine(sandbox.ConfigurationFile, "not-a-directory", ConfigurationEncryptionKey.KeyFileName); var store = sandbox.CreateStore(keyFilePath); store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); var legacyValue = sandbox.RawCertificate(); // Act - sandbox.CreateUpgrade(store, keyFilePath).PrepareKey(); + Action run = () => sandbox.CreateUpgrade(store, keyFilePath).Upgrade(); // Assert - File.Exists(keyFilePath).Should().BeTrue(); + run.Should().Throw(); sandbox.RawCertificate().Should().Be(legacyValue); - sandbox.Log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); } [Test] - public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() + public void WhenAgentStartCannotCreateTheKeyThenItWarnsAndKeepsWorkingOnLegacyValues() { // Arrange using var sandbox = new ConfigurationSandbox(); @@ -77,11 +78,12 @@ public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() var legacyValue = sandbox.RawCertificate(); // Act - Action run = () => sandbox.CreateUpgrade(store, keyFilePath).Upgrade(); + sandbox.CreateUpgrade(store, keyFilePath).TryUpgrade(); // Assert - run.Should().Throw(); + sandbox.Log.Received(1).Warn(Arg.Any(), Arg.Is(m => m.Contains("still protected by the key earlier versions used"))); sandbox.RawCertificate().Should().Be(legacyValue); + sandbox.CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); } [Test] From 9c1a24383649d991f453d68489bebc657df5642c Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:16:10 +1100 Subject: [PATCH 040/124] Test create-instance key failure through real instance store; drop internal TryUpgrade test --- .../Commands/CreateInstanceCommandTests.cs | 23 +++++++++---------- .../TentacleConfigurationUpgradeTests.cs | 23 +------------------ 2 files changed, 12 insertions(+), 34 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs index 4583db82e..918fa61e7 100644 --- a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs +++ b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs @@ -10,6 +10,8 @@ using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Internals.Options; +using Octopus.Tentacle.Kubernetes.Configuration; +using Octopus.Tentacle.Tests.Support; using Octopus.Tentacle.Startup; using Octopus.Tentacle.Tests.Support.TestAttributes; using Octopus.Tentacle.Tests.Util; @@ -29,19 +31,16 @@ public void WhenTheConfigurationEncryptionKeyCannotBeCreatedThenNoInstanceIsCrea Directory.CreateDirectory(directory); var blockingFile = Path.Combine(directory, "not-a-directory"); File.WriteAllText(blockingFile, ""); - using var _ = new TemporaryEnvironmentVariable(EnvironmentVariables.TentacleInstancesDataDirectory, blockingFile); + using var dataDirectory = new TemporaryEnvironmentVariable(EnvironmentVariables.TentacleInstancesDataDirectory, blockingFile); + using var homeDirectory = new TemporaryEnvironmentVariable(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, directory); var configurationFile = Path.Combine(directory, "Tentacle", "tentacle.config"); - var log = Substitute.For(); + var log = new InMemoryLog(); var fileSystem = new OctopusPhysicalFileSystem(log); - var instanceStore = Substitute.For(); - var manager = new ApplicationInstanceManager( - ApplicationName.Tentacle, - new StartUpRegistryInstanceRequest("Tentacle"), - fileSystem, - log, - instanceStore, - new Lazy(() => Substitute.For())); - var command = new CreateInstanceCommand(manager, Substitute.For(), new Lazy(() => Substitute.For())); + var request = new StartUpRegistryInstanceRequest("Tentacle"); + var instanceStore = new ApplicationInstanceStore(ApplicationName.Tentacle, log, fileSystem, Substitute.For()); + var selector = new ApplicationInstanceSelector(ApplicationName.Tentacle, instanceStore, request, Array.Empty(), new Lazy(() => throw new NotSupportedException()), fileSystem, log); + var manager = new ApplicationInstanceManager(ApplicationName.Tentacle, request, fileSystem, log, instanceStore, new Lazy(() => throw new NotSupportedException())); + var command = new CreateInstanceCommand(manager, Substitute.For(), new Lazy(() => new TentacleConfigurationUpgrade(selector, fileSystem, log))); try { @@ -51,7 +50,7 @@ public void WhenTheConfigurationEncryptionKeyCannotBeCreatedThenNoInstanceIsCrea // Assert create.Should().Throw().WithMessage("*so the instance was not created*"); File.Exists(configurationFile).Should().BeFalse(); - instanceStore.DidNotReceiveWithAnyArgs().RegisterInstance(default!); + instanceStore.ListInstances().Should().BeEmpty(); } finally { diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs index 37cfed237..ef1a53bb3 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs @@ -13,7 +13,6 @@ using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Configuration.Instances; using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Internals.Options; using Octopus.Tentacle.Startup; using Octopus.Tentacle.Tests.Support; @@ -42,8 +41,7 @@ public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted() sandbox.CreateUpgrade(store, keyFilePath).Upgrade(); // Assert - File.GetUnixFileMode(keyFilePath).Should().Be(UnixFileMode.UserRead | UnixFileMode.UserWrite); - UnixFile.OwnerOf(keyFilePath).Should().Be(UnixFile.OwnerOf(sandbox.ConfigurationFile)); + File.Exists(keyFilePath).Should().BeTrue(); sandbox.RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); sandbox.CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); sandbox.Log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); @@ -67,25 +65,6 @@ public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() sandbox.RawCertificate().Should().Be(legacyValue); } - [Test] - public void WhenAgentStartCannotCreateTheKeyThenItWarnsAndKeepsWorkingOnLegacyValues() - { - // Arrange - using var sandbox = new ConfigurationSandbox(); - var keyFilePath = Path.Combine(sandbox.ConfigurationFile, "not-a-directory", ConfigurationEncryptionKey.KeyFileName); - var store = sandbox.CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - var legacyValue = sandbox.RawCertificate(); - - // Act - sandbox.CreateUpgrade(store, keyFilePath).TryUpgrade(); - - // Assert - sandbox.Log.Received(1).Warn(Arg.Any(), Arg.Is(m => m.Contains("still protected by the key earlier versions used"))); - sandbox.RawCertificate().Should().Be(legacyValue); - sandbox.CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); - } - [Test] public void WhenTheConfigurationIsNotInTheRegistryThenNoKeyIsCreatedAndValuesStayLegacy() { From 8c796d90782319fc6f6cf49ea8075d709a6b9dd7 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:23:53 +1100 Subject: [PATCH 041/124] Restore Linux key file permission, concurrency and umask tests --- .../LinuxConfigurationFileSecurityFixture.cs | 158 ++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs new file mode 100644 index 000000000..45747af51 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs @@ -0,0 +1,158 @@ +#if !NETFRAMEWORK +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using NSubstitute; +using NUnit.Framework; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Core.Util; +using Octopus.Tentacle.Tests.Support.TestAttributes; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Tests.Configuration.Crypto +{ + [TestFixture] + [LinuxTest] + [SupportedOSPlatform("linux")] + public class LinuxConfigurationFileSecurityFixture + { + const UnixFileMode OwnerReadWrite = UnixFileMode.UserRead | UnixFileMode.UserWrite; + + string directory; + string keyFilePath; + ISystemLog log; + OctopusPhysicalFileSystem fileSystem; + + [SetUp] + public void SetUp() + { + directory = Path.Combine(Path.GetTempPath(), "octopus-config-encryption-key-" + Guid.NewGuid()); + keyFilePath = Path.Combine(directory, ConfigurationEncryptionKey.KeyFileName); + log = Substitute.For(); + fileSystem = new OctopusPhysicalFileSystem(log); + } + + [TearDown] + public void TearDown() + { + if (Directory.Exists(directory)) + { + Directory.Delete(directory, recursive: true); + } + } + + [Test] + public void WhenTheKeyIsCreatedThenOnlyItsOwnerCanReadIt() + { + // Arrange + var keySource = new ConfigurationEncryptionKey(log, fileSystem, keyFilePath); + + // Act + keySource.CreateIfMissing(); + var key = keySource.Load(); + + // Assert + File.Exists(keyFilePath).Should().BeTrue("the directory is created on demand, as it always was"); + File.GetUnixFileMode(keyFilePath).Should().Be(OwnerReadWrite); + File.ReadAllText(keyFilePath).Should().Be(Convert.ToBase64String(key)); + Directory.GetFiles(directory).Should().ContainSingle("the temporary file the key is written to first is not left behind"); + } + + [Test] + public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() + { + // Arrange + const int racers = 32; + using var start = new ManualResetEventSlim(false); + var loads = Enumerable.Range(0, racers) + .Select(_ => Task.Run(() => + { + start.Wait(); + var keySource = new ConfigurationEncryptionKey(log, new OctopusPhysicalFileSystem(log), keyFilePath); + keySource.CreateIfMissing(); + return keySource.Load(); + })) + .ToArray(); + + // Act + start.Set(); + var keys = await Task.WhenAll(loads); + + // Assert + var onDisk = Convert.FromBase64String(File.ReadAllText(keyFilePath)); + keys.Should().AllSatisfy(k => k.Should().Equal(onDisk)); + Directory.GetFiles(directory).Should().ContainSingle("no racer's temporary file is left behind"); + } + + [Test] + public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillReadIt() + { + if (geteuid() != 0) + { + Assert.Ignore("Creating a key for another user needs root."); + } + + // Arrange + var user = "octo-key-" + Guid.NewGuid().ToString("N").Substring(0, 8); + CreateUser(user).Should().Be(0); + var instanceKeyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); + var keySource = new ConfigurationEncryptionKey(log, fileSystem, instanceKeyFilePath); + var previousUmask = umask(Convert.ToUInt32("027", 8)); + try + { + // Act + keySource.CreateIfMissing(); + var owner = uint.Parse(RunAndRead("id", $"-u {user}")); + UnixFile.SetOwnerIfRunningAsRoot(owner, keySource.KeyDirectory!); + UnixFile.SetOwnerIfRunningAsRoot(owner, instanceKeyFilePath); + + // Assert + Run("su", $"-s /bin/sh -c \"cat {instanceKeyFilePath}\" {user}").Should().Be(0, "the owner must be able to traverse the shared directories to its key"); + File.GetUnixFileMode(keySource.KeyDirectory!).Should().Be(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + finally + { + umask(previousUmask); + DeleteUser(user); + } + } + + // Alpine has BusyBox's adduser and deluser rather than useradd and userdel. + static bool IsAlpine => File.Exists("/etc/alpine-release"); + + static int CreateUser(string user) + => IsAlpine ? Run("adduser", $"-D -H {user}") : Run("useradd", $"--no-create-home {user}"); + + static int DeleteUser(string user) + => IsAlpine ? Run("deluser", user) : Run("userdel", user); + + static int Run(string fileName, string arguments) + { + using var process = Process.Start(fileName, arguments); + process.WaitForExit(); + return process.ExitCode; + } + + static string RunAndRead(string fileName, string arguments) + { + using var process = Process.Start(new ProcessStartInfo(fileName, arguments) { RedirectStandardOutput = true })!; + var output = process.StandardOutput.ReadToEnd().Trim(); + process.WaitForExit(); + return output; + } + + [DllImport("libc")] + static extern uint geteuid(); + + [DllImport("libc")] + static extern uint umask(uint mask); + } +} +#endif From 47a1bda45718426f8c56f3dbb1577a54e11768f2 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:26:09 +1100 Subject: [PATCH 042/124] Cover create-instance key failure with a single real-executable test --- .../NonRootCreateInstanceTests.cs | 70 +++++++++++++++++++ .../Commands/CreateInstanceCommandTests.cs | 62 ---------------- .../ApplicationInstanceManagerTests.cs | 41 ----------- 3 files changed, 70 insertions(+), 103 deletions(-) create mode 100644 source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs delete mode 100644 source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs delete mode 100644 source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerTests.cs diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs new file mode 100644 index 000000000..32a65cf1b --- /dev/null +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs @@ -0,0 +1,70 @@ +#if NET +using System; +using System.IO; +using System.Runtime.Versioning; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using CliWrap; +using CliWrap.Buffered; +using FluentAssertions; +using NUnit.Framework; +using Octopus.Tentacle.Core.Util; +using Octopus.Tentacle.Tests.Integration.Support; +using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; +using Octopus.Tentacle.Tests.Integration.Util; + +namespace Octopus.Tentacle.Tests.Integration.Configuration +{ + [LinuxTest] + [NonParallelizable] + [UnsupportedOSPlatform("windows")] + public class NonRootCreateInstanceTests + { + [Test] + [RequiresSudoOnLinux] + public async Task WhenANonRootUserCannotCreateTheKeyThenTheCommandInTheErrorFixesIt() + { + // Arrange + var user = new LinuxTestUserPrincipal("octo-key-test"); + var root = Directory.CreateTempSubdirectory().FullName; + File.SetUnixFileMode(root, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + var dataDirectory = Path.Combine(root, "data"); + Directory.CreateDirectory(dataDirectory); + var homeDirectory = Path.Combine(root, "home"); + var configurationFile = Path.Combine(root, "config", "tentacle.config"); + Directory.CreateDirectory(homeDirectory); + Directory.CreateDirectory(Path.GetDirectoryName(configurationFile)!); + await Sudo("chown", "-R", user.UserName, homeDirectory, Path.GetDirectoryName(configurationFile)!); + + Task CreateInstanceAsUser() + => Sudo("-u", user.UserName, "env", + $"{EnvironmentVariables.TentacleInstancesDataDirectory}={dataDirectory}", + $"{EnvironmentVariables.TentacleMachineConfigurationHomeDirectory}={homeDirectory}", + TentacleExeFinder.FindTentacleExe(), "create-instance", "--instance", "Tentacle", "--config", configurationFile); + + try + { + // Act + var refused = await CreateInstanceAsUser(); + var fix = Regex.Match(refused.StandardOutput + refused.StandardError, "sudo mkdir[^`]*").Value; + await Cli.Wrap("/bin/bash").WithArguments(new[] { "-c", fix }).ExecuteBufferedAsync(); + var created = await CreateInstanceAsUser(); + + // Assert + refused.ExitCode.Should().NotBe(0); + fix.Should().NotBeEmpty($"the error should say which command fixes it, but it was: {refused.StandardOutput}{refused.StandardError}"); + created.ExitCode.Should().Be(0, $"running `{fix}` should let the user create the instance, but: {created.StandardOutput}{created.StandardError}"); + File.Exists(configurationFile).Should().BeTrue(); + } + finally + { + Directory.Delete(root, recursive: true); + await Sudo("userdel", "-r", user.UserName); + } + } + + static Task Sudo(params string[] arguments) + => Cli.Wrap("sudo").WithArguments(arguments).WithValidation(CommandResultValidation.None).ExecuteBufferedAsync(); + } +} +#endif diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs deleted file mode 100644 index 918fa61e7..000000000 --- a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#if NET -using System; -using System.IO; -using FluentAssertions; -using NSubstitute; -using NUnit.Framework; -using Octopus.Tentacle.Commands; -using Octopus.Tentacle.Configuration; -using Octopus.Tentacle.Configuration.Instances; -using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Core.Util; -using Octopus.Tentacle.Internals.Options; -using Octopus.Tentacle.Kubernetes.Configuration; -using Octopus.Tentacle.Tests.Support; -using Octopus.Tentacle.Startup; -using Octopus.Tentacle.Tests.Support.TestAttributes; -using Octopus.Tentacle.Tests.Util; -using Octopus.Tentacle.Util; - -namespace Octopus.Tentacle.Tests.Commands -{ - [LinuxOrMacTest] - [NonParallelizable] - public class CreateInstanceCommandTests - { - [Test] - public void WhenTheConfigurationEncryptionKeyCannotBeCreatedThenNoInstanceIsCreated() - { - // Arrange - var directory = Path.Combine(Path.GetTempPath(), "octopus-create-instance-" + Guid.NewGuid()); - Directory.CreateDirectory(directory); - var blockingFile = Path.Combine(directory, "not-a-directory"); - File.WriteAllText(blockingFile, ""); - using var dataDirectory = new TemporaryEnvironmentVariable(EnvironmentVariables.TentacleInstancesDataDirectory, blockingFile); - using var homeDirectory = new TemporaryEnvironmentVariable(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, directory); - var configurationFile = Path.Combine(directory, "Tentacle", "tentacle.config"); - var log = new InMemoryLog(); - var fileSystem = new OctopusPhysicalFileSystem(log); - var request = new StartUpRegistryInstanceRequest("Tentacle"); - var instanceStore = new ApplicationInstanceStore(ApplicationName.Tentacle, log, fileSystem, Substitute.For()); - var selector = new ApplicationInstanceSelector(ApplicationName.Tentacle, instanceStore, request, Array.Empty(), new Lazy(() => throw new NotSupportedException()), fileSystem, log); - var manager = new ApplicationInstanceManager(ApplicationName.Tentacle, request, fileSystem, log, instanceStore, new Lazy(() => throw new NotSupportedException())); - var command = new CreateInstanceCommand(manager, Substitute.For(), new Lazy(() => new TentacleConfigurationUpgrade(selector, fileSystem, log))); - - try - { - // Act - Action create = () => command.Start(new[] { "--instance=Tentacle", $"--config={configurationFile}" }, Substitute.For(), new OptionSet()); - - // Assert - create.Should().Throw().WithMessage("*so the instance was not created*"); - File.Exists(configurationFile).Should().BeFalse(); - instanceStore.ListInstances().Should().BeEmpty(); - } - finally - { - Directory.Delete(directory, recursive: true); - } - } - } -} -#endif diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerTests.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerTests.cs deleted file mode 100644 index 2a13331d1..000000000 --- a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceManagerTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using FluentAssertions; -using NSubstitute; -using NUnit.Framework; -using Octopus.Tentacle.Configuration; -using Octopus.Tentacle.Configuration.Instances; -using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Tests.Support.TestAttributes; -using Octopus.Tentacle.Util; - -namespace Octopus.Tentacle.Tests.Configuration -{ - [LinuxTest] - public class ApplicationInstanceManagerTests - { - [Test] - public void WhenTheConfigurationEncryptionKeyCannotBeCreatedThenNoInstanceIsCreated() - { - // Arrange - var fileSystem = Substitute.For(); - fileSystem.When(f => f.EnsureDirectoryExists(Arg.Is(d => d.EndsWith("/keys/Tentacle")))) - .Do(_ => throw new UnauthorizedAccessException("Permission denied")); - var instanceStore = Substitute.For(); - var manager = new ApplicationInstanceManager( - ApplicationName.Tentacle, - new StartUpRegistryInstanceRequest("Tentacle"), - fileSystem, - Substitute.For(), - instanceStore, - new Lazy(() => Substitute.For())); - - // Act - Action create = () => manager.CreateInstance("Tentacle", "/etc/octopus/Tentacle/tentacle.config", "/etc/octopus/Tentacle"); - - // Assert - create.Should().Throw().WithMessage("*Permission denied*"); - fileSystem.DidNotReceive().EnsureDirectoryExists("/etc/octopus/Tentacle"); - instanceStore.DidNotReceiveWithAnyArgs().RegisterInstance(default!); - } - } -} From c2361690f206b3fc2e31570cd748dd5ecf5e5fee Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:27:14 +1100 Subject: [PATCH 043/124] Delete test we don't need --- .../Commands/RunAgentCommandFixture.cs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs index 0dbe2a71b..40ec49814 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs @@ -68,20 +68,6 @@ public override void SetUp() selector.Current.Returns(new ApplicationInstanceConfiguration("MyTentacle", null, null, null)); } - [Test] - public void WhenCommandIsStartedThenTheConfigurationIsUpgradedBeforeHalibutStarts() - { - // Act - Start(); - - // Assert - Received.InOrder(() => - { - configurationUpgrade.TryUpgrade(); - halibut.Start(); - }); - } - [Test] public void WhenCommandIsStartedThenBackgroundServicesAreStarted() { From cf0bef7bfc8fee3c9bd23daaf2b56b14e41116e9 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:28:26 +1100 Subject: [PATCH 044/124] Test --config key selection through the installed package instead of a mocked selector --- .../test-scripts/test-linux-package.sh | 4 ++++ .../ApplicationInstanceSelectorFixture.cs | 19 ------------------- 2 files changed, 4 insertions(+), 19 deletions(-) diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh index c5c72bdd5..0d365107b 100644 --- a/linux-packages/test-scripts/test-linux-package.sh +++ b/linux-packages/test-scripts/test-linux-package.sh @@ -98,6 +98,10 @@ if [[ -z "$THUMBPRINT" ]] || ! grep -qF "key=\"Tentacle.CertificateThumbprint\"> exit 1 fi echo "The certificate decrypts in a new process and matches the recorded thumbprint." + +# Selecting the instance by --config must still find the registered instance's key. +[[ "$(Tentacle show-thumbprint --config "$CONFIGURATION_FILE")" == "$THUMBPRINT" ]] || { echo "'Tentacle show-thumbprint --config' did not decrypt with the registered instance's key."; exit 1; } +echo "Selecting the instance by its configuration file uses that instance's key." echo "" echo "All tests passed." diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs index 492df010a..4ce170ef8 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs @@ -92,25 +92,6 @@ public void GivenConfigurationInstanceExists_WhenRequestingConfigurationInstance mock.Current.ConfigurationPath.Should().Be(filePath); } - [Test] - public void GivenARegisteredInstanceUsesTheConfiguration_WhenRequestingConfigurationInstance_ThenItUsesThatInstancesKey() - { - if (PlatformDetection.IsRunningOnWindows) - Assert.Ignore("Configuration encryption keys are Linux only"); - - var filePath = "/etc/octopus/tentacle.config"; - var mock = CreateApplicationInstanceSelector(new StartUpConfigFileInstanceRequest(filePath)); - octopusFileSystem.FileExists(filePath).Returns(true); - octopusFileSystem.GetFullPath(Arg.Any()).Returns(c => c.Arg()); - applicationInstanceStore.ListInstances().Returns(new[] - { - new ApplicationInstanceRecord("Other", "/etc/octopus/other.config"), - new ApplicationInstanceRecord("Registered", filePath) - }); - - mock.Current.KeyFilePath.Should().Be(ConfigurationEncryptionKey.KeyFilePathFor("Registered")); - } - [Test] public void GivenConfigurationInstanceDoesNotExists_WhenRequestingConfigurationInstance_ThenThrows() { From 5e39b51926d1ab9ae27544b012e734165cdbd794 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:30:29 +1100 Subject: [PATCH 045/124] Remove test-linux-package.sh --- .../test-scripts/test-linux-package.sh | 108 ------------------ 1 file changed, 108 deletions(-) delete mode 100644 linux-packages/test-scripts/test-linux-package.sh diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh deleted file mode 100644 index 0d365107b..000000000 --- a/linux-packages/test-scripts/test-linux-package.sh +++ /dev/null @@ -1,108 +0,0 @@ -#!/bin/bash -set -eux - -# Test that the tentacle*.deb or tentacle*.rpm package installs a Tentacle command that runs successfully. - -PACKAGE_FILENAME="$1" -SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}") - -stat "$PACKAGE_FILENAME" -. $SCRIPT_DIR/install-package.sh "$PACKAGE_FILENAME" - -# Confirm that Tentacle is on the path -# We don't use `which Tentacle` here as, although Tentacle should have been installed, we can't trust that `which` exists. -Tentacle --version -echo "Tentacle binary lives in the path." -echo "" - -# Confirm that the version reported by Tentacle is the expected one. -# -# Neither side can be compared raw, because the two are stamped from different -# OctoVersion fields: -# -# a. Tentacle prints its AssemblyInformationalVersion (see VersionCommand.cs), -# which build/Build.cs stamps from OctoVersionInfo.InformationalVersion, -# i.e. '+Branch..Sha.'. BUILD_NUMBER is the bare -# FullSemVer, so the '+...' build metadata has to come off the reported -# version before the two can match. This applies to CI builds too, not -# just local ones. -# -# b. A local NUKE build additionally appends '-' to FullSemVer -# (build/Build.cs), and that timestamp is never stamped into the binary. On -# TeamCity there is no such suffix and stripping it is a no-op, so this -# makes the target runnable locally without weakening what CI asserts. -# -# testing/docker-linux/build-and-test-linux-docker-image.sh normalises the same -# two things for the same reasons - keep the two in step. -# -# The timestamp is stripped with a bash regex rather than sed, for the same -# reason `which` is avoided above: this runs on distributions as old as Ubuntu -# 16.04, and the fewer tools it assumes, the better. -TENTACLE_VERSION=$(Tentacle --version) -echo "Tentacle is reporting version $TENTACLE_VERSION." - -REPORTED_VERSION="${TENTACLE_VERSION%%+*}" - -if [[ "$BUILD_NUMBER" =~ ^(.*)-[0-9]{14}$ ]]; then - EXPECTED_VERSION="${BASH_REMATCH[1]}" -else - EXPECTED_VERSION="$BUILD_NUMBER" -fi - -if [[ "$REPORTED_VERSION" != "$EXPECTED_VERSION" ]]; then - echo "Tentacle version was $REPORTED_VERSION but expected version was $EXPECTED_VERSION." - exit 1 -fi -echo "The installed Tentacle version matches the expected one." -echo "" - -# A new certificate must be encrypted with the instance's generated key, not one derived from /etc/machine-id. -INSTANCE_NAME="package-test" -CONFIGURATION_FILE="/etc/octopus/$INSTANCE_NAME/tentacle.config" -MACHINE_KEY_FILE="/var/lib/octopus/tentacle/$INSTANCE_NAME/keys/config-encryption.key" - -mkdir -p "$(dirname "$CONFIGURATION_FILE")" -Tentacle create-instance --instance "$INSTANCE_NAME" --config "$CONFIGURATION_FILE" -Tentacle new-certificate --instance "$INSTANCE_NAME" - -if ! grep -qF 'key="Tentacle.Certificate">AESGCM-V1$' "$CONFIGURATION_FILE"; then - echo "The Tentacle certificate in $CONFIGURATION_FILE was not encrypted with the versioned machine key scheme." - exit 1 -fi -echo "The Tentacle certificate is encrypted with the key generated for this machine." - -MACHINE_KEY_MODE=$(stat -c %a "$MACHINE_KEY_FILE") -if [[ "$MACHINE_KEY_MODE" != "600" ]]; then - echo "$MACHINE_KEY_FILE has permissions $MACHINE_KEY_MODE but only its owner should be able to read or write it (600)." - exit 1 -fi -echo "The machine key file can only be read by its owner." - -# A numeric uid stands in for the service user, as minimal images may not have useradd. -SERVICE_USER_ID=4321 -chown "$SERVICE_USER_ID" "$CONFIGURATION_FILE" -Tentacle upgrade-configuration-encryption --instance "$INSTANCE_NAME" - -for KEY_PATH in "$MACHINE_KEY_FILE" "$(dirname "$MACHINE_KEY_FILE")"; do - KEY_PATH_OWNER=$(stat -c %u "$KEY_PATH") - if [[ "$KEY_PATH_OWNER" != "$SERVICE_USER_ID" ]]; then - echo "$KEY_PATH is owned by uid $KEY_PATH_OWNER but the configuration is owned by uid $SERVICE_USER_ID, so the service could not read its key." - exit 1 - fi -done -echo "The machine key was given to the owner of the configuration." - -THUMBPRINT=$(Tentacle show-thumbprint --instance "$INSTANCE_NAME") -if [[ -z "$THUMBPRINT" ]] || ! grep -qF "key=\"Tentacle.CertificateThumbprint\">$THUMBPRINT<" "$CONFIGURATION_FILE"; then - echo "'Tentacle show-thumbprint' reported '$THUMBPRINT', which is not the thumbprint recorded in $CONFIGURATION_FILE." - exit 1 -fi -echo "The certificate decrypts in a new process and matches the recorded thumbprint." - -# Selecting the instance by --config must still find the registered instance's key. -[[ "$(Tentacle show-thumbprint --config "$CONFIGURATION_FILE")" == "$THUMBPRINT" ]] || { echo "'Tentacle show-thumbprint --config' did not decrypt with the registered instance's key."; exit 1; } -echo "Selecting the instance by its configuration file uses that instance's key." -echo "" - -echo "All tests passed." -echo "" From f238cdbf52440b37a1fde152d862b34527695a9b Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:31:49 +1100 Subject: [PATCH 046/124] Restore registered-instance key selection test --- .../ApplicationInstanceSelectorFixture.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs index 4ce170ef8..492df010a 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs @@ -92,6 +92,25 @@ public void GivenConfigurationInstanceExists_WhenRequestingConfigurationInstance mock.Current.ConfigurationPath.Should().Be(filePath); } + [Test] + public void GivenARegisteredInstanceUsesTheConfiguration_WhenRequestingConfigurationInstance_ThenItUsesThatInstancesKey() + { + if (PlatformDetection.IsRunningOnWindows) + Assert.Ignore("Configuration encryption keys are Linux only"); + + var filePath = "/etc/octopus/tentacle.config"; + var mock = CreateApplicationInstanceSelector(new StartUpConfigFileInstanceRequest(filePath)); + octopusFileSystem.FileExists(filePath).Returns(true); + octopusFileSystem.GetFullPath(Arg.Any()).Returns(c => c.Arg()); + applicationInstanceStore.ListInstances().Returns(new[] + { + new ApplicationInstanceRecord("Other", "/etc/octopus/other.config"), + new ApplicationInstanceRecord("Registered", filePath) + }); + + mock.Current.KeyFilePath.Should().Be(ConfigurationEncryptionKey.KeyFilePathFor("Registered")); + } + [Test] public void GivenConfigurationInstanceDoesNotExists_WhenRequestingConfigurationInstance_ThenThrows() { From a314dc20960a8a19c5787b4a2920d76d308bd618 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:40:00 +1100 Subject: [PATCH 047/124] Revert "Remove test-linux-package.sh" This reverts commit 5e39b51926d1ab9ae27544b012e734165cdbd794. --- .../test-scripts/test-linux-package.sh | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 linux-packages/test-scripts/test-linux-package.sh diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh new file mode 100644 index 000000000..0d365107b --- /dev/null +++ b/linux-packages/test-scripts/test-linux-package.sh @@ -0,0 +1,108 @@ +#!/bin/bash +set -eux + +# Test that the tentacle*.deb or tentacle*.rpm package installs a Tentacle command that runs successfully. + +PACKAGE_FILENAME="$1" +SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}") + +stat "$PACKAGE_FILENAME" +. $SCRIPT_DIR/install-package.sh "$PACKAGE_FILENAME" + +# Confirm that Tentacle is on the path +# We don't use `which Tentacle` here as, although Tentacle should have been installed, we can't trust that `which` exists. +Tentacle --version +echo "Tentacle binary lives in the path." +echo "" + +# Confirm that the version reported by Tentacle is the expected one. +# +# Neither side can be compared raw, because the two are stamped from different +# OctoVersion fields: +# +# a. Tentacle prints its AssemblyInformationalVersion (see VersionCommand.cs), +# which build/Build.cs stamps from OctoVersionInfo.InformationalVersion, +# i.e. '+Branch..Sha.'. BUILD_NUMBER is the bare +# FullSemVer, so the '+...' build metadata has to come off the reported +# version before the two can match. This applies to CI builds too, not +# just local ones. +# +# b. A local NUKE build additionally appends '-' to FullSemVer +# (build/Build.cs), and that timestamp is never stamped into the binary. On +# TeamCity there is no such suffix and stripping it is a no-op, so this +# makes the target runnable locally without weakening what CI asserts. +# +# testing/docker-linux/build-and-test-linux-docker-image.sh normalises the same +# two things for the same reasons - keep the two in step. +# +# The timestamp is stripped with a bash regex rather than sed, for the same +# reason `which` is avoided above: this runs on distributions as old as Ubuntu +# 16.04, and the fewer tools it assumes, the better. +TENTACLE_VERSION=$(Tentacle --version) +echo "Tentacle is reporting version $TENTACLE_VERSION." + +REPORTED_VERSION="${TENTACLE_VERSION%%+*}" + +if [[ "$BUILD_NUMBER" =~ ^(.*)-[0-9]{14}$ ]]; then + EXPECTED_VERSION="${BASH_REMATCH[1]}" +else + EXPECTED_VERSION="$BUILD_NUMBER" +fi + +if [[ "$REPORTED_VERSION" != "$EXPECTED_VERSION" ]]; then + echo "Tentacle version was $REPORTED_VERSION but expected version was $EXPECTED_VERSION." + exit 1 +fi +echo "The installed Tentacle version matches the expected one." +echo "" + +# A new certificate must be encrypted with the instance's generated key, not one derived from /etc/machine-id. +INSTANCE_NAME="package-test" +CONFIGURATION_FILE="/etc/octopus/$INSTANCE_NAME/tentacle.config" +MACHINE_KEY_FILE="/var/lib/octopus/tentacle/$INSTANCE_NAME/keys/config-encryption.key" + +mkdir -p "$(dirname "$CONFIGURATION_FILE")" +Tentacle create-instance --instance "$INSTANCE_NAME" --config "$CONFIGURATION_FILE" +Tentacle new-certificate --instance "$INSTANCE_NAME" + +if ! grep -qF 'key="Tentacle.Certificate">AESGCM-V1$' "$CONFIGURATION_FILE"; then + echo "The Tentacle certificate in $CONFIGURATION_FILE was not encrypted with the versioned machine key scheme." + exit 1 +fi +echo "The Tentacle certificate is encrypted with the key generated for this machine." + +MACHINE_KEY_MODE=$(stat -c %a "$MACHINE_KEY_FILE") +if [[ "$MACHINE_KEY_MODE" != "600" ]]; then + echo "$MACHINE_KEY_FILE has permissions $MACHINE_KEY_MODE but only its owner should be able to read or write it (600)." + exit 1 +fi +echo "The machine key file can only be read by its owner." + +# A numeric uid stands in for the service user, as minimal images may not have useradd. +SERVICE_USER_ID=4321 +chown "$SERVICE_USER_ID" "$CONFIGURATION_FILE" +Tentacle upgrade-configuration-encryption --instance "$INSTANCE_NAME" + +for KEY_PATH in "$MACHINE_KEY_FILE" "$(dirname "$MACHINE_KEY_FILE")"; do + KEY_PATH_OWNER=$(stat -c %u "$KEY_PATH") + if [[ "$KEY_PATH_OWNER" != "$SERVICE_USER_ID" ]]; then + echo "$KEY_PATH is owned by uid $KEY_PATH_OWNER but the configuration is owned by uid $SERVICE_USER_ID, so the service could not read its key." + exit 1 + fi +done +echo "The machine key was given to the owner of the configuration." + +THUMBPRINT=$(Tentacle show-thumbprint --instance "$INSTANCE_NAME") +if [[ -z "$THUMBPRINT" ]] || ! grep -qF "key=\"Tentacle.CertificateThumbprint\">$THUMBPRINT<" "$CONFIGURATION_FILE"; then + echo "'Tentacle show-thumbprint' reported '$THUMBPRINT', which is not the thumbprint recorded in $CONFIGURATION_FILE." + exit 1 +fi +echo "The certificate decrypts in a new process and matches the recorded thumbprint." + +# Selecting the instance by --config must still find the registered instance's key. +[[ "$(Tentacle show-thumbprint --config "$CONFIGURATION_FILE")" == "$THUMBPRINT" ]] || { echo "'Tentacle show-thumbprint --config' did not decrypt with the registered instance's key."; exit 1; } +echo "Selecting the instance by its configuration file uses that instance's key." +echo "" + +echo "All tests passed." +echo "" From 72c862dc704f7de2750037bb5879295cf266c534 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 14:49:11 +1100 Subject: [PATCH 048/124] Remove test asserting unregistered configurations stay on legacy keys --- .../TentacleConfigurationUpgradeTests.cs | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs index ef1a53bb3..725e5a5d8 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs @@ -65,25 +65,6 @@ public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() sandbox.RawCertificate().Should().Be(legacyValue); } - [Test] - public void WhenTheConfigurationIsNotInTheRegistryThenNoKeyIsCreatedAndValuesStayLegacy() - { - // Arrange - using var sandbox = new ConfigurationSandbox(); - var keyFilePath = sandbox.DefaultKeyFilePath; - var store = sandbox.CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - var legacyValue = sandbox.RawCertificate(); - - // Act - sandbox.CreateUpgrade(store, keyFilePath: null, instanceName: null).Upgrade(); - - // Assert - File.Exists(keyFilePath).Should().BeFalse(); - sandbox.RawCertificate().Should().Be(legacyValue); - sandbox.Log.Received(1).Warn(Arg.Any()); - } - [Test] public void UpgradeConfigurationEncryptionCreatesTheKeyAndReEncryptsLegacyValues() { From 77a2c4e0a2b03776fa6b3ef2c1628a59260dff53 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 15:39:31 +1100 Subject: [PATCH 049/124] Remove in-process upgrade tests now covered by old-to-new Tentacle tests --- .../TentacleConfigurationUpgradeTests.cs | 56 ------------------- 1 file changed, 56 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs index 725e5a5d8..460b5dca4 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs @@ -27,62 +27,6 @@ public class TentacleConfigurationUpgradeTests { const string Certificate = "MIIC...the certificate..."; - [Test] - public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted() - { - // Arrange - using var sandbox = new ConfigurationSandbox(); - var keyFilePath = sandbox.DefaultKeyFilePath; - var store = sandbox.CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - sandbox.RawCertificate().Should().NotStartWith(LinuxMachineKeyEncryptor.Specifier + "$", "without a key, values are written the way earlier versions wrote them"); - - // Act - sandbox.CreateUpgrade(store, keyFilePath).Upgrade(); - - // Assert - File.Exists(keyFilePath).Should().BeTrue(); - sandbox.RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); - sandbox.CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); - sandbox.Log.DidNotReceive().Warn(Arg.Any(), Arg.Any()); - } - - [Test] - public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() - { - // Arrange - using var sandbox = new ConfigurationSandbox(); - var keyFilePath = Path.Combine(sandbox.ConfigurationFile, "not-a-directory", ConfigurationEncryptionKey.KeyFileName); - var store = sandbox.CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - var legacyValue = sandbox.RawCertificate(); - - // Act - Action run = () => sandbox.CreateUpgrade(store, keyFilePath).Upgrade(); - - // Assert - run.Should().Throw(); - sandbox.RawCertificate().Should().Be(legacyValue); - } - - [Test] - public void UpgradeConfigurationEncryptionCreatesTheKeyAndReEncryptsLegacyValues() - { - // Arrange - using var sandbox = new ConfigurationSandbox(); - var keyFilePath = sandbox.DefaultKeyFilePath; - var store = sandbox.CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - - // Act - sandbox.StartUpgradeCommand(store, keyFilePath); - - // Assert - File.Exists(keyFilePath).Should().BeTrue(); - sandbox.RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); - sandbox.CreateStore(keyFilePath).Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate); - } - [Test] public void UpgradeConfigurationEncryptionFailsForAConfigurationNotInTheRegistry() { From 4b62340ca3dc7554aa09e54d0d8ba156a2a5d853 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 15:48:07 +1100 Subject: [PATCH 050/124] Test upgrading a version 14 configuration from the machine-id key to its own key --- .../ConfigurationEncryptionUpgradeTests.cs | 100 ++++++++++++++++++ .../Support/TentacleVersions.cs | 4 + 2 files changed, 104 insertions(+) create mode 100644 source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs new file mode 100644 index 000000000..35fc03bc4 --- /dev/null +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -0,0 +1,100 @@ +#if NET +using System; +using System.IO; +using System.Linq; +using System.Runtime.Versioning; +using System.Threading.Tasks; +using System.Xml.Linq; +using CliWrap; +using CliWrap.Buffered; +using FluentAssertions; +using NUnit.Framework; +using Octopus.Tentacle.CommonTestUtils; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Core.Util; +using Octopus.Tentacle.Tests.Integration.Support; +using Octopus.Tentacle.Tests.Integration.Support.TentacleFetchers; +using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; +using Octopus.Tentacle.Tests.Integration.Util; + +namespace Octopus.Tentacle.Tests.Integration.Configuration +{ + [LinuxTest] + [UnsupportedOSPlatform("windows")] + public class ConfigurationEncryptionUpgradeTests : IntegrationTest + { + const string InstanceName = "Tentacle"; + + [Test] + public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToItsOwnKey() + { + // Arrange + using var root = new TemporaryDirectory(); + var dataDirectory = Path.Combine(root.DirectoryPath, "data"); + var configurationFile = Path.Combine(root.DirectoryPath, "tentacle.config"); + var environment = Environment(root, dataDirectory); + var version14 = await Version14(); + await Run(version14, environment, "create-instance", "--instance", InstanceName, "--config", configurationFile); + await Run(version14, environment, "new-certificate", "--instance", InstanceName); + var thumbprint = (await Run(version14, environment, "show-thumbprint", "--instance", InstanceName)).StandardOutput.Trim(); + RawCertificate(configurationFile).Should().NotStartWith(LinuxMachineKeyEncryptor.Specifier + "$"); + + // Act + await Run(TentacleExeFinder.FindTentacleExe(), environment, "upgrade-configuration-encryption", "--instance", InstanceName); + + // Assert + RawCertificate(configurationFile).Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); + File.Exists(Path.Combine(dataDirectory, InstanceName, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); + var upgradedThumbprint = await Run(TentacleExeFinder.FindTentacleExe(), environment, "show-thumbprint", "--instance", InstanceName); + upgradedThumbprint.StandardOutput.Trim().Should().Be(thumbprint); + } + + [Test] + public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14ConfigurationStaysEncryptedWithTheMachineId() + { + // Arrange + using var root = new TemporaryDirectory(); + var dataDirectoryThatIsAFile = Path.Combine(root.DirectoryPath, "data"); + await File.WriteAllTextAsync(dataDirectoryThatIsAFile, "not a directory"); + var configurationFile = Path.Combine(root.DirectoryPath, "tentacle.config"); + var environment = Environment(root, dataDirectoryThatIsAFile); + var version14 = await Version14(); + await Run(version14, environment, "create-instance", "--instance", InstanceName, "--config", configurationFile); + await Run(version14, environment, "new-certificate", "--instance", InstanceName); + var version14Certificate = RawCertificate(configurationFile); + + // Act + var upgrade = await Run(TentacleExeFinder.FindTentacleExe(), environment, CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", InstanceName); + + // Assert + var output = upgrade.StandardOutput + upgrade.StandardError; + upgrade.ExitCode.Should().NotBe(0, output); + output.Should().Contain(dataDirectoryThatIsAFile); + RawCertificate(configurationFile).Should().Be(version14Certificate); + } + + Task Version14() + => TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption, DefaultTentacleRuntime.Value, Logger, CancellationToken); + + static (string Name, string Value)[] Environment(TemporaryDirectory root, string dataDirectory) + => new[] + { + (EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, Path.Combine(root.DirectoryPath, "home")), + (EnvironmentVariables.TentacleInstancesDataDirectory, dataDirectory) + }; + + static string RawCertificate(string configurationFile) + => XDocument.Load(configurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == "Tentacle.Certificate").Value; + + static Task Run(string tentacleExe, (string Name, string Value)[] environment, params string[] arguments) + => Run(tentacleExe, environment, CommandResultValidation.ZeroExitCode, arguments); + + static Task Run(string tentacleExe, (string Name, string Value)[] environment, CommandResultValidation validation, params string[] arguments) + => Cli.Wrap(tentacleExe) + .WithArguments(arguments) + .WithValidation(validation) + .WithEnvironmentVariables(environment.ToDictionary(x => x.Name, x => (string?)x.Value)) + .ExecuteBufferedAsync(); + } +} +#endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleVersions.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleVersions.cs index f1819b60d..9dd1c6b2f 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleVersions.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleVersions.cs @@ -29,6 +29,9 @@ public static class TentacleVersions // Contains ScriptServiceV1 and ScriptServiceV2 public static readonly Version v8_0_81_AsyncHalibutAndLastWithoutScriptServiceV3Alpha = new("8.0.81"); + // Last release before configuration encryption moved off the machine-id derived key + public static readonly Version v14_0_4849_LastWithMachineIdConfigurationEncryption = new("14.0.4849"); + // The version compiled from the current source public static readonly Version? Current = null; @@ -68,6 +71,7 @@ static Version[] GetAllTestedVersionsToDownload() versions.Add(v6_3_451_NoCapabilitiesService); versions.Add(v7_1_189_SyncHalibutAndScriptServiceV2); versions.Add(v8_0_81_AsyncHalibutAndLastWithoutScriptServiceV3Alpha); + versions.Add(v14_0_4849_LastWithMachineIdConfigurationEncryption); return versions.ToArray(); } From accc06fd1eb519044f6927fc1db0901360a0db47 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 15:49:38 +1100 Subject: [PATCH 051/124] Name the version 14 Tentacle helper for what it returns --- .../ConfigurationEncryptionUpgradeTests.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 35fc03bc4..dd9ea928c 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -33,10 +33,10 @@ public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToIt var dataDirectory = Path.Combine(root.DirectoryPath, "data"); var configurationFile = Path.Combine(root.DirectoryPath, "tentacle.config"); var environment = Environment(root, dataDirectory); - var version14 = await Version14(); - await Run(version14, environment, "create-instance", "--instance", InstanceName, "--config", configurationFile); - await Run(version14, environment, "new-certificate", "--instance", InstanceName); - var thumbprint = (await Run(version14, environment, "show-thumbprint", "--instance", InstanceName)).StandardOutput.Trim(); + var version14Tentacle = await GetVersion14Tentacle(); + await Run(version14Tentacle, environment, "create-instance", "--instance", InstanceName, "--config", configurationFile); + await Run(version14Tentacle, environment, "new-certificate", "--instance", InstanceName); + var thumbprint = (await Run(version14Tentacle, environment, "show-thumbprint", "--instance", InstanceName)).StandardOutput.Trim(); RawCertificate(configurationFile).Should().NotStartWith(LinuxMachineKeyEncryptor.Specifier + "$"); // Act @@ -58,9 +58,9 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co await File.WriteAllTextAsync(dataDirectoryThatIsAFile, "not a directory"); var configurationFile = Path.Combine(root.DirectoryPath, "tentacle.config"); var environment = Environment(root, dataDirectoryThatIsAFile); - var version14 = await Version14(); - await Run(version14, environment, "create-instance", "--instance", InstanceName, "--config", configurationFile); - await Run(version14, environment, "new-certificate", "--instance", InstanceName); + var version14Tentacle = await GetVersion14Tentacle(); + await Run(version14Tentacle, environment, "create-instance", "--instance", InstanceName, "--config", configurationFile); + await Run(version14Tentacle, environment, "new-certificate", "--instance", InstanceName); var version14Certificate = RawCertificate(configurationFile); // Act @@ -73,7 +73,7 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co RawCertificate(configurationFile).Should().Be(version14Certificate); } - Task Version14() + Task GetVersion14Tentacle() => TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption, DefaultTentacleRuntime.Value, Logger, CancellationToken); static (string Name, string Value)[] Environment(TemporaryDirectory root, string dataDirectory) From 42d657e5e1f666fe9f0c4099bd4dc4146ad5cce4 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 15:50:09 +1100 Subject: [PATCH 052/124] Name the certificate helper for the encrypted value it reads --- .../ConfigurationEncryptionUpgradeTests.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index dd9ea928c..5eda540e0 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -37,13 +37,13 @@ public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToIt await Run(version14Tentacle, environment, "create-instance", "--instance", InstanceName, "--config", configurationFile); await Run(version14Tentacle, environment, "new-certificate", "--instance", InstanceName); var thumbprint = (await Run(version14Tentacle, environment, "show-thumbprint", "--instance", InstanceName)).StandardOutput.Trim(); - RawCertificate(configurationFile).Should().NotStartWith(LinuxMachineKeyEncryptor.Specifier + "$"); + EncryptedCertificateIn(configurationFile).Should().NotStartWith(LinuxMachineKeyEncryptor.Specifier + "$"); // Act await Run(TentacleExeFinder.FindTentacleExe(), environment, "upgrade-configuration-encryption", "--instance", InstanceName); // Assert - RawCertificate(configurationFile).Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); + EncryptedCertificateIn(configurationFile).Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); File.Exists(Path.Combine(dataDirectory, InstanceName, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); var upgradedThumbprint = await Run(TentacleExeFinder.FindTentacleExe(), environment, "show-thumbprint", "--instance", InstanceName); upgradedThumbprint.StandardOutput.Trim().Should().Be(thumbprint); @@ -61,7 +61,7 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co var version14Tentacle = await GetVersion14Tentacle(); await Run(version14Tentacle, environment, "create-instance", "--instance", InstanceName, "--config", configurationFile); await Run(version14Tentacle, environment, "new-certificate", "--instance", InstanceName); - var version14Certificate = RawCertificate(configurationFile); + var encryptedByVersion14 = EncryptedCertificateIn(configurationFile); // Act var upgrade = await Run(TentacleExeFinder.FindTentacleExe(), environment, CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", InstanceName); @@ -70,7 +70,7 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co var output = upgrade.StandardOutput + upgrade.StandardError; upgrade.ExitCode.Should().NotBe(0, output); output.Should().Contain(dataDirectoryThatIsAFile); - RawCertificate(configurationFile).Should().Be(version14Certificate); + EncryptedCertificateIn(configurationFile).Should().Be(encryptedByVersion14); } Task GetVersion14Tentacle() @@ -83,7 +83,7 @@ Task GetVersion14Tentacle() (EnvironmentVariables.TentacleInstancesDataDirectory, dataDirectory) }; - static string RawCertificate(string configurationFile) + static string EncryptedCertificateIn(string configurationFile) => XDocument.Load(configurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == "Tentacle.Certificate").Value; static Task Run(string tentacleExe, (string Name, string Value)[] environment, params string[] arguments) From 8b1965a58d8aba88c5873afb5ee108b9d496eae9 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 15:50:24 +1100 Subject: [PATCH 053/124] Name the redirected Tentacle directories for what they are --- .../ConfigurationEncryptionUpgradeTests.cs | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 5eda540e0..4685be190 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -32,20 +32,20 @@ public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToIt using var root = new TemporaryDirectory(); var dataDirectory = Path.Combine(root.DirectoryPath, "data"); var configurationFile = Path.Combine(root.DirectoryPath, "tentacle.config"); - var environment = Environment(root, dataDirectory); + var tentacleDirectories = TentacleDirectoriesIn(root, dataDirectory); var version14Tentacle = await GetVersion14Tentacle(); - await Run(version14Tentacle, environment, "create-instance", "--instance", InstanceName, "--config", configurationFile); - await Run(version14Tentacle, environment, "new-certificate", "--instance", InstanceName); - var thumbprint = (await Run(version14Tentacle, environment, "show-thumbprint", "--instance", InstanceName)).StandardOutput.Trim(); + await Run(version14Tentacle, tentacleDirectories, "create-instance", "--instance", InstanceName, "--config", configurationFile); + await Run(version14Tentacle, tentacleDirectories, "new-certificate", "--instance", InstanceName); + var thumbprint = (await Run(version14Tentacle, tentacleDirectories, "show-thumbprint", "--instance", InstanceName)).StandardOutput.Trim(); EncryptedCertificateIn(configurationFile).Should().NotStartWith(LinuxMachineKeyEncryptor.Specifier + "$"); // Act - await Run(TentacleExeFinder.FindTentacleExe(), environment, "upgrade-configuration-encryption", "--instance", InstanceName); + await Run(TentacleExeFinder.FindTentacleExe(), tentacleDirectories, "upgrade-configuration-encryption", "--instance", InstanceName); // Assert EncryptedCertificateIn(configurationFile).Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); File.Exists(Path.Combine(dataDirectory, InstanceName, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); - var upgradedThumbprint = await Run(TentacleExeFinder.FindTentacleExe(), environment, "show-thumbprint", "--instance", InstanceName); + var upgradedThumbprint = await Run(TentacleExeFinder.FindTentacleExe(), tentacleDirectories, "show-thumbprint", "--instance", InstanceName); upgradedThumbprint.StandardOutput.Trim().Should().Be(thumbprint); } @@ -57,14 +57,14 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co var dataDirectoryThatIsAFile = Path.Combine(root.DirectoryPath, "data"); await File.WriteAllTextAsync(dataDirectoryThatIsAFile, "not a directory"); var configurationFile = Path.Combine(root.DirectoryPath, "tentacle.config"); - var environment = Environment(root, dataDirectoryThatIsAFile); + var tentacleDirectories = TentacleDirectoriesIn(root, dataDirectoryThatIsAFile); var version14Tentacle = await GetVersion14Tentacle(); - await Run(version14Tentacle, environment, "create-instance", "--instance", InstanceName, "--config", configurationFile); - await Run(version14Tentacle, environment, "new-certificate", "--instance", InstanceName); + await Run(version14Tentacle, tentacleDirectories, "create-instance", "--instance", InstanceName, "--config", configurationFile); + await Run(version14Tentacle, tentacleDirectories, "new-certificate", "--instance", InstanceName); var encryptedByVersion14 = EncryptedCertificateIn(configurationFile); // Act - var upgrade = await Run(TentacleExeFinder.FindTentacleExe(), environment, CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", InstanceName); + var upgrade = await Run(TentacleExeFinder.FindTentacleExe(), tentacleDirectories, CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", InstanceName); // Assert var output = upgrade.StandardOutput + upgrade.StandardError; @@ -76,7 +76,7 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co Task GetVersion14Tentacle() => TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption, DefaultTentacleRuntime.Value, Logger, CancellationToken); - static (string Name, string Value)[] Environment(TemporaryDirectory root, string dataDirectory) + static (string Name, string Value)[] TentacleDirectoriesIn(TemporaryDirectory root, string dataDirectory) => new[] { (EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, Path.Combine(root.DirectoryPath, "home")), @@ -86,14 +86,14 @@ Task GetVersion14Tentacle() static string EncryptedCertificateIn(string configurationFile) => XDocument.Load(configurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == "Tentacle.Certificate").Value; - static Task Run(string tentacleExe, (string Name, string Value)[] environment, params string[] arguments) - => Run(tentacleExe, environment, CommandResultValidation.ZeroExitCode, arguments); + static Task Run(string tentacleExe, (string Name, string Value)[] tentacleDirectories, params string[] arguments) + => Run(tentacleExe, tentacleDirectories, CommandResultValidation.ZeroExitCode, arguments); - static Task Run(string tentacleExe, (string Name, string Value)[] environment, CommandResultValidation validation, params string[] arguments) + static Task Run(string tentacleExe, (string Name, string Value)[] tentacleDirectories, CommandResultValidation validation, params string[] arguments) => Cli.Wrap(tentacleExe) .WithArguments(arguments) .WithValidation(validation) - .WithEnvironmentVariables(environment.ToDictionary(x => x.Name, x => (string?)x.Value)) + .WithEnvironmentVariables(tentacleDirectories.ToDictionary(x => x.Name, x => (string?)x.Value)) .ExecuteBufferedAsync(); } } From 518f25edcc168d3d5301309362a4b3b1381b41ac Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 15:51:18 +1100 Subject: [PATCH 054/124] Make the version 14 upgrade tests read as a story --- .../ConfigurationEncryptionUpgradeTests.cs | 113 ++++++++++-------- 1 file changed, 66 insertions(+), 47 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 4685be190..40a37ef5c 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -23,78 +23,97 @@ namespace Octopus.Tentacle.Tests.Integration.Configuration [UnsupportedOSPlatform("windows")] public class ConfigurationEncryptionUpgradeTests : IntegrationTest { - const string InstanceName = "Tentacle"; + static readonly string EncryptedWithItsOwnKey = LinuxMachineKeyEncryptor.Specifier + "$"; [Test] public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToItsOwnKey() { // Arrange - using var root = new TemporaryDirectory(); - var dataDirectory = Path.Combine(root.DirectoryPath, "data"); - var configurationFile = Path.Combine(root.DirectoryPath, "tentacle.config"); - var tentacleDirectories = TentacleDirectoriesIn(root, dataDirectory); - var version14Tentacle = await GetVersion14Tentacle(); - await Run(version14Tentacle, tentacleDirectories, "create-instance", "--instance", InstanceName, "--config", configurationFile); - await Run(version14Tentacle, tentacleDirectories, "new-certificate", "--instance", InstanceName); - var thumbprint = (await Run(version14Tentacle, tentacleDirectories, "show-thumbprint", "--instance", InstanceName)).StandardOutput.Trim(); - EncryptedCertificateIn(configurationFile).Should().NotStartWith(LinuxMachineKeyEncryptor.Specifier + "$"); + using var instance = new IsolatedTentacleInstance(); + var version14 = await GetVersion14Tentacle(); + await instance.CreateWithACertificate(version14); + var thumbprintBeforeUpgrade = await instance.Thumbprint(version14); + instance.EncryptedCertificate.Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); // Act - await Run(TentacleExeFinder.FindTentacleExe(), tentacleDirectories, "upgrade-configuration-encryption", "--instance", InstanceName); + await instance.UpgradeConfigurationEncryption(TentacleExeFinder.FindTentacleExe()); // Assert - EncryptedCertificateIn(configurationFile).Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); - File.Exists(Path.Combine(dataDirectory, InstanceName, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); - var upgradedThumbprint = await Run(TentacleExeFinder.FindTentacleExe(), tentacleDirectories, "show-thumbprint", "--instance", InstanceName); - upgradedThumbprint.StandardOutput.Trim().Should().Be(thumbprint); + instance.EncryptedCertificate.Should().StartWith(EncryptedWithItsOwnKey); + File.Exists(instance.KeyFile).Should().BeTrue(); + (await instance.Thumbprint(TentacleExeFinder.FindTentacleExe())).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); } [Test] public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14ConfigurationStaysEncryptedWithTheMachineId() { // Arrange - using var root = new TemporaryDirectory(); - var dataDirectoryThatIsAFile = Path.Combine(root.DirectoryPath, "data"); - await File.WriteAllTextAsync(dataDirectoryThatIsAFile, "not a directory"); - var configurationFile = Path.Combine(root.DirectoryPath, "tentacle.config"); - var tentacleDirectories = TentacleDirectoriesIn(root, dataDirectoryThatIsAFile); - var version14Tentacle = await GetVersion14Tentacle(); - await Run(version14Tentacle, tentacleDirectories, "create-instance", "--instance", InstanceName, "--config", configurationFile); - await Run(version14Tentacle, tentacleDirectories, "new-certificate", "--instance", InstanceName); - var encryptedByVersion14 = EncryptedCertificateIn(configurationFile); + using var instance = new IsolatedTentacleInstance(); + var version14 = await GetVersion14Tentacle(); + await instance.CreateWithACertificate(version14); + var certificateEncryptedByVersion14 = instance.EncryptedCertificate; + instance.PreventTheKeyDirectoryFromBeingCreated(); // Act - var upgrade = await Run(TentacleExeFinder.FindTentacleExe(), tentacleDirectories, CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", InstanceName); + var upgrade = await instance.TryUpgradeConfigurationEncryption(TentacleExeFinder.FindTentacleExe()); // Assert - var output = upgrade.StandardOutput + upgrade.StandardError; - upgrade.ExitCode.Should().NotBe(0, output); - output.Should().Contain(dataDirectoryThatIsAFile); - EncryptedCertificateIn(configurationFile).Should().Be(encryptedByVersion14); + upgrade.ExitCode.Should().NotBe(0, upgrade.Output); + upgrade.Output.Should().Contain(instance.DataDirectory, "the failure should be about creating the key, not something else"); + instance.EncryptedCertificate.Should().Be(certificateEncryptedByVersion14); } Task GetVersion14Tentacle() => TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption, DefaultTentacleRuntime.Value, Logger, CancellationToken); - static (string Name, string Value)[] TentacleDirectoriesIn(TemporaryDirectory root, string dataDirectory) - => new[] + // A Tentacle instance whose registry, configuration and key all live in a temporary directory, so it can be driven by any Tentacle version. + sealed class IsolatedTentacleInstance : IDisposable + { + const string Name = "Tentacle"; + readonly TemporaryDirectory root = new(); + + public string DataDirectory => Path.Combine(root.DirectoryPath, "data"); + public string KeyFile => Path.Combine(DataDirectory, Name, "keys", ConfigurationEncryptionKey.KeyFileName); + string ConfigurationFile => Path.Combine(root.DirectoryPath, "tentacle.config"); + + public string EncryptedCertificate + => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == "Tentacle.Certificate").Value; + + public async Task CreateWithACertificate(string tentacle) { - (EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, Path.Combine(root.DirectoryPath, "home")), - (EnvironmentVariables.TentacleInstancesDataDirectory, dataDirectory) - }; - - static string EncryptedCertificateIn(string configurationFile) - => XDocument.Load(configurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == "Tentacle.Certificate").Value; - - static Task Run(string tentacleExe, (string Name, string Value)[] tentacleDirectories, params string[] arguments) - => Run(tentacleExe, tentacleDirectories, CommandResultValidation.ZeroExitCode, arguments); - - static Task Run(string tentacleExe, (string Name, string Value)[] tentacleDirectories, CommandResultValidation validation, params string[] arguments) - => Cli.Wrap(tentacleExe) - .WithArguments(arguments) - .WithValidation(validation) - .WithEnvironmentVariables(tentacleDirectories.ToDictionary(x => x.Name, x => (string?)x.Value)) - .ExecuteBufferedAsync(); + await Run(tentacle, "create-instance", "--instance", Name, "--config", ConfigurationFile); + await Run(tentacle, "new-certificate", "--instance", Name); + } + + public async Task Thumbprint(string tentacle) + => (await Run(tentacle, "show-thumbprint", "--instance", Name)).StandardOutput.Trim(); + + public Task UpgradeConfigurationEncryption(string tentacle) + => Run(tentacle, "upgrade-configuration-encryption", "--instance", Name); + + public async Task<(int ExitCode, string Output)> TryUpgradeConfigurationEncryption(string tentacle) + { + var result = await Run(tentacle, CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", Name); + return (result.ExitCode, result.StandardOutput + result.StandardError); + } + + public void PreventTheKeyDirectoryFromBeingCreated() + => File.WriteAllText(DataDirectory, "a file where the data directory should be"); + + Task Run(string tentacle, params string[] arguments) + => Run(tentacle, CommandResultValidation.ZeroExitCode, arguments); + + Task Run(string tentacle, CommandResultValidation validation, params string[] arguments) + => Cli.Wrap(tentacle) + .WithArguments(arguments) + .WithValidation(validation) + .WithEnvironmentVariables(e => e + .Set(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, Path.Combine(root.DirectoryPath, "home")) + .Set(EnvironmentVariables.TentacleInstancesDataDirectory, DataDirectory)) + .ExecuteBufferedAsync(); + + public void Dispose() => root.Dispose(); + } } } #endif From 13f4e0702ed2595e05750b5832ef3d472a40e67d Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 15:56:06 +1100 Subject: [PATCH 055/124] Add a builder for a Tentacle instance that is not running, and use it in the upgrade tests --- .../ConfigurationEncryptionUpgradeTests.cs | 98 +++++-------------- .../Support/TentacleInstanceBuilder.cs | 87 ++++++++++++++++ 2 files changed, 112 insertions(+), 73 deletions(-) create mode 100644 source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 40a37ef5c..65e6487c7 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -5,15 +5,10 @@ using System.Runtime.Versioning; using System.Threading.Tasks; using System.Xml.Linq; -using CliWrap; -using CliWrap.Buffered; using FluentAssertions; using NUnit.Framework; -using Octopus.Tentacle.CommonTestUtils; using Octopus.Tentacle.Configuration.Crypto; -using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Tests.Integration.Support; -using Octopus.Tentacle.Tests.Integration.Support.TentacleFetchers; using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; using Octopus.Tentacle.Tests.Integration.Util; @@ -29,91 +24,48 @@ public class ConfigurationEncryptionUpgradeTests : IntegrationTest public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToItsOwnKey() { // Arrange - using var instance = new IsolatedTentacleInstance(); - var version14 = await GetVersion14Tentacle(); - await instance.CreateWithACertificate(version14); - var thumbprintBeforeUpgrade = await instance.Thumbprint(version14); - instance.EncryptedCertificate.Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); + using var instance = await new TentacleInstanceBuilder() + .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) + .WithNewCertificate() + .Build(Logger, CancellationToken); + var thumbprintBeforeUpgrade = await Thumbprint(instance, instance.TentacleExe); + EncryptedCertificateIn(instance).Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); // Act - await instance.UpgradeConfigurationEncryption(TentacleExeFinder.FindTentacleExe()); + await instance.RunWith(TentacleExeFinder.FindTentacleExe(), "upgrade-configuration-encryption", "--instance", instance.Name); // Assert - instance.EncryptedCertificate.Should().StartWith(EncryptedWithItsOwnKey); - File.Exists(instance.KeyFile).Should().BeTrue(); - (await instance.Thumbprint(TentacleExeFinder.FindTentacleExe())).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); + EncryptedCertificateIn(instance).Should().StartWith(EncryptedWithItsOwnKey); + File.Exists(Path.Combine(instance.DataDirectory, instance.Name, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); + (await Thumbprint(instance, TentacleExeFinder.FindTentacleExe())).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); } [Test] public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14ConfigurationStaysEncryptedWithTheMachineId() { // Arrange - using var instance = new IsolatedTentacleInstance(); - var version14 = await GetVersion14Tentacle(); - await instance.CreateWithACertificate(version14); - var certificateEncryptedByVersion14 = instance.EncryptedCertificate; - instance.PreventTheKeyDirectoryFromBeingCreated(); + using var instance = await new TentacleInstanceBuilder() + .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) + .WithNewCertificate() + .Build(Logger, CancellationToken); + var certificateEncryptedByVersion14 = EncryptedCertificateIn(instance); + await File.WriteAllTextAsync(instance.DataDirectory, "a file where the data directory should be, so the key directory cannot be created"); // Act - var upgrade = await instance.TryUpgradeConfigurationEncryption(TentacleExeFinder.FindTentacleExe()); + var upgrade = await instance.TryRunWith(TentacleExeFinder.FindTentacleExe(), "upgrade-configuration-encryption", "--instance", instance.Name); // Assert - upgrade.ExitCode.Should().NotBe(0, upgrade.Output); - upgrade.Output.Should().Contain(instance.DataDirectory, "the failure should be about creating the key, not something else"); - instance.EncryptedCertificate.Should().Be(certificateEncryptedByVersion14); + var output = upgrade.StandardOutput + upgrade.StandardError; + upgrade.ExitCode.Should().NotBe(0, output); + output.Should().Contain(instance.DataDirectory, "the failure should be about creating the key, not something else"); + EncryptedCertificateIn(instance).Should().Be(certificateEncryptedByVersion14); } - Task GetVersion14Tentacle() - => TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption, DefaultTentacleRuntime.Value, Logger, CancellationToken); + static async Task Thumbprint(TentacleInstance instance, string tentacleExe) + => (await instance.RunWith(tentacleExe, "show-thumbprint", "--instance", instance.Name)).StandardOutput.Trim(); - // A Tentacle instance whose registry, configuration and key all live in a temporary directory, so it can be driven by any Tentacle version. - sealed class IsolatedTentacleInstance : IDisposable - { - const string Name = "Tentacle"; - readonly TemporaryDirectory root = new(); - - public string DataDirectory => Path.Combine(root.DirectoryPath, "data"); - public string KeyFile => Path.Combine(DataDirectory, Name, "keys", ConfigurationEncryptionKey.KeyFileName); - string ConfigurationFile => Path.Combine(root.DirectoryPath, "tentacle.config"); - - public string EncryptedCertificate - => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == "Tentacle.Certificate").Value; - - public async Task CreateWithACertificate(string tentacle) - { - await Run(tentacle, "create-instance", "--instance", Name, "--config", ConfigurationFile); - await Run(tentacle, "new-certificate", "--instance", Name); - } - - public async Task Thumbprint(string tentacle) - => (await Run(tentacle, "show-thumbprint", "--instance", Name)).StandardOutput.Trim(); - - public Task UpgradeConfigurationEncryption(string tentacle) - => Run(tentacle, "upgrade-configuration-encryption", "--instance", Name); - - public async Task<(int ExitCode, string Output)> TryUpgradeConfigurationEncryption(string tentacle) - { - var result = await Run(tentacle, CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", Name); - return (result.ExitCode, result.StandardOutput + result.StandardError); - } - - public void PreventTheKeyDirectoryFromBeingCreated() - => File.WriteAllText(DataDirectory, "a file where the data directory should be"); - - Task Run(string tentacle, params string[] arguments) - => Run(tentacle, CommandResultValidation.ZeroExitCode, arguments); - - Task Run(string tentacle, CommandResultValidation validation, params string[] arguments) - => Cli.Wrap(tentacle) - .WithArguments(arguments) - .WithValidation(validation) - .WithEnvironmentVariables(e => e - .Set(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, Path.Combine(root.DirectoryPath, "home")) - .Set(EnvironmentVariables.TentacleInstancesDataDirectory, DataDirectory)) - .ExecuteBufferedAsync(); - - public void Dispose() => root.Dispose(); - } + static string EncryptedCertificateIn(TentacleInstance instance) + => XDocument.Load(instance.ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == "Tentacle.Certificate").Value; } } #endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs new file mode 100644 index 000000000..8a947e2ea --- /dev/null +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -0,0 +1,87 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using CliWrap; +using CliWrap.Buffered; +using Octopus.Tentacle.CommonTestUtils; +using Octopus.Tentacle.Core.Util; +using Octopus.Tentacle.Tests.Integration.Support.TentacleFetchers; +using Octopus.Tentacle.Tests.Integration.Util; +using Serilog; + +namespace Octopus.Tentacle.Tests.Integration.Support +{ + // Builds a Tentacle instance that is configured but not running, for tests that drive Tentacle through its commands. + public class TentacleInstanceBuilder + { + Version? tentacleVersion; + bool withNewCertificate; + + public TentacleInstanceBuilder WithTentacleVersion(Version tentacleVersion) + { + this.tentacleVersion = tentacleVersion; + return this; + } + + public TentacleInstanceBuilder WithNewCertificate() + { + withNewCertificate = true; + return this; + } + + public async Task Build(ILogger logger, CancellationToken cancellationToken) + { + var tentacleExe = tentacleVersion == null + ? TentacleExeFinder.FindTentacleExe() + : await TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken); + + var instance = new TentacleInstance(tentacleExe, cancellationToken); + await instance.Run("create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); + if (withNewCertificate) + { + await instance.Run("new-certificate", "--instance", instance.Name); + } + + return instance; + } + } + + // Everything the instance owns - its registry entry, configuration and data - lives in a temporary home directory. + public class TentacleInstance : IDisposable + { + readonly TemporaryDirectory home = new(); + readonly CancellationToken cancellationToken; + + internal TentacleInstance(string tentacleExe, CancellationToken cancellationToken) + { + TentacleExe = tentacleExe; + this.cancellationToken = cancellationToken; + } + + public string Name => "Tentacle"; + public string TentacleExe { get; } + public string ConfigurationFile => Path.Combine(home.DirectoryPath, "tentacle.config"); + public string DataDirectory => Path.Combine(home.DirectoryPath, "data"); + + public Task Run(params string[] arguments) + => RunWith(TentacleExe, CommandResultValidation.ZeroExitCode, arguments); + + public Task RunWith(string tentacleExe, params string[] arguments) + => RunWith(tentacleExe, CommandResultValidation.ZeroExitCode, arguments); + + public Task TryRunWith(string tentacleExe, params string[] arguments) + => RunWith(tentacleExe, CommandResultValidation.None, arguments); + + Task RunWith(string tentacleExe, CommandResultValidation validation, string[] arguments) + => Cli.Wrap(tentacleExe) + .WithArguments(arguments) + .WithValidation(validation) + .WithEnvironmentVariables(e => e + .Set(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, Path.Combine(home.DirectoryPath, "home")) + .Set(EnvironmentVariables.TentacleInstancesDataDirectory, DataDirectory)) + .ExecuteBufferedAsync(cancellationToken); + + public void Dispose() => home.Dispose(); + } +} From 9e489b9337ea9a9c26fb45c394b429b1b7938047 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 16:05:28 +1100 Subject: [PATCH 056/124] Read the stored certificate from the Tentacle instance --- .../ConfigurationEncryptionUpgradeTests.cs | 26 ++++++++----------- .../Support/TentacleInstanceBuilder.cs | 22 +++++++--------- 2 files changed, 20 insertions(+), 28 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 65e6487c7..d8f9913cd 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -1,10 +1,9 @@ #if NET using System; using System.IO; -using System.Linq; using System.Runtime.Versioning; using System.Threading.Tasks; -using System.Xml.Linq; +using CliWrap; using FluentAssertions; using NUnit.Framework; using Octopus.Tentacle.Configuration.Crypto; @@ -28,16 +27,16 @@ public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToIt .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) .WithNewCertificate() .Build(Logger, CancellationToken); - var thumbprintBeforeUpgrade = await Thumbprint(instance, instance.TentacleExe); - EncryptedCertificateIn(instance).Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); + var thumbprintBeforeUpgrade = await ExecuteShowThumbprintCommand(instance, instance.TentacleExe); + instance.CertificateAsStoredInTheConfigurationFile().Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); // Act - await instance.RunWith(TentacleExeFinder.FindTentacleExe(), "upgrade-configuration-encryption", "--instance", instance.Name); + await instance.ExecuteTentacleCommand(TentacleExeFinder.FindTentacleExe(), CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption", "--instance", instance.Name); // Assert - EncryptedCertificateIn(instance).Should().StartWith(EncryptedWithItsOwnKey); + instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); File.Exists(Path.Combine(instance.DataDirectory, instance.Name, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); - (await Thumbprint(instance, TentacleExeFinder.FindTentacleExe())).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); + (await ExecuteShowThumbprintCommand(instance, TentacleExeFinder.FindTentacleExe())).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); } [Test] @@ -48,24 +47,21 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) .WithNewCertificate() .Build(Logger, CancellationToken); - var certificateEncryptedByVersion14 = EncryptedCertificateIn(instance); + var certificateEncryptedByVersion14 = instance.CertificateAsStoredInTheConfigurationFile(); await File.WriteAllTextAsync(instance.DataDirectory, "a file where the data directory should be, so the key directory cannot be created"); // Act - var upgrade = await instance.TryRunWith(TentacleExeFinder.FindTentacleExe(), "upgrade-configuration-encryption", "--instance", instance.Name); + var upgrade = await instance.ExecuteTentacleCommand(TentacleExeFinder.FindTentacleExe(), CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", instance.Name); // Assert var output = upgrade.StandardOutput + upgrade.StandardError; upgrade.ExitCode.Should().NotBe(0, output); output.Should().Contain(instance.DataDirectory, "the failure should be about creating the key, not something else"); - EncryptedCertificateIn(instance).Should().Be(certificateEncryptedByVersion14); + instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedByVersion14); } - static async Task Thumbprint(TentacleInstance instance, string tentacleExe) - => (await instance.RunWith(tentacleExe, "show-thumbprint", "--instance", instance.Name)).StandardOutput.Trim(); - - static string EncryptedCertificateIn(TentacleInstance instance) - => XDocument.Load(instance.ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == "Tentacle.Certificate").Value; + static async Task ExecuteShowThumbprintCommand(TentacleInstance instance, string tentacleExe) + => (await instance.ExecuteTentacleCommand(tentacleExe, CommandResultValidation.ZeroExitCode, "show-thumbprint", "--instance", instance.Name)).StandardOutput.Trim(); } } #endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index 8a947e2ea..39599ce97 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -1,13 +1,15 @@ using System; using System.IO; +using System.Linq; +using System.Xml.Linq; using System.Threading; using System.Threading.Tasks; using CliWrap; using CliWrap.Buffered; using Octopus.Tentacle.CommonTestUtils; +using Octopus.Tentacle.Configuration; using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Tests.Integration.Support.TentacleFetchers; -using Octopus.Tentacle.Tests.Integration.Util; using Serilog; namespace Octopus.Tentacle.Tests.Integration.Support @@ -37,10 +39,10 @@ public async Task Build(ILogger logger, CancellationToken canc : await TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken); var instance = new TentacleInstance(tentacleExe, cancellationToken); - await instance.Run("create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); + await instance.ExecuteTentacleCommand(instance.TentacleExe, CommandResultValidation.ZeroExitCode, "create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); if (withNewCertificate) { - await instance.Run("new-certificate", "--instance", instance.Name); + await instance.ExecuteTentacleCommand(instance.TentacleExe, CommandResultValidation.ZeroExitCode, "new-certificate", "--instance", instance.Name); } return instance; @@ -64,17 +66,11 @@ internal TentacleInstance(string tentacleExe, CancellationToken cancellationToke public string ConfigurationFile => Path.Combine(home.DirectoryPath, "tentacle.config"); public string DataDirectory => Path.Combine(home.DirectoryPath, "data"); - public Task Run(params string[] arguments) - => RunWith(TentacleExe, CommandResultValidation.ZeroExitCode, arguments); + public string CertificateAsStoredInTheConfigurationFile() + => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; - public Task RunWith(string tentacleExe, params string[] arguments) - => RunWith(tentacleExe, CommandResultValidation.ZeroExitCode, arguments); - - public Task TryRunWith(string tentacleExe, params string[] arguments) - => RunWith(tentacleExe, CommandResultValidation.None, arguments); - - Task RunWith(string tentacleExe, CommandResultValidation validation, string[] arguments) - => Cli.Wrap(tentacleExe) + public async Task ExecuteTentacleCommand(string tentacleExe, CommandResultValidation validation, params string[] arguments) + => await Cli.Wrap(tentacleExe) .WithArguments(arguments) .WithValidation(validation) .WithEnvironmentVariables(e => e From 31980e6d0df0a53090356221e5cf01393fe99586 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 16:07:35 +1100 Subject: [PATCH 057/124] Let a Tentacle instance own its Tentacle version and switch to the latest --- .../ConfigurationEncryptionUpgradeTests.cs | 14 ++++---- .../Support/TentacleInstanceBuilder.cs | 33 +++++++++++-------- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index d8f9913cd..922a90f4a 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -9,7 +9,6 @@ using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Tests.Integration.Support; using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; -using Octopus.Tentacle.Tests.Integration.Util; namespace Octopus.Tentacle.Tests.Integration.Configuration { @@ -27,16 +26,17 @@ public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToIt .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) .WithNewCertificate() .Build(Logger, CancellationToken); - var thumbprintBeforeUpgrade = await ExecuteShowThumbprintCommand(instance, instance.TentacleExe); + var thumbprintBeforeUpgrade = await instance.ShowThumbprint(); instance.CertificateAsStoredInTheConfigurationFile().Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); // Act - await instance.ExecuteTentacleCommand(TentacleExeFinder.FindTentacleExe(), CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption", "--instance", instance.Name); + await instance.ChangeTentacleVersion(TentacleVersions.Current); + await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption", "--instance", instance.Name); // Assert instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); File.Exists(Path.Combine(instance.DataDirectory, instance.Name, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); - (await ExecuteShowThumbprintCommand(instance, TentacleExeFinder.FindTentacleExe())).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); + (await instance.ShowThumbprint()).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); } [Test] @@ -51,7 +51,8 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co await File.WriteAllTextAsync(instance.DataDirectory, "a file where the data directory should be, so the key directory cannot be created"); // Act - var upgrade = await instance.ExecuteTentacleCommand(TentacleExeFinder.FindTentacleExe(), CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", instance.Name); + await instance.ChangeTentacleVersion(TentacleVersions.Current); + var upgrade = await instance.ExecuteTentacleCommand(CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", instance.Name); // Assert var output = upgrade.StandardOutput + upgrade.StandardError; @@ -59,9 +60,6 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co output.Should().Contain(instance.DataDirectory, "the failure should be about creating the key, not something else"); instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedByVersion14); } - - static async Task ExecuteShowThumbprintCommand(TentacleInstance instance, string tentacleExe) - => (await instance.ExecuteTentacleCommand(tentacleExe, CommandResultValidation.ZeroExitCode, "show-thumbprint", "--instance", instance.Name)).StandardOutput.Trim(); } } #endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index 39599ce97..e751b9a1f 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -17,10 +17,10 @@ namespace Octopus.Tentacle.Tests.Integration.Support // Builds a Tentacle instance that is configured but not running, for tests that drive Tentacle through its commands. public class TentacleInstanceBuilder { - Version? tentacleVersion; + Version? tentacleVersion = TentacleVersions.Current; bool withNewCertificate; - public TentacleInstanceBuilder WithTentacleVersion(Version tentacleVersion) + public TentacleInstanceBuilder WithTentacleVersion(Version? tentacleVersion) { this.tentacleVersion = tentacleVersion; return this; @@ -34,15 +34,12 @@ public TentacleInstanceBuilder WithNewCertificate() public async Task Build(ILogger logger, CancellationToken cancellationToken) { - var tentacleExe = tentacleVersion == null - ? TentacleExeFinder.FindTentacleExe() - : await TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken); - - var instance = new TentacleInstance(tentacleExe, cancellationToken); - await instance.ExecuteTentacleCommand(instance.TentacleExe, CommandResultValidation.ZeroExitCode, "create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); + var instance = new TentacleInstance(logger, cancellationToken); + await instance.ChangeTentacleVersion(tentacleVersion); + await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); if (withNewCertificate) { - await instance.ExecuteTentacleCommand(instance.TentacleExe, CommandResultValidation.ZeroExitCode, "new-certificate", "--instance", instance.Name); + await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "new-certificate", "--instance", instance.Name); } return instance; @@ -53,23 +50,33 @@ public async Task Build(ILogger logger, CancellationToken canc public class TentacleInstance : IDisposable { readonly TemporaryDirectory home = new(); + readonly ILogger logger; readonly CancellationToken cancellationToken; + string tentacleExe = null!; - internal TentacleInstance(string tentacleExe, CancellationToken cancellationToken) + internal TentacleInstance(ILogger logger, CancellationToken cancellationToken) { - TentacleExe = tentacleExe; + this.logger = logger; this.cancellationToken = cancellationToken; } public string Name => "Tentacle"; - public string TentacleExe { get; } public string ConfigurationFile => Path.Combine(home.DirectoryPath, "tentacle.config"); public string DataDirectory => Path.Combine(home.DirectoryPath, "data"); + // Swaps the Tentacle that runs this instance's commands, as installing a different version over it would. Null is the current build. + public async Task ChangeTentacleVersion(Version? tentacleVersion) + => tentacleExe = tentacleVersion is null + ? TentacleExeFinder.FindTentacleExe() + : await TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken); + public string CertificateAsStoredInTheConfigurationFile() => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; - public async Task ExecuteTentacleCommand(string tentacleExe, CommandResultValidation validation, params string[] arguments) + public async Task ShowThumbprint() + => (await ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "show-thumbprint", "--instance", Name)).StandardOutput.Trim(); + + public async Task ExecuteTentacleCommand(CommandResultValidation validation, params string[] arguments) => await Cli.Wrap(tentacleExe) .WithArguments(arguments) .WithValidation(validation) From 8501b8c22beef6ef3132fae42931ac40d8638df1 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 16:09:47 +1100 Subject: [PATCH 058/124] Build the Tentacle instance with its Tentacle and upgrade it to the latest explicitly --- .../ConfigurationEncryptionUpgradeTests.cs | 4 ++-- .../Support/TentacleInstanceBuilder.cs | 22 +++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 922a90f4a..8a12b3feb 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -30,7 +30,7 @@ public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToIt instance.CertificateAsStoredInTheConfigurationFile().Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); // Act - await instance.ChangeTentacleVersion(TentacleVersions.Current); + instance.UpgradeToLatestTentacle(); await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption", "--instance", instance.Name); // Assert @@ -51,7 +51,7 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co await File.WriteAllTextAsync(instance.DataDirectory, "a file where the data directory should be, so the key directory cannot be created"); // Act - await instance.ChangeTentacleVersion(TentacleVersions.Current); + instance.UpgradeToLatestTentacle(); var upgrade = await instance.ExecuteTentacleCommand(CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", instance.Name); // Assert diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index e751b9a1f..e499e78da 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -34,8 +34,11 @@ public TentacleInstanceBuilder WithNewCertificate() public async Task Build(ILogger logger, CancellationToken cancellationToken) { - var instance = new TentacleInstance(logger, cancellationToken); - await instance.ChangeTentacleVersion(tentacleVersion); + var tentacleExe = tentacleVersion is null + ? TentacleExeFinder.FindTentacleExe() + : await TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken); + + var instance = new TentacleInstance(tentacleExe, cancellationToken); await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); if (withNewCertificate) { @@ -50,13 +53,12 @@ public async Task Build(ILogger logger, CancellationToken canc public class TentacleInstance : IDisposable { readonly TemporaryDirectory home = new(); - readonly ILogger logger; readonly CancellationToken cancellationToken; - string tentacleExe = null!; + string tentacleExe; - internal TentacleInstance(ILogger logger, CancellationToken cancellationToken) + internal TentacleInstance(string tentacleExe, CancellationToken cancellationToken) { - this.logger = logger; + this.tentacleExe = tentacleExe; this.cancellationToken = cancellationToken; } @@ -64,11 +66,9 @@ internal TentacleInstance(ILogger logger, CancellationToken cancellationToken) public string ConfigurationFile => Path.Combine(home.DirectoryPath, "tentacle.config"); public string DataDirectory => Path.Combine(home.DirectoryPath, "data"); - // Swaps the Tentacle that runs this instance's commands, as installing a different version over it would. Null is the current build. - public async Task ChangeTentacleVersion(Version? tentacleVersion) - => tentacleExe = tentacleVersion is null - ? TentacleExeFinder.FindTentacleExe() - : await TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken); + // As installing the latest Tentacle over this instance would. + public void UpgradeToLatestTentacle() + => tentacleExe = TentacleExeFinder.FindTentacleExe(); public string CertificateAsStoredInTheConfigurationFile() => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; From 3c2d66a7ef71ec24fa38ffdab887be8786f35734 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 16:14:35 +1100 Subject: [PATCH 059/124] Build the Tentacle instance with its Tentacle and switch to the current Tentacle with a new instance --- .../ConfigurationEncryptionUpgradeTests.cs | 10 +++++----- .../Support/TentacleInstanceBuilder.cs | 17 +++++++++++------ 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 8a12b3feb..350f0c220 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -30,13 +30,13 @@ public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToIt instance.CertificateAsStoredInTheConfigurationFile().Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); // Act - instance.UpgradeToLatestTentacle(); - await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption", "--instance", instance.Name); + var upgradedInstance = instance.WithCurrentTentacleExe(); + await upgradedInstance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption", "--instance", instance.Name); // Assert instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); File.Exists(Path.Combine(instance.DataDirectory, instance.Name, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); - (await instance.ShowThumbprint()).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); + (await upgradedInstance.ShowThumbprint()).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); } [Test] @@ -51,8 +51,8 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co await File.WriteAllTextAsync(instance.DataDirectory, "a file where the data directory should be, so the key directory cannot be created"); // Act - instance.UpgradeToLatestTentacle(); - var upgrade = await instance.ExecuteTentacleCommand(CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", instance.Name); + var upgradedInstance = instance.WithCurrentTentacleExe(); + var upgrade = await upgradedInstance.ExecuteTentacleCommand(CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", instance.Name); // Assert var output = upgrade.StandardOutput + upgrade.StandardError; diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index e499e78da..5518f0d72 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -52,12 +52,17 @@ public async Task Build(ILogger logger, CancellationToken canc // Everything the instance owns - its registry entry, configuration and data - lives in a temporary home directory. public class TentacleInstance : IDisposable { - readonly TemporaryDirectory home = new(); + readonly TemporaryDirectory home; + readonly string tentacleExe; readonly CancellationToken cancellationToken; - string tentacleExe; - internal TentacleInstance(string tentacleExe, CancellationToken cancellationToken) + internal TentacleInstance(string tentacleExe, CancellationToken cancellationToken) : this(new TemporaryDirectory(), tentacleExe, cancellationToken) { + } + + TentacleInstance(TemporaryDirectory home, string tentacleExe, CancellationToken cancellationToken) + { + this.home = home; this.tentacleExe = tentacleExe; this.cancellationToken = cancellationToken; } @@ -66,9 +71,9 @@ internal TentacleInstance(string tentacleExe, CancellationToken cancellationToke public string ConfigurationFile => Path.Combine(home.DirectoryPath, "tentacle.config"); public string DataDirectory => Path.Combine(home.DirectoryPath, "data"); - // As installing the latest Tentacle over this instance would. - public void UpgradeToLatestTentacle() - => tentacleExe = TentacleExeFinder.FindTentacleExe(); + // The same instance, as if the current Tentacle had been installed over it. + public TentacleInstance WithCurrentTentacleExe() + => new(home, TentacleExeFinder.FindTentacleExe(), cancellationToken); public string CertificateAsStoredInTheConfigurationFile() => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; From 598b3ca75e210be57dfbe8d4e5ffc99b51c5ec12 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 16:22:14 +1100 Subject: [PATCH 060/124] Test that an unnamed version 14 instance is told to create a named instance, using the real executables --- .../ConfigurationEncryptionUpgradeTests.cs | 28 ++++++++++++-- .../Support/TentacleInstanceBuilder.cs | 38 +++++++++++++++---- .../TentacleConfigurationUpgradeTests.cs | 28 -------------- 3 files changed, 55 insertions(+), 39 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 350f0c220..d6cd015ad 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -31,11 +31,11 @@ public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToIt // Act var upgradedInstance = instance.WithCurrentTentacleExe(); - await upgradedInstance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption", "--instance", instance.Name); + await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption"); // Assert instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); - File.Exists(Path.Combine(instance.DataDirectory, instance.Name, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); + File.Exists(Path.Combine(instance.DataDirectory, instance.Name!, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); (await upgradedInstance.ShowThumbprint()).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); } @@ -52,7 +52,7 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co // Act var upgradedInstance = instance.WithCurrentTentacleExe(); - var upgrade = await upgradedInstance.ExecuteTentacleCommand(CommandResultValidation.None, "upgrade-configuration-encryption", "--instance", instance.Name); + var upgrade = await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "upgrade-configuration-encryption"); // Assert var output = upgrade.StandardOutput + upgrade.StandardError; @@ -60,6 +60,28 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co output.Should().Contain(instance.DataDirectory, "the failure should be about creating the key, not something else"); instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedByVersion14); } + + [Test] + public async Task AnUnnamedVersion14InstanceIsToldToCreateANamedInstanceBecauseItsOwnKeyIsStoredUnderTheInstanceName() + { + // Arrange + using var instance = await new TentacleInstanceBuilder() + .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) + .UnnamedInstanceAddressedOnlyByConfig() + .WithNewCertificate() + .Build(Logger, CancellationToken); + var certificateEncryptedByVersion14 = instance.CertificateAsStoredInTheConfigurationFile(); + + // Act + var upgradedInstance = instance.WithCurrentTentacleExe(); + var upgrade = await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "upgrade-configuration-encryption"); + + // Assert + var output = upgrade.StandardOutput + upgrade.StandardError; + upgrade.ExitCode.Should().NotBe(0, output); + output.Should().Contain("create-instance --instance", "the user should be told how to give the configuration a name"); + instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedByVersion14); + } } } #endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index 5518f0d72..5aeee7dee 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -19,6 +19,7 @@ public class TentacleInstanceBuilder { Version? tentacleVersion = TentacleVersions.Current; bool withNewCertificate; + bool unnamed; public TentacleInstanceBuilder WithTentacleVersion(Version? tentacleVersion) { @@ -26,6 +27,13 @@ public TentacleInstanceBuilder WithTentacleVersion(Version? tentacleVersion) return this; } + // An instance with no name has no registry entry, so commands can only reach it through its configuration file. + public TentacleInstanceBuilder UnnamedInstanceAddressedOnlyByConfig() + { + unnamed = true; + return this; + } + public TentacleInstanceBuilder WithNewCertificate() { withNewCertificate = true; @@ -38,11 +46,19 @@ public async Task Build(ILogger logger, CancellationToken canc ? TentacleExeFinder.FindTentacleExe() : await TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken); - var instance = new TentacleInstance(tentacleExe, cancellationToken); - await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); + var instance = new TentacleInstance(tentacleExe, unnamed ? null : "Tentacle", cancellationToken); + if (instance.Name is null) + { + await File.WriteAllTextAsync(instance.ConfigurationFile, "", cancellationToken); + } + else + { + await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); + } + if (withNewCertificate) { - await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "new-certificate", "--instance", instance.Name); + await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "new-certificate"); } return instance; @@ -56,30 +72,36 @@ public class TentacleInstance : IDisposable readonly string tentacleExe; readonly CancellationToken cancellationToken; - internal TentacleInstance(string tentacleExe, CancellationToken cancellationToken) : this(new TemporaryDirectory(), tentacleExe, cancellationToken) + internal TentacleInstance(string tentacleExe, string? name, CancellationToken cancellationToken) : this(new TemporaryDirectory(), tentacleExe, name, cancellationToken) { } - TentacleInstance(TemporaryDirectory home, string tentacleExe, CancellationToken cancellationToken) + TentacleInstance(TemporaryDirectory home, string tentacleExe, string? name, CancellationToken cancellationToken) { this.home = home; this.tentacleExe = tentacleExe; + Name = name; this.cancellationToken = cancellationToken; } - public string Name => "Tentacle"; + public string? Name { get; } public string ConfigurationFile => Path.Combine(home.DirectoryPath, "tentacle.config"); public string DataDirectory => Path.Combine(home.DirectoryPath, "data"); // The same instance, as if the current Tentacle had been installed over it. public TentacleInstance WithCurrentTentacleExe() - => new(home, TentacleExeFinder.FindTentacleExe(), cancellationToken); + => new(home, TentacleExeFinder.FindTentacleExe(), Name, cancellationToken); public string CertificateAsStoredInTheConfigurationFile() => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; public async Task ShowThumbprint() - => (await ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "show-thumbprint", "--instance", Name)).StandardOutput.Trim(); + => (await ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "show-thumbprint")).StandardOutput.Trim(); + + public async Task ExecuteTentacleCommandOnTheInstance(CommandResultValidation validation, string command) + => Name is null + ? await ExecuteTentacleCommand(validation, command, "--config", ConfigurationFile) + : await ExecuteTentacleCommand(validation, command, "--instance", Name); public async Task ExecuteTentacleCommand(CommandResultValidation validation, params string[] arguments) => await Cli.Wrap(tentacleExe) diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs index 460b5dca4..c0da0606e 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs @@ -8,13 +8,10 @@ using FluentAssertions; using NSubstitute; using NUnit.Framework; -using Octopus.Tentacle.Commands; using Octopus.Tentacle.Configuration; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Configuration.Instances; using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Internals.Options; -using Octopus.Tentacle.Startup; using Octopus.Tentacle.Tests.Support; using Octopus.Tentacle.Tests.Support.TestAttributes; using Octopus.Tentacle.Util; @@ -27,23 +24,6 @@ public class TentacleConfigurationUpgradeTests { const string Certificate = "MIIC...the certificate..."; - [Test] - public void UpgradeConfigurationEncryptionFailsForAConfigurationNotInTheRegistry() - { - // Arrange - using var sandbox = new ConfigurationSandbox(); - var store = sandbox.CreateStore(sandbox.DefaultKeyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - var legacyValue = sandbox.RawCertificate(); - - // Act - Action start = () => sandbox.StartUpgradeCommand(store, keyFilePath: null, instanceName: null); - - // Assert - start.Should().Throw().WithMessage("*create-instance --instance*"); - sandbox.RawCertificate().Should().Be(legacyValue); - } - [Test] public void AValueProtectedWithTheKeyIsNeverRewrittenWithALegacyKey() { @@ -109,14 +89,6 @@ public XmlFileKeyValueStore CreateStore(string keyFilePath) public TentacleConfigurationUpgrade CreateUpgrade(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle") => new(CreateSelector(store, keyFilePath, instanceName), FileSystem, Log); - public void StartUpgradeCommand(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle") - { - var selector = CreateSelector(store, keyFilePath, instanceName); - var upgrade = new TentacleConfigurationUpgrade(selector, FileSystem, Log); - var command = new UpgradeConfigurationEncryptionCommand(new Lazy(() => upgrade), selector, Log, Substitute.For()); - command.Start(new string[0], Substitute.For(), new OptionSet()); - } - public string RawCertificate() => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; From 1132beb883c112f7f05abea9454b96bf1889695f Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 16:23:00 +1100 Subject: [PATCH 061/124] Name the configuration encryption upgrade tests When_And_Then --- .../Configuration/ConfigurationEncryptionUpgradeTests.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index d6cd015ad..f6bb44845 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -19,7 +19,7 @@ public class ConfigurationEncryptionUpgradeTests : IntegrationTest static readonly string EncryptedWithItsOwnKey = LinuxMachineKeyEncryptor.Specifier + "$"; [Test] - public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToItsOwnKey() + public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndUpgradeConfigurationEncryptionIsCalled_ThenTheCertificateIsReEncrypted() { // Arrange using var instance = await new TentacleInstanceBuilder() @@ -40,7 +40,7 @@ public async Task AVersion14ConfigurationEncryptedWithTheMachineIdIsUpgradedToIt } [Test] - public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14ConfigurationStaysEncryptedWithTheMachineId() + public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheNewKeyCannotBeCreated_ThenUpgradeConfigurationEncryptionFailsAndTheCertificateIsUnchanged() { // Arrange using var instance = await new TentacleInstanceBuilder() @@ -62,7 +62,7 @@ public async Task WhenItsOwnKeyCannotBeCreatedThenTheUpgradeFailsAndAVersion14Co } [Test] - public async Task AnUnnamedVersion14InstanceIsToldToCreateANamedInstanceBecauseItsOwnKeyIsStoredUnderTheInstanceName() + public async Task WhenTentacleInstanceIsUnnamed_AndUpgradeConfigurationEncryptionIsCalled_ThenItFailsAndSaysToCreateANamedInstance() { // Arrange using var instance = await new TentacleInstanceBuilder() From 6c6409e24d5f3e32c28c9d475ef09669290f34ff Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 16:25:58 +1100 Subject: [PATCH 062/124] Move the lost key test to the real executable and drop the mocked upgrade tests --- .../ConfigurationEncryptionUpgradeTests.cs | 22 +++- .../Support/TentacleInstanceBuilder.cs | 2 + .../TentacleConfigurationUpgradeTests.cs | 106 ------------------ 3 files changed, 23 insertions(+), 107 deletions(-) delete mode 100644 source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index f6bb44845..dbb846c0e 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -35,7 +35,7 @@ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndUpgradeConfigura // Assert instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); - File.Exists(Path.Combine(instance.DataDirectory, instance.Name!, "keys", ConfigurationEncryptionKey.KeyFileName)).Should().BeTrue(); + File.Exists(instance.ConfigurationEncryptionKeyFile).Should().BeTrue(); (await upgradedInstance.ShowThumbprint()).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); } @@ -82,6 +82,26 @@ public async Task WhenTentacleInstanceIsUnnamed_AndUpgradeConfigurationEncryptio output.Should().Contain("create-instance --instance", "the user should be told how to give the configuration a name"); instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedByVersion14); } + + [Test] + public async Task WhenTentacleKeyFileIsDeleted_AndANewCertificateIsCreated_ThenItFailsRatherThanFallBackToEtcMachineId() + { + // Arrange + using var instance = await new TentacleInstanceBuilder() + .WithNewCertificate() + .Build(Logger, CancellationToken); + var certificateEncryptedWithTheKey = instance.CertificateAsStoredInTheConfigurationFile(); + certificateEncryptedWithTheKey.Should().StartWith(EncryptedWithItsOwnKey); + File.Delete(instance.ConfigurationEncryptionKeyFile); + + // Act + var newCertificate = await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "new-certificate"); + + // Assert + var output = newCertificate.StandardOutput + newCertificate.StandardError; + newCertificate.ExitCode.Should().NotBe(0, output); + instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedWithTheKey); + } } } #endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index 5aeee7dee..f3adbc544 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -8,6 +8,7 @@ using CliWrap.Buffered; using Octopus.Tentacle.CommonTestUtils; using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Tests.Integration.Support.TentacleFetchers; using Serilog; @@ -87,6 +88,7 @@ internal TentacleInstance(string tentacleExe, string? name, CancellationToken ca public string? Name { get; } public string ConfigurationFile => Path.Combine(home.DirectoryPath, "tentacle.config"); public string DataDirectory => Path.Combine(home.DirectoryPath, "data"); + public string ConfigurationEncryptionKeyFile => Path.Combine(DataDirectory, Name!, "keys", ConfigurationEncryptionKey.KeyFileName); // The same instance, as if the current Tentacle had been installed over it. public TentacleInstance WithCurrentTentacleExe() diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs deleted file mode 100644 index c0da0606e..000000000 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeTests.cs +++ /dev/null @@ -1,106 +0,0 @@ -#if NET -using System; -using System.IO; -using System.Linq; -using System.Runtime.Versioning; -using System.Security.Cryptography; -using System.Xml.Linq; -using FluentAssertions; -using NSubstitute; -using NUnit.Framework; -using Octopus.Tentacle.Configuration; -using Octopus.Tentacle.Configuration.Crypto; -using Octopus.Tentacle.Configuration.Instances; -using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Tests.Support; -using Octopus.Tentacle.Tests.Support.TestAttributes; -using Octopus.Tentacle.Util; - -namespace Octopus.Tentacle.Tests.Configuration -{ - [LinuxOrMacTest] - [UnsupportedOSPlatform("windows")] - public class TentacleConfigurationUpgradeTests - { - const string Certificate = "MIIC...the certificate..."; - - [Test] - public void AValueProtectedWithTheKeyIsNeverRewrittenWithALegacyKey() - { - // Arrange - using var sandbox = new ConfigurationSandbox(); - var keyFilePath = Path.Combine(sandbox.Directory, "my-key", ConfigurationEncryptionKey.KeyFileName); - new ConfigurationEncryptionKey(sandbox.Log, sandbox.FileSystem, keyFilePath).CreateIfMissing(); - sandbox.CreateStore(keyFilePath).Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - var protectedValue = sandbox.RawCertificate(); - var storeWithoutKey = sandbox.CreateStore(Path.Combine(sandbox.Directory, "missing", ConfigurationEncryptionKey.KeyFileName)); - - // Act - Action set = () => storeWithoutKey.Set(TentacleConfiguration.CertificateSettingName, "another certificate", ProtectionLevel.MachineKey); - - // Assert - set.Should().Throw(); - sandbox.RawCertificate().Should().Be(protectedValue); - } - - [Test] - public void WhenTheKeyIsLostAfterMigrationThenStartLeavesProtectedValuesUntouched() - { - // Arrange - using var sandbox = new ConfigurationSandbox(); - var keyFilePath = sandbox.DefaultKeyFilePath; - var store = sandbox.CreateStore(keyFilePath); - store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey); - sandbox.CreateUpgrade(store, keyFilePath).Upgrade(); - var protectedValue = sandbox.RawCertificate(); - File.Delete(keyFilePath); - - // Act - sandbox.CreateUpgrade(sandbox.CreateStore(keyFilePath), keyFilePath).Upgrade(); - - // Assert - sandbox.RawCertificate().Should().Be(protectedValue); - sandbox.RawCertificate().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); - } - - sealed class ConfigurationSandbox : IDisposable - { - readonly InMemoryCryptoKeyNixSource legacyKey = new(); - - public ConfigurationSandbox() - { - Directory = Path.Combine(Path.GetTempPath(), "octopus-config-upgrade-" + Guid.NewGuid()); - System.IO.Directory.CreateDirectory(Directory); - ConfigurationFile = Path.Combine(Directory, "tentacle.config"); - FileSystem = new OctopusPhysicalFileSystem(Log); - FileSystem.OverwriteFile(ConfigurationFile, @""); - } - - public string Directory { get; } - public string ConfigurationFile { get; } - public ISystemLog Log { get; } = Substitute.For(); - public OctopusPhysicalFileSystem FileSystem { get; } - - public string DefaultKeyFilePath => Path.Combine(Directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); - - public XmlFileKeyValueStore CreateStore(string keyFilePath) - => new(FileSystem, ConfigurationFile, encryptor: new LinuxMachineKeyEncryptor(Log, new ConfigurationEncryptionKey(Log, FileSystem, keyFilePath), new[] { legacyKey })); - - public TentacleConfigurationUpgrade CreateUpgrade(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle") - => new(CreateSelector(store, keyFilePath, instanceName), FileSystem, Log); - - public string RawCertificate() - => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; - - IApplicationInstanceSelector CreateSelector(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName) - { - var selector = Substitute.For(); - selector.Current.Returns(new ApplicationInstanceConfiguration(instanceName, ConfigurationFile, store, store, keyFilePath)); - return selector; - } - - public void Dispose() => System.IO.Directory.Delete(Directory, recursive: true); - } - } -} -#endif From f4486d868fa6828cea525df585c3aa0256a970c5 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 16:58:01 +1100 Subject: [PATCH 063/124] Build running Tentacles from a TentacleInstance, and test the upgrade when the current Tentacle starts --- .../ConfigurationEncryptionUpgradeTests.cs | 41 ++++++ .../Support/ClientAndTentacleBuilder.cs | 14 +- .../Legacy/LegacyClientAndTentacleBuilder.cs | 8 +- ....cs => ListeningRunningTentacleBuilder.cs} | 39 ++---- ...er.cs => PollingRunningTentacleBuilder.cs} | 40 ++---- .../Support/RunningTentacle.cs | 8 +- ...leBuilder.cs => RunningTentacleBuilder.cs} | 131 ++++++++---------- ...RunningTentacleBuilderExtensionMethods.cs} | 4 +- .../Support/TentacleInstanceBuilder.cs | 109 ++++++++++++--- 9 files changed, 243 insertions(+), 151 deletions(-) rename source/Octopus.Tentacle.Tests.Integration/Support/{ListeningTentacleBuilder.cs => ListeningRunningTentacleBuilder.cs} (51%) rename source/Octopus.Tentacle.Tests.Integration/Support/{PollingTentacleBuilder.cs => PollingRunningTentacleBuilder.cs} (52%) rename source/Octopus.Tentacle.Tests.Integration/Support/{TentacleBuilder.cs => RunningTentacleBuilder.cs} (82%) rename source/Octopus.Tentacle.Tests.Integration/Support/{TentacleBuilderExtensionMethods.cs => RunningTentacleBuilderExtensionMethods.cs} (65%) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index dbb846c0e..85e6be5b4 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -6,6 +6,7 @@ using CliWrap; using FluentAssertions; using NUnit.Framework; +using Octopus.Tentacle.CommonTestUtils; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Tests.Integration.Support; using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; @@ -102,6 +103,46 @@ public async Task WhenTentacleKeyFileIsDeleted_AndANewCertificateIsCreated_ThenI newCertificate.ExitCode.Should().NotBe(0, output); instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedWithTheKey); } + + [Test] + public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheCurrentTentacleStarts_ThenTheCertificateIsReEncrypted() + { + // Arrange + using var instance = await new TentacleInstanceBuilder() + .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) + .WithNewCertificate() + .Build(Logger, CancellationToken); + + // Act + await using var runningTentacle = await new ListeningRunningTentacleBuilder(TestCertificates.ServerPublicThumbprint, instance.WithCurrentTentacleExe()) + .Build(Logger, CancellationToken); + + // Assert + instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); + (await instance.WithCurrentTentacleExe().ShowThumbprint()).Should().Be(instance.Thumbprint, "the upgraded certificate must still decrypt to the same certificate"); + } + + [Test] + public async Task WhenTentacleKeyFileIsDeleted_AndTheCurrentTentacleStarts_ThenTheCertificateIsLeftUntouched() + { + // Arrange + using var instance = await new TentacleInstanceBuilder() + .WithNewCertificate() + .Build(Logger, CancellationToken); + var certificateEncryptedWithTheKey = instance.CertificateAsStoredInTheConfigurationFile(); + File.Delete(instance.ConfigurationEncryptionKeyFile); + + // Act + Func start = async () => + { + await using var runningTentacle = await new ListeningRunningTentacleBuilder(TestCertificates.ServerPublicThumbprint, instance) + .Build(Logger, CancellationToken); + }; + + // Assert + await start.Should().ThrowAsync("the certificate cannot be decrypted without its key"); + instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedWithTheKey); + } } } #endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/ClientAndTentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/ClientAndTentacleBuilder.cs index b61ac18c9..cc13667db 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/ClientAndTentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/ClientAndTentacleBuilder.cs @@ -36,7 +36,7 @@ public class ClientAndTentacleBuilder IPendingRequestQueueFactory? queueFactory = null; Reference? portForwarderReference; ITentacleClientObserver tentacleClientObserver = new NoTentacleClientObserver(); - Action? tentacleBuilderAction; + Action? tentacleBuilderAction; Action? configureClientOptions; TcpConnectionUtilities? tcpConnectionUtilities; bool installAsAService = false; @@ -141,7 +141,7 @@ public ClientAndTentacleBuilder WithTentacleClientObserver(ITentacleClientObserv return this; } - public ClientAndTentacleBuilder WithTentacle(Action tentacleBuilderAction) + public ClientAndTentacleBuilder WithTentacle(Action tentacleBuilderAction) { this.tentacleBuilderAction = tentacleBuilderAction; return this; @@ -224,8 +224,10 @@ public async Task Build(CancellationToken cancellationToken) { portForwarder = BuildPortForwarder(serverListeningPort, null); - var pollingTentacleBuilder = new PollingTentacleBuilder(portForwarder?.ListeningPort ?? serverListeningPort, TestCertificates.ServerPublicThumbprint, tentacleVersion) + var pollingTentacleBuilder = new TentacleInstanceBuilder() + .WithTentacleVersion(tentacleVersion) .WithTentacleExe(tentacleExe) + .RunAsPollingTentacle(portForwarder?.ListeningPort ?? serverListeningPort, TestCertificates.ServerPublicThumbprint) .WithSubscriptionId(pollingSubscriptionId); if (useDefaultMachineConfigurationHomeDirectory) @@ -246,8 +248,10 @@ public async Task Build(CancellationToken cancellationToken) } else { - var listeningTentacleBuilder = new ListeningTentacleBuilder(TestCertificates.ServerPublicThumbprint, tentacleVersion) - .WithTentacleExe(tentacleExe); + var listeningTentacleBuilder = new TentacleInstanceBuilder() + .WithTentacleVersion(tentacleVersion) + .WithTentacleExe(tentacleExe) + .RunAsListeningTentacle(TestCertificates.ServerPublicThumbprint); if (useDefaultMachineConfigurationHomeDirectory) { diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/Legacy/LegacyClientAndTentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/Legacy/LegacyClientAndTentacleBuilder.cs index e5b77912e..d0a5f262e 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/Legacy/LegacyClientAndTentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/Legacy/LegacyClientAndTentacleBuilder.cs @@ -83,8 +83,10 @@ public async Task Build(CancellationToken cancellationT { portForwarder = PortForwarderBuilder.ForwardingToLocalPort(serverListeningPort, new SerilogLoggerBuilder().Build()).Build(); - runningTentacle = await new PollingTentacleBuilder(portForwarder.ListeningPort, TestCertificates.ServerPublicThumbprint, tentacleVersion) + runningTentacle = await new TentacleInstanceBuilder() + .WithTentacleVersion(tentacleVersion) .WithTentacleExe(tentacleExe) + .RunAsPollingTentacle(portForwarder.ListeningPort, TestCertificates.ServerPublicThumbprint) .WithSubscriptionId(pollingSubscriptionId) .Build(logger, cancellationToken); @@ -92,8 +94,10 @@ public async Task Build(CancellationToken cancellationT } else { - runningTentacle = await new ListeningTentacleBuilder(TestCertificates.ServerPublicThumbprint, tentacleVersion) + runningTentacle = await new TentacleInstanceBuilder() + .WithTentacleVersion(tentacleVersion) .WithTentacleExe(tentacleExe) + .RunAsListeningTentacle(TestCertificates.ServerPublicThumbprint) .Build(logger, cancellationToken); portForwarder = new PortForwarderBuilder(runningTentacle.ServiceUri, new SerilogLoggerBuilder().Build()).Build(); diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/ListeningTentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/ListeningRunningTentacleBuilder.cs similarity index 51% rename from source/Octopus.Tentacle.Tests.Integration/Support/ListeningTentacleBuilder.cs rename to source/Octopus.Tentacle.Tests.Integration/Support/ListeningRunningTentacleBuilder.cs index 61a90c30d..c0f3cdbee 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/ListeningTentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/ListeningRunningTentacleBuilder.cs @@ -8,42 +8,33 @@ namespace Octopus.Tentacle.Tests.Integration.Support { - public class ListeningTentacleBuilder : TentacleBuilder + public class ListeningRunningTentacleBuilder : RunningTentacleBuilder { - public ListeningTentacleBuilder(string serverThumbprint, Version? tentacleVersion) : base(tentacleVersion) + internal ListeningRunningTentacleBuilder(string serverThumbprint, TentacleInstanceBuilder instanceBuilder) : base(instanceBuilder) { ServerThumbprint = serverThumbprint; } - internal async Task Build(ILogger log, CancellationToken cancellationToken) + public ListeningRunningTentacleBuilder(string serverThumbprint, TentacleInstance instance) : base(instance) { - var instanceName = InstanceNameGenerator(); - var configFilePath = Path.Combine(HomeDirectory.DirectoryPath, instanceName + ".cfg"); - var tentacleExe = TentacleExePath ?? TentacleExeFinder.FindTentacleExe(); - - var logger = log.ForContext(); - logger.Information($"Tentacle.exe location: {tentacleExe}"); + ServerThumbprint = serverThumbprint; + } - ConfigureTentacleMachineConfigurationHomeDirectory(); + internal async Task Build(ILogger log, CancellationToken cancellationToken) + { + var logger = log.ForContext(); using (await GetConfigureAndStartTentacleLockIfRequired(logger, cancellationToken)) { - await CreateInstance(tentacleExe, configFilePath, instanceName, HomeDirectory, logger, cancellationToken); - await AddCertificateToTentacle(tentacleExe, instanceName, CertificatePfxPath, HomeDirectory, logger, cancellationToken); - var applicationDirectory = Path.Combine(HomeDirectory.DirectoryPath, "appdir"); - ConfigureTentacleToListen(configFilePath, applicationDirectory); + var instance = await BuildInstance(logger, cancellationToken); + logger.Information($"Tentacle.exe location: {instance.TentacleExe}"); + + var applicationDirectory = Path.Combine(instance.Home.DirectoryPath, "appdir"); + ConfigureTentacleToListen(instance.ConfigurationFile, applicationDirectory); - var runningTentacle = await StartTentacle( - null, - tentacleExe, - instanceName, - HomeDirectory, - applicationDirectory, - TentacleThumbprint, - logger, - cancellationToken); + var runningTentacle = await StartTentacle(null, instance, applicationDirectory, logger, cancellationToken); - SetThePort(configFilePath, runningTentacle.ServiceUri.Port); + SetThePort(instance.ConfigurationFile, runningTentacle.ServiceUri.Port); return runningTentacle; } diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/PollingTentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/PollingRunningTentacleBuilder.cs similarity index 52% rename from source/Octopus.Tentacle.Tests.Integration/Support/PollingTentacleBuilder.cs rename to source/Octopus.Tentacle.Tests.Integration/Support/PollingRunningTentacleBuilder.cs index d140840eb..c64c8fa92 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/PollingTentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/PollingRunningTentacleBuilder.cs @@ -9,20 +9,24 @@ namespace Octopus.Tentacle.Tests.Integration.Support { - public class PollingTentacleBuilder : TentacleBuilder + public class PollingRunningTentacleBuilder : RunningTentacleBuilder { readonly int pollingPort; Uri? subscriptionId; - public PollingTentacleBuilder(int pollingPort, string serverThumbprint, Version? tentacleVersion) : base(tentacleVersion) - + internal PollingRunningTentacleBuilder(int pollingPort, string serverThumbprint, TentacleInstanceBuilder instanceBuilder) : base(instanceBuilder) { this.pollingPort = pollingPort; + ServerThumbprint = serverThumbprint; + } + public PollingRunningTentacleBuilder(int pollingPort, string serverThumbprint, TentacleInstance instance) : base(instance) + { + this.pollingPort = pollingPort; ServerThumbprint = serverThumbprint; } - public PollingTentacleBuilder WithSubscriptionId(Uri subscriptionId) + public PollingRunningTentacleBuilder WithSubscriptionId(Uri subscriptionId) { this.subscriptionId = subscriptionId; return this; @@ -30,32 +34,18 @@ public PollingTentacleBuilder WithSubscriptionId(Uri subscriptionId) internal async Task Build(ILogger log, CancellationToken cancellationToken) { - var instanceName = InstanceNameGenerator(); - var configFilePath = Path.Combine(HomeDirectory.DirectoryPath, instanceName + ".cfg"); - var tentacleExe = TentacleExePath ?? TentacleExeFinder.FindTentacleExe(); var subscriptionId = this.subscriptionId ?? PollingSubscriptionId.Generate(); - - var logger = log.ForContext(); - logger.Information($"Tentacle.exe location: {tentacleExe}"); - - ConfigureTentacleMachineConfigurationHomeDirectory(); + var logger = log.ForContext(); using (await GetConfigureAndStartTentacleLockIfRequired(logger, cancellationToken)) { - await CreateInstance(tentacleExe, configFilePath, instanceName, HomeDirectory, logger, cancellationToken); - var applicationDirectory = Path.Combine(HomeDirectory.DirectoryPath, "appdir"); - ConfigureTentacleToPollOctopusServer(configFilePath, subscriptionId, applicationDirectory); - await AddCertificateToTentacle(tentacleExe, instanceName, CertificatePfxPath, HomeDirectory, logger, cancellationToken); + var instance = await BuildInstance(logger, cancellationToken); + logger.Information($"Tentacle.exe location: {instance.TentacleExe}"); + + var applicationDirectory = Path.Combine(instance.Home.DirectoryPath, "appdir"); + ConfigureTentacleToPollOctopusServer(instance.ConfigurationFile, subscriptionId, applicationDirectory); - return await StartTentacle( - subscriptionId, - tentacleExe, - instanceName, - HomeDirectory, - applicationDirectory, - TentacleThumbprint, - logger, - cancellationToken); + return await StartTentacle(subscriptionId, instance, applicationDirectory, logger, cancellationToken); } } diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs index eb81ccbec..a33e06253 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs @@ -12,7 +12,7 @@ namespace Octopus.Tentacle.Tests.Integration.Support { public class RunningTentacle : IAsyncDisposable { - private readonly TemporaryDirectory temporaryDirectory; + private readonly TemporaryDirectory? temporaryDirectoryToDelete; private CancellationTokenSource? cancellationTokenSource; private Task? runningTentacleTask; private readonly Func> startTentacleFunction; @@ -20,7 +20,7 @@ public class RunningTentacle : IAsyncDisposable private ILogger logger; public RunningTentacle(FileInfo tentacleExe, - TemporaryDirectory temporaryDirectory, + TemporaryDirectory? temporaryDirectoryToDelete, Func> startTentacleFunction, string thumbprint, string instanceName, @@ -31,7 +31,7 @@ public RunningTentacle(FileInfo tentacleExe, ILogger logger) { this.startTentacleFunction = startTentacleFunction; - this.temporaryDirectory = temporaryDirectory; + this.temporaryDirectoryToDelete = temporaryDirectoryToDelete; this.deleteInstanceFunction = deleteInstanceFunction; TentacleExe = tentacleExe; @@ -111,7 +111,7 @@ public async ValueTask DisposeAsync() await deleteInstanceFunction(cancellationToken); logger.Information("Starting temporaryDirectory.Dispose"); - temporaryDirectory.Dispose(); + temporaryDirectoryToDelete?.Dispose(); logger.Information("Finished DisposeAsync"); } diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs similarity index 82% rename from source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs rename to source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs index 6e1e929ed..a54da82ff 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs @@ -23,24 +23,21 @@ namespace Octopus.Tentacle.Tests.Integration.Support { - public interface ITentacleBuilder + public interface IRunningTentacleBuilder { - ITentacleBuilder WithEnvironmentVariable(string environmentVariable, TValue value); - ITentacleBuilder WithHomeDirectory(TemporaryDirectory homeDirectory); + IRunningTentacleBuilder WithEnvironmentVariable(string environmentVariable, TValue value); + IRunningTentacleBuilder WithHomeDirectory(TemporaryDirectory homeDirectory); } - public abstract class TentacleBuilder : ITentacleBuilder - where T : TentacleBuilder + public abstract class RunningTentacleBuilder : IRunningTentacleBuilder + where T : RunningTentacleBuilder { private readonly AsyncLock configureAndStartTentacleLock = new (); - protected readonly Version? TentacleVersion; + readonly TentacleInstanceBuilder? instanceBuilder; + readonly TentacleInstance? givenInstance; protected string? ServerThumbprint; - protected string? TentacleExePath; - protected string CertificatePfxPath = TestCertificates.TentaclePfxPath; - protected string TentacleThumbprint = TestCertificates.TentaclePublicThumbprint; bool installAsService = false; - bool useDefaultMachineConfigurationHomeDirectory = false; static readonly Regex ListeningPortRegex = new (@"listen:\/\/.+:(\d+)\/"); readonly Dictionary runTentacleEnvironmentVariables = BuildDefaultTentacleEnvironmentVariables(); @@ -54,29 +51,52 @@ public static Dictionary BuildDefaultTentacleEnvironmentVariable return env; } - TemporaryDirectory? homeDirectory; + // Builds the instance, so the running Tentacle owns it and deletes it when disposed. + protected RunningTentacleBuilder(TentacleInstanceBuilder instanceBuilder) + { + this.instanceBuilder = instanceBuilder + .WithName(InstanceNameGenerator()) + .WithCertificate(TestCertificates.TentaclePfxPath, TestCertificates.TentaclePublicThumbprint); + } - public TentacleBuilder(Version? tentacleVersion) + // Runs an instance the caller built, so the caller owns it. + protected RunningTentacleBuilder(TentacleInstance instance) { - this.TentacleVersion = tentacleVersion; + if (instance.Name == null) + { + throw new ArgumentException("An unnamed instance cannot be run, the agent is started with --instance", nameof(instance)); + } + + givenInstance = instance; } - protected TemporaryDirectory HomeDirectory + TentacleInstanceBuilder InstanceBuilder + => instanceBuilder ?? throw new InvalidOperationException("The instance was given already built, so it cannot be changed"); + + protected async Task BuildInstance(ILogger logger, CancellationToken cancellationToken) { - get + var instance = givenInstance ?? await InstanceBuilder.Build(logger, cancellationToken); + if (instance.Thumbprint == null) + { + throw new InvalidOperationException("The instance needs a certificate to be run"); + } + + foreach (var environmentVariable in instance.EnvironmentVariables) { - homeDirectory ??= new TemporaryDirectory(); - return homeDirectory; + runTentacleEnvironmentVariables.TryAdd(environmentVariable.Key, environmentVariable.Value); } + + return instance; } protected AwaitableDisposable GetConfigureAndStartTentacleLockIfRequired(ILogger logger, CancellationToken cancellationToken) { // If we are using a Tentacle version prior to 8.1.284 then there is no way to isolate the tentacle instances // so we take an exclusive lock around configuration, startup and deletion of the tentacle instance - if (TentacleVersion != null && TentacleVersion < new Version(8, 1, 284)) + var tentacleVersion = instanceBuilder?.TentacleVersion; + if (tentacleVersion != null && tentacleVersion < new Version(8, 1, 284)) { - logger.Information($"Acquiring an exclusive lock to perform configuration / startup or deletion of Tentacle {TentacleVersion}"); + logger.Information($"Acquiring an exclusive lock to perform configuration / startup or deletion of Tentacle {tentacleVersion}"); return configureAndStartTentacleLock.LockAsync(cancellationToken); } @@ -89,30 +109,16 @@ async Task GetDummyDisposableAsync() } } - public ITentacleBuilder WithHomeDirectory(TemporaryDirectory homeDirectory) + public IRunningTentacleBuilder WithHomeDirectory(TemporaryDirectory homeDirectory) { - this.homeDirectory = homeDirectory; + InstanceBuilder.WithHomeDirectory(homeDirectory); return this; } - public T WithCertificate(string certificatePfxPath, string tentacleThumbprint) - { - CertificatePfxPath = certificatePfxPath; - TentacleThumbprint = tentacleThumbprint; - - return (T)this; - } - - public T WithTentacleExe(string tentacleExe) - { - TentacleExePath = tentacleExe; - - return (T)this; - } - - public ITentacleBuilder WithEnvironmentVariable(string environmentVariable, TValue value) + public IRunningTentacleBuilder WithEnvironmentVariable(string environmentVariable, TValue value) { runTentacleEnvironmentVariables[environmentVariable] = value?.ToString(); + instanceBuilder?.WithEnvironmentVariable(environmentVariable, value?.ToString()); return this; } @@ -126,41 +132,44 @@ protected void WithWritableTentacleConfiguration(string configFilePath, Action StartTentacle( Uri? serviceUri, - string tentacleExe, - string instanceName, - TemporaryDirectory tempDirectory, + TentacleInstance instance, string applicationDirectory, - string tentacleThumbprint, ILogger logger, CancellationToken cancellationToken) { - var log = new SerilogLoggerBuilder().Build().ForContext(); + var log = new SerilogLoggerBuilder().Build().ForContext(); + var tentacleExe = instance.TentacleExe; + var instanceName = instance.Name!; + var tempDirectory = instance.Home; + var ownsInstance = givenInstance == null; var runningTentacle = new RunningTentacle( new FileInfo(tentacleExe), - tempDirectory, + ownsInstance ? tempDirectory : null, startTentacleFunction: ct => RunTentacle(serviceUri, tentacleExe, instanceName, tempDirectory, log, ct), - tentacleThumbprint, + instance.Thumbprint!, instanceName, - HomeDirectory.DirectoryPath, + tempDirectory.DirectoryPath, applicationDirectory, - deleteInstanceFunction: ct => DeleteInstanceIgnoringFailure(installAsService, tentacleExe, instanceName, tempDirectory, logger, ct), + deleteInstanceFunction: ownsInstance + ? ct => DeleteInstanceIgnoringFailure(installAsService, tentacleExe, instanceName, tempDirectory, logger, ct) + : _ => Task.CompletedTask, runTentacleEnvironmentVariables, logger); @@ -314,18 +323,6 @@ await RunCommandOutOfProcess( return (runningTentacle, serviceUri); } - protected void ConfigureTentacleMachineConfigurationHomeDirectory() - { - if (!useDefaultMachineConfigurationHomeDirectory) - { - var directory = Path.Combine(HomeDirectory.DirectoryPath, "Octopus", "Tentacle", "Instances"); - - WithEnvironmentVariable(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, directory); - } - - WithEnvironmentVariable(EnvironmentVariables.TentacleInstancesDataDirectory, Path.Combine(HomeDirectory.DirectoryPath, "data")); - } - async Task SetEnvironmentVariablesForService(string instanceName, TemporaryDirectory tempDirectory, ILogger logger, CancellationToken cancellationToken) { if (PlatformDetection.IsRunningOnWindows) @@ -394,18 +391,6 @@ await RunCommandOutOfProcess( return (false, null, lastLogFileContents); } - protected async Task AddCertificateToTentacle(string tentacleExe, string instanceName, string tentaclePfxPath, TemporaryDirectory tmp, ILogger logger, CancellationToken cancellationToken) - { - await RunTentacleCommand(tentacleExe, new[] {"import-certificate", $"--from-file={tentaclePfxPath}", $"--instance={instanceName}"}, tmp, logger, cancellationToken); - cancellationToken.ThrowIfCancellationRequested(); - } - - protected async Task CreateInstance(string tentacleExe, string configFilePath, string instanceName, TemporaryDirectory tmp, ILogger logger, CancellationToken cancellationToken) - { - await RunTentacleCommand(tentacleExe, new[] {"create-instance", "--config", configFilePath, $"--instance={instanceName}"}, tmp, logger,cancellationToken); - cancellationToken.ThrowIfCancellationRequested(); - } - internal async Task DeleteInstanceIgnoringFailure(bool runningAsService, string tentacleExe, string instanceName, TemporaryDirectory tmp, ILogger logger, CancellationToken cancellationToken) { using (await GetConfigureAndStartTentacleLockIfRequired(logger, cancellationToken)) diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilderExtensionMethods.cs b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilderExtensionMethods.cs similarity index 65% rename from source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilderExtensionMethods.cs rename to source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilderExtensionMethods.cs index 011cf4553..328f3895d 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleBuilderExtensionMethods.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilderExtensionMethods.cs @@ -3,9 +3,9 @@ namespace Octopus.Tentacle.Tests.Integration.Support { - public static class TentacleBuilderExtensionMethods + public static class RunningTentacleBuilderExtensionMethods { - public static ITentacleBuilder WithWorkspaceCleaningSettings(this ITentacleBuilder builder, TimeSpan cleanerDelay, TimeSpan deleteWorkspacesOlderThan) + public static IRunningTentacleBuilder WithWorkspaceCleaningSettings(this IRunningTentacleBuilder builder, TimeSpan cleanerDelay, TimeSpan deleteWorkspacesOlderThan) { return builder .WithEnvironmentVariable(WorkspaceCleanerConfiguration.CleanerDelayEnvironmentVariableName, cleanerDelay) diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index f3adbc544..2e0670bb1 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; @@ -19,8 +20,15 @@ namespace Octopus.Tentacle.Tests.Integration.Support public class TentacleInstanceBuilder { Version? tentacleVersion = TentacleVersions.Current; + string? tentacleExe; + string? name = "Tentacle"; + TemporaryDirectory? home; + bool useDefaultMachineConfigurationHomeDirectory; + readonly Dictionary environmentVariables = new(); bool withNewCertificate; - bool unnamed; + (string PfxPath, string Thumbprint)? certificate; + + internal Version? TentacleVersion => tentacleVersion; public TentacleInstanceBuilder WithTentacleVersion(Version? tentacleVersion) { @@ -28,10 +36,47 @@ public TentacleInstanceBuilder WithTentacleVersion(Version? tentacleVersion) return this; } + public TentacleInstanceBuilder WithTentacleExe(string tentacleExe) + { + this.tentacleExe = tentacleExe; + return this; + } + + public TentacleInstanceBuilder WithName(string name) + { + this.name = name; + return this; + } + // An instance with no name has no registry entry, so commands can only reach it through its configuration file. public TentacleInstanceBuilder UnnamedInstanceAddressedOnlyByConfig() { - unnamed = true; + name = null; + return this; + } + + public TentacleInstanceBuilder WithHomeDirectory(TemporaryDirectory home) + { + this.home = home; + return this; + } + + // Registers the instance in the machine's real registry rather than one in its home directory. + public TentacleInstanceBuilder UseDefaultMachineConfigurationHomeDirectory() + { + useDefaultMachineConfigurationHomeDirectory = true; + return this; + } + + public TentacleInstanceBuilder WithEnvironmentVariable(string name, string? value) + { + environmentVariables[name] = value!; + return this; + } + + public TentacleInstanceBuilder WithCertificate(string pfxPath, string thumbprint) + { + certificate = (pfxPath, thumbprint); return this; } @@ -41,13 +86,33 @@ public TentacleInstanceBuilder WithNewCertificate() return this; } + public ListeningRunningTentacleBuilder RunAsListeningTentacle(string serverThumbprint) + => new(serverThumbprint, this); + + public PollingRunningTentacleBuilder RunAsPollingTentacle(int pollingPort, string serverThumbprint) + => new(pollingPort, serverThumbprint, this); + public async Task Build(ILogger logger, CancellationToken cancellationToken) { - var tentacleExe = tentacleVersion is null + var exe = tentacleExe ?? (tentacleVersion is null ? TentacleExeFinder.FindTentacleExe() - : await TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken); + : await TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken)); + var instanceHome = home ?? new TemporaryDirectory(); + var environment = new Dictionary + { + [EnvironmentVariables.TentacleInstancesDataDirectory] = Path.Combine(instanceHome.DirectoryPath, "data") + }; + if (!useDefaultMachineConfigurationHomeDirectory) + { + environment[EnvironmentVariables.TentacleMachineConfigurationHomeDirectory] = Path.Combine(instanceHome.DirectoryPath, "Octopus", "Tentacle", "Instances"); + } - var instance = new TentacleInstance(tentacleExe, unnamed ? null : "Tentacle", cancellationToken); + foreach (var environmentVariable in environmentVariables) + { + environment[environmentVariable.Key] = environmentVariable.Value; + } + + var instance = new TentacleInstance(instanceHome, exe, name, thumbprint: null, environment, cancellationToken); if (instance.Name is null) { await File.WriteAllTextAsync(instance.ConfigurationFile, "", cancellationToken); @@ -57,42 +122,55 @@ public async Task Build(ILogger logger, CancellationToken canc await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); } + if (certificate != null) + { + await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "import-certificate", $"--from-file={certificate.Value.PfxPath}", "--instance", instance.Name!); + return instance.WithThumbprint(certificate.Value.Thumbprint); + } + if (withNewCertificate) { await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "new-certificate"); + return instance.WithThumbprint(await instance.ShowThumbprint()); } return instance; } } - // Everything the instance owns - its registry entry, configuration and data - lives in a temporary home directory. + // Everything the instance owns - its registry entry, configuration and data - lives in its home directory. public class TentacleInstance : IDisposable { readonly TemporaryDirectory home; readonly string tentacleExe; + readonly IReadOnlyDictionary environmentVariables; readonly CancellationToken cancellationToken; - internal TentacleInstance(string tentacleExe, string? name, CancellationToken cancellationToken) : this(new TemporaryDirectory(), tentacleExe, name, cancellationToken) - { - } - - TentacleInstance(TemporaryDirectory home, string tentacleExe, string? name, CancellationToken cancellationToken) + internal TentacleInstance(TemporaryDirectory home, string tentacleExe, string? name, string? thumbprint, IReadOnlyDictionary environmentVariables, CancellationToken cancellationToken) { this.home = home; this.tentacleExe = tentacleExe; Name = name; + Thumbprint = thumbprint; + this.environmentVariables = environmentVariables; this.cancellationToken = cancellationToken; } public string? Name { get; } - public string ConfigurationFile => Path.Combine(home.DirectoryPath, "tentacle.config"); + public string? Thumbprint { get; } + internal TemporaryDirectory Home => home; + internal string TentacleExe => tentacleExe; + internal IReadOnlyDictionary EnvironmentVariables => environmentVariables; + public string ConfigurationFile => Path.Combine(home.DirectoryPath, (Name ?? "Tentacle") + ".cfg"); public string DataDirectory => Path.Combine(home.DirectoryPath, "data"); public string ConfigurationEncryptionKeyFile => Path.Combine(DataDirectory, Name!, "keys", ConfigurationEncryptionKey.KeyFileName); // The same instance, as if the current Tentacle had been installed over it. public TentacleInstance WithCurrentTentacleExe() - => new(home, TentacleExeFinder.FindTentacleExe(), Name, cancellationToken); + => new(home, TentacleExeFinder.FindTentacleExe(), Name, Thumbprint, environmentVariables, cancellationToken); + + internal TentacleInstance WithThumbprint(string thumbprint) + => new(home, tentacleExe, Name, thumbprint, environmentVariables, cancellationToken); public string CertificateAsStoredInTheConfigurationFile() => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; @@ -109,9 +187,8 @@ public async Task ExecuteTentacleCommand(CommandResultVal => await Cli.Wrap(tentacleExe) .WithArguments(arguments) .WithValidation(validation) - .WithEnvironmentVariables(e => e - .Set(EnvironmentVariables.TentacleMachineConfigurationHomeDirectory, Path.Combine(home.DirectoryPath, "home")) - .Set(EnvironmentVariables.TentacleInstancesDataDirectory, DataDirectory)) + .WithWorkingDirectory(home.DirectoryPath) + .WithEnvironmentVariables(environmentVariables) .ExecuteBufferedAsync(cancellationToken); public void Dispose() => home.Dispose(); From d324aba4a60b68fa1cd22fb2094aab2b07ea1ff5 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 17:36:19 +1100 Subject: [PATCH 064/124] Test the upgrade by restarting a running version 14 Tentacle as the current Tentacle --- .../ConfigurationEncryptionUpgradeTests.cs | 12 +++--- .../Support/RunningTentacle.cs | 39 ++++++++++--------- .../Support/RunningTentacleBuilder.cs | 16 +++----- 3 files changed, 32 insertions(+), 35 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 85e6be5b4..ffc18b8a0 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -108,18 +108,18 @@ public async Task WhenTentacleKeyFileIsDeleted_AndANewCertificateIsCreated_ThenI public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheCurrentTentacleStarts_ThenTheCertificateIsReEncrypted() { // Arrange - using var instance = await new TentacleInstanceBuilder() + await using var runningTentacle = await new TentacleInstanceBuilder() .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) - .WithNewCertificate() + .RunAsListeningTentacle(TestCertificates.ServerPublicThumbprint) .Build(Logger, CancellationToken); + runningTentacle.Instance.CertificateAsStoredInTheConfigurationFile().Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); // Act - await using var runningTentacle = await new ListeningRunningTentacleBuilder(TestCertificates.ServerPublicThumbprint, instance.WithCurrentTentacleExe()) - .Build(Logger, CancellationToken); + await runningTentacle.RestartWithCurrentTentacle(CancellationToken); // Assert - instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); - (await instance.WithCurrentTentacleExe().ShowThumbprint()).Should().Be(instance.Thumbprint, "the upgraded certificate must still decrypt to the same certificate"); + runningTentacle.Instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); + (await runningTentacle.Instance.ShowThumbprint()).Should().Be(runningTentacle.Thumbprint, "the upgraded certificate must still decrypt to the same certificate"); } [Test] diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs index a33e06253..d7c806734 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs @@ -15,18 +15,15 @@ public class RunningTentacle : IAsyncDisposable private readonly TemporaryDirectory? temporaryDirectoryToDelete; private CancellationTokenSource? cancellationTokenSource; private Task? runningTentacleTask; - private readonly Func> startTentacleFunction; - private readonly Func deleteInstanceFunction; + private readonly Func> startTentacleFunction; + private readonly Func deleteInstanceFunction; private ILogger logger; - public RunningTentacle(FileInfo tentacleExe, + public RunningTentacle(TentacleInstance instance, TemporaryDirectory? temporaryDirectoryToDelete, - Func> startTentacleFunction, - string thumbprint, - string instanceName, - string homeDirectory, + Func> startTentacleFunction, string applicationDirectory, - Func deleteInstanceFunction, + Func deleteInstanceFunction, IReadOnlyDictionary runTentacleEnvironmentVariables, ILogger logger) { @@ -34,10 +31,7 @@ public RunningTentacle(FileInfo tentacleExe, this.temporaryDirectoryToDelete = temporaryDirectoryToDelete; this.deleteInstanceFunction = deleteInstanceFunction; - TentacleExe = tentacleExe; - Thumbprint = thumbprint; - InstanceName = instanceName; - HomeDirectory = homeDirectory; + Instance = instance; ApplicationDirectory = applicationDirectory; RunTentacleEnvironmentVariables = runTentacleEnvironmentVariables; @@ -45,12 +39,13 @@ public RunningTentacle(FileInfo tentacleExe, } public Uri ServiceUri { get; private set; } - public string InstanceName { get; } - public string Thumbprint { get; } - public string HomeDirectory { get; } + public TentacleInstance Instance { get; private set; } + public string InstanceName => Instance.Name!; + public string Thumbprint => Instance.Thumbprint!; + public string HomeDirectory => Instance.Home.DirectoryPath; public string ApplicationDirectory { get; } public IReadOnlyDictionary RunTentacleEnvironmentVariables { get; } - public FileInfo TentacleExe { get; } + public FileInfo TentacleExe => new(Instance.TentacleExe); public string LogFilePath => Path.Combine(HomeDirectory, "Logs", "OctopusTentacle.txt"); public async Task Start(CancellationToken cancellationToken) @@ -62,7 +57,7 @@ public async Task Start(CancellationToken cancellationToken) cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - var (rtt, serviceUri) = await startTentacleFunction(cancellationTokenSource.Token); + var (rtt, serviceUri) = await startTentacleFunction(Instance, cancellationTokenSource.Token); runningTentacleTask = rtt; ServiceUri = serviceUri; @@ -94,6 +89,14 @@ public async Task Restart(CancellationToken cancellationToken) await Start(cancellationToken); } + // As if the current Tentacle had been installed over the running one. + public async Task RestartWithCurrentTentacle(CancellationToken cancellationToken) + { + await Stop(cancellationToken); + Instance = Instance.WithCurrentTentacleExe(); + await Start(cancellationToken); + } + public async ValueTask DisposeAsync() { using var disposeCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); @@ -108,7 +111,7 @@ public async ValueTask DisposeAsync() } logger.Information("Starting deleteInstanceFunction"); - await deleteInstanceFunction(cancellationToken); + await deleteInstanceFunction(Instance, cancellationToken); logger.Information("Starting temporaryDirectory.Dispose"); temporaryDirectoryToDelete?.Dispose(); diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs index a54da82ff..36772f7a4 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs @@ -154,22 +154,16 @@ protected async Task StartTentacle( CancellationToken cancellationToken) { var log = new SerilogLoggerBuilder().Build().ForContext(); - var tentacleExe = instance.TentacleExe; - var instanceName = instance.Name!; - var tempDirectory = instance.Home; var ownsInstance = givenInstance == null; var runningTentacle = new RunningTentacle( - new FileInfo(tentacleExe), - ownsInstance ? tempDirectory : null, - startTentacleFunction: ct => RunTentacle(serviceUri, tentacleExe, instanceName, tempDirectory, log, ct), - instance.Thumbprint!, - instanceName, - tempDirectory.DirectoryPath, + instance, + ownsInstance ? instance.Home : null, + startTentacleFunction: (i, ct) => RunTentacle(serviceUri, i.TentacleExe, i.Name!, i.Home, log, ct), applicationDirectory, deleteInstanceFunction: ownsInstance - ? ct => DeleteInstanceIgnoringFailure(installAsService, tentacleExe, instanceName, tempDirectory, logger, ct) - : _ => Task.CompletedTask, + ? (i, ct) => DeleteInstanceIgnoringFailure(installAsService, i.TentacleExe, i.Name!, i.Home, logger, ct) + : (_, _) => Task.CompletedTask, runTentacleEnvironmentVariables, logger); From f082eecc05a0cf5cc0f47f729213028eece8d4b8 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 17:38:36 +1100 Subject: [PATCH 065/124] Rename RestartWithCurrentTentacle to StopAndStartWithCurrentVersionOfTentacle --- .../Configuration/ConfigurationEncryptionUpgradeTests.cs | 2 +- .../Support/RunningTentacle.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index ffc18b8a0..4ee2b9e33 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -115,7 +115,7 @@ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheCurrentTentac runningTentacle.Instance.CertificateAsStoredInTheConfigurationFile().Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); // Act - await runningTentacle.RestartWithCurrentTentacle(CancellationToken); + await runningTentacle.StopAndStartWithCurrentVersionOfTentacle(CancellationToken); // Assert runningTentacle.Instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs index d7c806734..2a9eade9e 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacle.cs @@ -90,7 +90,7 @@ public async Task Restart(CancellationToken cancellationToken) } // As if the current Tentacle had been installed over the running one. - public async Task RestartWithCurrentTentacle(CancellationToken cancellationToken) + public async Task StopAndStartWithCurrentVersionOfTentacle(CancellationToken cancellationToken) { await Stop(cancellationToken); Instance = Instance.WithCurrentTentacleExe(); From e19480683a4695dca52173b4a08595ee1e77f965 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Mon, 23 Nov 2026 21:17:07 +1100 Subject: [PATCH 066/124] Assert encryption key failures are about the missing key --- .../ConfigurationEncryptionUpgradeTests.cs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 4ee2b9e33..c7c151fbb 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -1,5 +1,4 @@ #if NET -using System; using System.IO; using System.Runtime.Versioning; using System.Threading.Tasks; @@ -101,6 +100,7 @@ public async Task WhenTentacleKeyFileIsDeleted_AndANewCertificateIsCreated_ThenI // Assert var output = newCertificate.StandardOutput + newCertificate.StandardError; newCertificate.ExitCode.Should().NotBe(0, output); + output.Should().Contain("configuration encryption key, which is not available", "the failure should be about the missing key, not something else"); instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedWithTheKey); } @@ -133,14 +133,12 @@ public async Task WhenTentacleKeyFileIsDeleted_AndTheCurrentTentacleStarts_ThenT File.Delete(instance.ConfigurationEncryptionKeyFile); // Act - Func start = async () => - { - await using var runningTentacle = await new ListeningRunningTentacleBuilder(TestCertificates.ServerPublicThumbprint, instance) - .Build(Logger, CancellationToken); - }; + var agent = await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "agent"); // Assert - await start.Should().ThrowAsync("the certificate cannot be decrypted without its key"); + var output = agent.StandardOutput + agent.StandardError; + agent.ExitCode.Should().NotBe(0, output); + output.Should().Contain(instance.ConfigurationEncryptionKeyFile, "the certificate cannot be decrypted without its key"); instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedWithTheKey); } } From 4aab95f772e7b7972de4a14eaf29ffbb24553034 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 09:04:31 +1100 Subject: [PATCH 067/124] Align the Docker test setup with #1363 --- .../LinuxTentacleConfigEncryptionTests.cs | 8 +- .../Setup/DockerCli.cs | 2 +- .../Setup/DockerContainer.cs | 4 + .../Setup/TentacleContainer.cs | 29 ++-- .../Setup/TentacleContainerBuilder.cs | 132 ++++++++++++++---- 5 files changed, 132 insertions(+), 43 deletions(-) diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs index 09a99eb6f..f9d698c74 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs @@ -80,12 +80,12 @@ public async Task TheContainerRefusesToStartWhenOnlyTheConfigurationIsPersisted( await using var server = await new FakeOctopusServerBuilder().Build(); // Act - await using var tentacle = await new TentacleContainerBuilder(server) + var (exitCode, logs) = await new TentacleContainerBuilder(server) .WithVolume(config, "/etc/octopus") - .WithTentacleThatRefusesToStart() - .Build(); + .RunUntilExit(); // Assert - (await tentacle.Docker.GetLogs()).Should().Contain("/var/lib/octopus/tentacle is not"); + exitCode.Should().NotBe(0, logs); + logs.Should().Contain("/var/lib/octopus/tentacle is not"); } } diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs index 1122f1ed6..a7e9b3930 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerCli.cs @@ -49,7 +49,7 @@ public static async Task Logs(string container) } } - static readonly string[] SecretVariables = { "ServerApiKey", "BearerToken", "ServerPassword" }; + static readonly string[] SecretVariables = { "ServerApiKey", "BearerToken", "ServerPassword", "TentacleCertificateBase64" }; static string Redact(string argument) { diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerContainer.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerContainer.cs index 00d19c571..3be95c8c3 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerContainer.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/DockerContainer.cs @@ -81,6 +81,10 @@ public async Task DescribeState() public Task GetLogs() => DockerCli.Logs(Id); + /// Runs a command in the running container, as `docker exec` does, and returns its output. + public Task Exec(IEnumerable command, CancellationToken cancellationToken) + => DockerCli.Run(new[] { "exec", Id }.Concat(command), cancellationToken); + /// Restarts the container as `docker restart` does: SIGTERM, then SIGKILL after the grace period. public Task Restart(TimeSpan gracePeriod, CancellationToken cancellationToken) => DockerCli.Run(new[] { "restart", "--time", ((int)gracePeriod.TotalSeconds).ToString(), Id }, cancellationToken); diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs index 3fb888ca6..2f6526275 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs @@ -30,8 +30,8 @@ public sealed class TentacleContainer : IAsyncDisposable /// How Tentacle containers address the machine running the tests. public const string DockerHost = "host.docker.internal"; - /// The credentials the image's entrypoint uses to register, which it must not pass on to the agent. - static readonly string[] RegistrationCredentialVariables = { "ServerApiKey", "BearerToken", "ServerUsername", "ServerPassword" }; + /// The secrets the image's entrypoint uses to register and configure Tentacle, which it must not pass on to the agent. + static readonly string[] RegistrationCredentialVariables = { "ServerApiKey", "BearerToken", "ServerUsername", "ServerPassword", "TentacleCertificateBase64" }; // Emulating an amd64 image on an arm64 machine makes start-up slow; be generous. static readonly TimeSpan RegistrationTimeout = TimeSpan.FromMinutes(5); @@ -41,8 +41,12 @@ public sealed class TentacleContainer : IAsyncDisposable // How often to check the container is still running while waiting on it. static readonly TimeSpan ContainerCheckInterval = TimeSpan.FromSeconds(2); + /// What configure-tentacle.sh prints when it starts without registering, so the Tentacle can be added by hand. + static readonly Regex ManualRegistrationThumbprint = new("Add it in Octopus as a listening Tentacle with thumbprint (?[0-9A-Fa-f]{40})"); + readonly FakeOctopusServer server; RegisteredMachine? registeredMachine; + string? unregisteredThumbprint; TentacleClient? tentacleClient; internal TentacleContainer(DockerContainer docker, FakeOctopusServer server, string machineName, TentacleCommunicationStyle communicationStyle) @@ -60,6 +64,9 @@ internal TentacleContainer(DockerContainer docker, FakeOctopusServer server, str public RegisteredMachine RegisteredMachine => registeredMachine ?? throw new InvalidOperationException("The Tentacle has not registered"); public TentacleClient TentacleClient => tentacleClient ?? throw new InvalidOperationException("The TentacleClient has not been built"); + /// The Tentacle's thumbprint: the one it registered with, or the one it printed if it did not register. + public string Thumbprint => registeredMachine?.Thumbprint ?? unregisteredThumbprint ?? throw new InvalidOperationException("The Tentacle has not started"); + internal async Task Start(Task registration, CancellationToken cancellationToken) { registeredMachine = await WaitForRegistration(registration); @@ -68,13 +75,17 @@ internal async Task Start(Task registration, CancellationToke tentacleClient = await BuildTentacleClient(cancellationToken); } - internal async Task WaitForRefusalToStart() + /// + /// Waits for a Tentacle started with ServerThumbprint to print its thumbprint, which stands in for registering: it + /// is what a user would add to Octopus by hand. + /// + internal async Task StartUnregistered(CancellationToken cancellationToken) { - using var timeout = new CancellationTokenSource(RegistrationTimeout); - if (await WaitForContainerToStop(timeout.Token) is null) - { - throw new TimeoutException($"The Tentacle container was expected to refuse to start, but is still {await Docker.DescribeState()} after {RegistrationTimeout.TotalSeconds:0} seconds."); - } + var match = await WaitForLogMatch(ManualRegistrationThumbprint, RegistrationTimeout); + unregisteredThumbprint = match.Groups["thumbprint"].Value; + // The agent starts after configuration; if it dies straight away, say so rather than fail on a missing port. + await ThrowIfStopped("after configuring"); + tentacleClient = await BuildTentacleClient(cancellationToken); } async Task WaitForRegistration(Task registration) @@ -109,7 +120,7 @@ async Task BuildTentacleClient(CancellationToken cancellationTok ? new Uri($"https://localhost:{await Docker.GetPublishedPort(ListeningPort, cancellationToken)}/") : new Uri(RegisteredMachine.Uri!); - return TestServerHalibut.BuildTentacleClient(uri, RegisteredMachine.Thumbprint, server.Halibut, _ => { }); + return TestServerHalibut.BuildTentacleClient(uri, Thumbprint, server.Halibut, _ => { }); } /// diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs index 6d4a1dd93..ddc5eb1f4 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs @@ -16,13 +16,18 @@ public class TentacleContainerBuilder // Docker commands, including pulling the image, take longer than registration does. static readonly TimeSpan DockerCommandTimeout = TimeSpan.FromMinutes(10); + // How often to check whether a container expected to exit has. + static readonly TimeSpan ContainerCheckInterval = TimeSpan.FromSeconds(2); + readonly FakeOctopusServer server; TentacleCommunicationStyle communicationStyle = TentacleCommunicationStyle.Listening; string? workerPoolName; Dictionary credentials = new() { ["ServerApiKey"] = ApiKey }; + string? serverThumbprint; + string? certificateBase64; + readonly Dictionary extraEnvironment = new(); readonly List volumeMounts = new(); RegisteredMachine? alreadyRegistered; - bool refusesToStart; public TentacleContainerBuilder(FakeOctopusServer server) { @@ -54,6 +59,30 @@ public TentacleContainerBuilder WithUsernameAndPassword(string username, string return this; } + /// + /// Starts the Tentacle with ServerThumbprint, so it trusts that server and does not register with it. It still + /// listens; the fake server's HalibutRuntime connects to it as Octopus Server would once it is added by hand. + /// + public TentacleContainerBuilder WithoutRegistration(string serverThumbprint) + { + this.serverThumbprint = serverThumbprint; + return this; + } + + /// Imports this certificate with TentacleCertificateBase64 rather than letting Tentacle create one. + public TentacleContainerBuilder WithCertificate(string certificateBase64) + { + this.certificateBase64 = certificateBase64; + return this; + } + + /// Sets an environment variable after the builder's own, so it can add to or override them. + public TentacleContainerBuilder WithEnvironmentVariable(string name, string value) + { + extraEnvironment[name] = value; + return this; + } + public TentacleContainerBuilder WithVolume(DockerVolume volume, string containerPath) { volumeMounts.Add(volume.MountAt(containerPath)); @@ -70,33 +99,31 @@ public TentacleContainerBuilder WithStartingAlreadyConfiguredTentacle(Registered return this; } - /// Expects the entrypoint to exit before configuring, so waits for it to stop. - public TentacleContainerBuilder WithTentacleThatRefusesToStart() - { - refusesToStart = true; - return this; - } - public async Task Build() { + if (serverThumbprint is not null && communicationStyle == TentacleCommunicationStyle.Polling) + { + throw new InvalidOperationException("A Tentacle that does not register can only listen"); + } + using var cancellationTokenSource = new CancellationTokenSource(DockerCommandTimeout); var cancellationToken = cancellationTokenSource.Token; - var machineName = $"tentacle-docker-test-{communicationStyle}-{Guid.NewGuid():N}"[..48].ToLowerInvariant(); + var machineName = NewMachineName(); var image = TentacleImage.Resolve(); - TestContext.Out.WriteLine($"Testing {image} as a {communicationStyle} Tentacle named {machineName}"); + TestContext.Out.WriteLine($"Testing {image} as a {communicationStyle} Tentacle named {machineName}{(serverThumbprint is null ? "" : " that does not register")}"); - var registration = alreadyRegistered is null - ? server.WaitForRegistration(FakeOctopusServerBuilder.SpaceName, machineName) - : Task.FromResult(alreadyRegistered); + var registration = serverThumbprint is not null ? null + : alreadyRegistered is not null ? Task.FromResult(alreadyRegistered) + : server.WaitForRegistration(FakeOctopusServerBuilder.SpaceName, machineName); var docker = await DockerContainer.Run(image, machineName, RunOptions(machineName), cancellationToken); var tentacle = new TentacleContainer(docker, server, machineName, communicationStyle); try { - if (refusesToStart) + if (registration is null) { - await tentacle.WaitForRefusalToStart(); + await tentacle.StartUnregistered(cancellationToken); } else { @@ -112,6 +139,34 @@ public async Task Build() } } + /// + /// Starts a container expected to fail its configuration, and returns its exit code and logs once it has stopped. + /// The container is removed before returning. + /// + public async Task<(int ExitCode, string Logs)> RunUntilExit() + { + using var cancellationTokenSource = new CancellationTokenSource(DockerCommandTimeout); + var cancellationToken = cancellationTokenSource.Token; + + var machineName = NewMachineName(); + var image = TentacleImage.Resolve(); + TestContext.Out.WriteLine($"Running {image} as {machineName}, expecting it to exit"); + + await using var docker = await DockerContainer.Run(image, machineName, RunOptions(machineName), cancellationToken); + while (await docker.GetExitDescription(cancellationToken) is null) + { + await Task.Delay(ContainerCheckInterval, cancellationToken); + } + + var logs = await docker.GetLogs(); + TestContext.Out.WriteLine($"---- docker logs {docker.Name} ----"); + TestContext.Out.WriteLine(logs); + + return (await docker.GetExitCode(cancellationToken), logs); + } + + string NewMachineName() => $"tentacle-docker-test-{communicationStyle}-{Guid.NewGuid():N}"[..48].ToLowerInvariant(); + IEnumerable RunOptions(string machineName) { var options = new List @@ -147,30 +202,49 @@ Dictionary EnvironmentVariables(string machineName) ["ACCEPT_EULA"] = "Y", // Docker-in-Docker needs --privileged; the dind payload is covered by the image smoke tests. ["DISABLE_DIND"] = "Y", - ["ServerUrl"] = $"http://{TentacleContainer.DockerHost}:{server.Port}", - ["Space"] = FakeOctopusServerBuilder.SpaceName, - ["TargetName"] = machineName + ["Space"] = FakeOctopusServerBuilder.SpaceName }; - foreach (var (key, value) in credentials) + if (serverThumbprint is not null) { - environment[key] = value; + // configure-tentacle.sh rejects registration and polling settings alongside ServerThumbprint. + environment["ServerThumbprint"] = serverThumbprint; } - - if (workerPoolName is null) + else { - environment["TargetEnvironment"] = FakeOctopusServerBuilder.EnvironmentName; - environment["TargetRole"] = Role; + environment["ServerUrl"] = $"http://{TentacleContainer.DockerHost}:{server.Port}"; + environment["TargetName"] = machineName; + + foreach (var (key, value) in credentials) + { + environment[key] = value; + } + + if (workerPoolName is null) + { + environment["TargetEnvironment"] = FakeOctopusServerBuilder.EnvironmentName; + environment["TargetRole"] = Role; + } + else + { + // configure-tentacle.sh rejects environments and roles alongside a worker pool. + environment["TargetWorkerPool"] = workerPoolName; + } + + if (communicationStyle == TentacleCommunicationStyle.Polling) + { + environment["ServerPort"] = server.PollingPort.ToString(); + } } - else + + if (certificateBase64 is not null) { - // configure-tentacle.sh rejects environments and roles alongside a worker pool. - environment["TargetWorkerPool"] = workerPoolName; + environment["TentacleCertificateBase64"] = certificateBase64; } - if (communicationStyle == TentacleCommunicationStyle.Polling) + foreach (var (key, value) in extraEnvironment) { - environment["ServerPort"] = server.PollingPort.ToString(); + environment[key] = value; } return environment; From b993f0f917a40f6325356740d66c7c9be3ccb644 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 09:09:41 +1100 Subject: [PATCH 068/124] Retry Tentacle commands that fail while another test registers an instance --- .../Support/TentacleInstanceBuilder.cs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index 2e0670bb1..42a775488 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using CliWrap; using CliWrap.Buffered; +using CliWrap.Exceptions; using Octopus.Tentacle.CommonTestUtils; using Octopus.Tentacle.Configuration; using Octopus.Tentacle.Configuration.Crypto; @@ -183,13 +184,15 @@ public async Task ExecuteTentacleCommandOnTheInstance(Com ? await ExecuteTentacleCommand(validation, command, "--config", ConfigurationFile) : await ExecuteTentacleCommand(validation, command, "--instance", Name); + // Older Tentacles share the machine's instance registry, so a command can fail while another test registers an instance. public async Task ExecuteTentacleCommand(CommandResultValidation validation, params string[] arguments) - => await Cli.Wrap(tentacleExe) - .WithArguments(arguments) - .WithValidation(validation) - .WithWorkingDirectory(home.DirectoryPath) - .WithEnvironmentVariables(environmentVariables) - .ExecuteBufferedAsync(cancellationToken); + => await RetryHelper.RetryAsync( + async () => await Cli.Wrap(tentacleExe) + .WithArguments(arguments) + .WithValidation(validation) + .WithWorkingDirectory(home.DirectoryPath) + .WithEnvironmentVariables(environmentVariables) + .ExecuteBufferedAsync(cancellationToken)); public void Dispose() => home.Dispose(); } From d860c16b7f4cc96b35c5b73f5588e7c9b1dd7302 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 09:13:56 +1100 Subject: [PATCH 069/124] Download each old Tentacle into its own temporary directory --- .../Support/TentacleInstanceBuilder.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index 42a775488..867ddb888 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -95,9 +95,10 @@ public PollingRunningTentacleBuilder RunAsPollingTentacle(int pollingPort, strin public async Task Build(ILogger logger, CancellationToken cancellationToken) { + using var download = new TemporaryDirectory(); var exe = tentacleExe ?? (tentacleVersion is null ? TentacleExeFinder.FindTentacleExe() - : await TentacleFetcher.GetTentacleVersion(Path.GetTempPath(), tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken)); + : await TentacleFetcher.GetTentacleVersion(download.DirectoryPath, tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken)); var instanceHome = home ?? new TemporaryDirectory(); var environment = new Dictionary { From 78bc03baa57d87122b4bd147710e18ed58c39439 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 09:15:01 +1100 Subject: [PATCH 070/124] Import certificates into unnamed instances through their configuration file --- .../Support/TentacleInstanceBuilder.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index 867ddb888..43950d9b4 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -126,7 +126,7 @@ public async Task Build(ILogger logger, CancellationToken canc if (certificate != null) { - await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "import-certificate", $"--from-file={certificate.Value.PfxPath}", "--instance", instance.Name!); + await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "import-certificate", $"--from-file={certificate.Value.PfxPath}"); return instance.WithThumbprint(certificate.Value.Thumbprint); } @@ -180,10 +180,11 @@ public string CertificateAsStoredInTheConfigurationFile() public async Task ShowThumbprint() => (await ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "show-thumbprint")).StandardOutput.Trim(); - public async Task ExecuteTentacleCommandOnTheInstance(CommandResultValidation validation, string command) - => Name is null - ? await ExecuteTentacleCommand(validation, command, "--config", ConfigurationFile) - : await ExecuteTentacleCommand(validation, command, "--instance", Name); + public async Task ExecuteTentacleCommandOnTheInstance(CommandResultValidation validation, string command, params string[] arguments) + => await ExecuteTentacleCommand(validation, new[] { command } + .Concat(arguments) + .Concat(Name is null ? new[] { "--config", ConfigurationFile } : new[] { "--instance", Name }) + .ToArray()); // Older Tentacles share the machine's instance registry, so a command can fail while another test registers an instance. public async Task ExecuteTentacleCommand(CommandResultValidation validation, params string[] arguments) From ed8ba4b4b2e2a779c17b900274472ca21c65c3a9 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 09:17:44 +1100 Subject: [PATCH 071/124] Reject running a caller-built instance as a service --- .../Support/RunningTentacleBuilder.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs index 36772f7a4..ec6182311 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs @@ -134,6 +134,11 @@ protected void WithWritableTentacleConfiguration(string configFilePath, Action Date: Tue, 24 Nov 2026 09:19:55 +1100 Subject: [PATCH 072/124] Keep the name and certificate a caller chose when running an instance --- .../Support/RunningTentacleBuilder.cs | 4 +--- .../Support/TentacleInstanceBuilder.cs | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs index ec6182311..d4fa270a9 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/RunningTentacleBuilder.cs @@ -54,9 +54,7 @@ public static Dictionary BuildDefaultTentacleEnvironmentVariable // Builds the instance, so the running Tentacle owns it and deletes it when disposed. protected RunningTentacleBuilder(TentacleInstanceBuilder instanceBuilder) { - this.instanceBuilder = instanceBuilder - .WithName(InstanceNameGenerator()) - .WithCertificate(TestCertificates.TentaclePfxPath, TestCertificates.TentaclePublicThumbprint); + this.instanceBuilder = instanceBuilder.WithDefaultsForRunning(InstanceNameGenerator(), TestCertificates.TentaclePfxPath, TestCertificates.TentaclePublicThumbprint); } // Runs an instance the caller built, so the caller owns it. diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index 43950d9b4..9f952b465 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -23,6 +23,7 @@ public class TentacleInstanceBuilder Version? tentacleVersion = TentacleVersions.Current; string? tentacleExe; string? name = "Tentacle"; + bool nameChosen; TemporaryDirectory? home; bool useDefaultMachineConfigurationHomeDirectory; readonly Dictionary environmentVariables = new(); @@ -46,6 +47,7 @@ public TentacleInstanceBuilder WithTentacleExe(string tentacleExe) public TentacleInstanceBuilder WithName(string name) { this.name = name; + nameChosen = true; return this; } @@ -53,6 +55,7 @@ public TentacleInstanceBuilder WithName(string name) public TentacleInstanceBuilder UnnamedInstanceAddressedOnlyByConfig() { name = null; + nameChosen = true; return this; } @@ -87,6 +90,26 @@ public TentacleInstanceBuilder WithNewCertificate() return this; } + // Fills in what a running Tentacle needs, keeping anything the caller chose. + internal TentacleInstanceBuilder WithDefaultsForRunning(string defaultName, string pfxPath, string thumbprint) + { + if (!nameChosen) + { + name = defaultName; + } + else if (name == null) + { + throw new InvalidOperationException("An unnamed instance cannot be run, the agent is started with --instance"); + } + + if (certificate == null && !withNewCertificate) + { + certificate = (pfxPath, thumbprint); + } + + return this; + } + public ListeningRunningTentacleBuilder RunAsListeningTentacle(string serverThumbprint) => new(serverThumbprint, this); From 88c7f0755d2958cae74bd9110c79b3ae21425d4d Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 09:22:37 +1100 Subject: [PATCH 073/124] Pass cancellation tokens to Tentacle instance commands instead of storing one --- .../ConfigurationEncryptionUpgradeTests.cs | 16 +++++------ .../Support/TentacleInstanceBuilder.cs | 28 +++++++++---------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index c7c151fbb..077bfbf1f 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -26,17 +26,17 @@ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndUpgradeConfigura .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) .WithNewCertificate() .Build(Logger, CancellationToken); - var thumbprintBeforeUpgrade = await instance.ShowThumbprint(); + var thumbprintBeforeUpgrade = await instance.ShowThumbprint(CancellationToken); instance.CertificateAsStoredInTheConfigurationFile().Should().NotStartWith(EncryptedWithItsOwnKey, "version 14 encrypts with a key derived from the machine id"); // Act var upgradedInstance = instance.WithCurrentTentacleExe(); - await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption"); + await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption", CancellationToken); // Assert instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); File.Exists(instance.ConfigurationEncryptionKeyFile).Should().BeTrue(); - (await upgradedInstance.ShowThumbprint()).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); + (await upgradedInstance.ShowThumbprint(CancellationToken)).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate"); } [Test] @@ -52,7 +52,7 @@ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheNewKeyCannotB // Act var upgradedInstance = instance.WithCurrentTentacleExe(); - var upgrade = await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "upgrade-configuration-encryption"); + var upgrade = await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "upgrade-configuration-encryption", CancellationToken); // Assert var output = upgrade.StandardOutput + upgrade.StandardError; @@ -74,7 +74,7 @@ public async Task WhenTentacleInstanceIsUnnamed_AndUpgradeConfigurationEncryptio // Act var upgradedInstance = instance.WithCurrentTentacleExe(); - var upgrade = await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "upgrade-configuration-encryption"); + var upgrade = await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "upgrade-configuration-encryption", CancellationToken); // Assert var output = upgrade.StandardOutput + upgrade.StandardError; @@ -95,7 +95,7 @@ public async Task WhenTentacleKeyFileIsDeleted_AndANewCertificateIsCreated_ThenI File.Delete(instance.ConfigurationEncryptionKeyFile); // Act - var newCertificate = await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "new-certificate"); + var newCertificate = await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "new-certificate", CancellationToken); // Assert var output = newCertificate.StandardOutput + newCertificate.StandardError; @@ -119,7 +119,7 @@ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheCurrentTentac // Assert runningTentacle.Instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey); - (await runningTentacle.Instance.ShowThumbprint()).Should().Be(runningTentacle.Thumbprint, "the upgraded certificate must still decrypt to the same certificate"); + (await runningTentacle.Instance.ShowThumbprint(CancellationToken)).Should().Be(runningTentacle.Thumbprint, "the upgraded certificate must still decrypt to the same certificate"); } [Test] @@ -133,7 +133,7 @@ public async Task WhenTentacleKeyFileIsDeleted_AndTheCurrentTentacleStarts_ThenT File.Delete(instance.ConfigurationEncryptionKeyFile); // Act - var agent = await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "agent"); + var agent = await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "agent", CancellationToken); // Assert var output = agent.StandardOutput + agent.StandardError; diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index 9f952b465..d0ced3f41 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -137,26 +137,26 @@ public async Task Build(ILogger logger, CancellationToken canc environment[environmentVariable.Key] = environmentVariable.Value; } - var instance = new TentacleInstance(instanceHome, exe, name, thumbprint: null, environment, cancellationToken); + var instance = new TentacleInstance(instanceHome, exe, name, thumbprint: null, environment); if (instance.Name is null) { await File.WriteAllTextAsync(instance.ConfigurationFile, "", cancellationToken); } else { - await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, "create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); + await instance.ExecuteTentacleCommand(CommandResultValidation.ZeroExitCode, cancellationToken, "create-instance", "--instance", instance.Name, "--config", instance.ConfigurationFile); } if (certificate != null) { - await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "import-certificate", $"--from-file={certificate.Value.PfxPath}"); + await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "import-certificate", cancellationToken, $"--from-file={certificate.Value.PfxPath}"); return instance.WithThumbprint(certificate.Value.Thumbprint); } if (withNewCertificate) { - await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "new-certificate"); - return instance.WithThumbprint(await instance.ShowThumbprint()); + await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "new-certificate", cancellationToken); + return instance.WithThumbprint(await instance.ShowThumbprint(cancellationToken)); } return instance; @@ -169,16 +169,14 @@ public class TentacleInstance : IDisposable readonly TemporaryDirectory home; readonly string tentacleExe; readonly IReadOnlyDictionary environmentVariables; - readonly CancellationToken cancellationToken; - internal TentacleInstance(TemporaryDirectory home, string tentacleExe, string? name, string? thumbprint, IReadOnlyDictionary environmentVariables, CancellationToken cancellationToken) + internal TentacleInstance(TemporaryDirectory home, string tentacleExe, string? name, string? thumbprint, IReadOnlyDictionary environmentVariables) { this.home = home; this.tentacleExe = tentacleExe; Name = name; Thumbprint = thumbprint; this.environmentVariables = environmentVariables; - this.cancellationToken = cancellationToken; } public string? Name { get; } @@ -192,25 +190,25 @@ internal TentacleInstance(TemporaryDirectory home, string tentacleExe, string? n // The same instance, as if the current Tentacle had been installed over it. public TentacleInstance WithCurrentTentacleExe() - => new(home, TentacleExeFinder.FindTentacleExe(), Name, Thumbprint, environmentVariables, cancellationToken); + => new(home, TentacleExeFinder.FindTentacleExe(), Name, Thumbprint, environmentVariables); internal TentacleInstance WithThumbprint(string thumbprint) - => new(home, tentacleExe, Name, thumbprint, environmentVariables, cancellationToken); + => new(home, tentacleExe, Name, thumbprint, environmentVariables); public string CertificateAsStoredInTheConfigurationFile() => XDocument.Load(ConfigurationFile).Root!.Elements("set").Single(e => (string?)e.Attribute("key") == TentacleConfiguration.CertificateSettingName).Value; - public async Task ShowThumbprint() - => (await ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "show-thumbprint")).StandardOutput.Trim(); + public async Task ShowThumbprint(CancellationToken cancellationToken) + => (await ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "show-thumbprint", cancellationToken)).StandardOutput.Trim(); - public async Task ExecuteTentacleCommandOnTheInstance(CommandResultValidation validation, string command, params string[] arguments) - => await ExecuteTentacleCommand(validation, new[] { command } + public async Task ExecuteTentacleCommandOnTheInstance(CommandResultValidation validation, string command, CancellationToken cancellationToken, params string[] arguments) + => await ExecuteTentacleCommand(validation, cancellationToken, new[] { command } .Concat(arguments) .Concat(Name is null ? new[] { "--config", ConfigurationFile } : new[] { "--instance", Name }) .ToArray()); // Older Tentacles share the machine's instance registry, so a command can fail while another test registers an instance. - public async Task ExecuteTentacleCommand(CommandResultValidation validation, params string[] arguments) + public async Task ExecuteTentacleCommand(CommandResultValidation validation, CancellationToken cancellationToken, params string[] arguments) => await RetryHelper.RetryAsync( async () => await Cli.Wrap(tentacleExe) .WithArguments(arguments) From 34268d38f46cf9784a7f3333310ef47ddef2de0c Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 09:29:10 +1100 Subject: [PATCH 074/124] Keep one multi-block unicode legacy ciphertext case per key --- .../Crypto/LegacyCiphertextCompatibilityTests.cs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs index eab9c4429..9dc45dfa1 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs @@ -15,13 +15,7 @@ namespace Octopus.Tentacle.Tests.Configuration.Crypto [LinuxOrMacTest] public class LegacyCiphertextCompatibilityTests { - const string CertificateSizedText = "AAcOFRwjKjE4P0ZNVFtiaXB3foWMk5qhqK+2vcTL0tng5+71/AMKERgfJi00O0JJUFdeZWxzeoGIj5adpKuyucDHztXc4+rx+P8GDRQbIikwNz5FTFNaYWhvdn2Ei5KZoKeutbzDytHY3+bt9PsCCRAXHiUsMzpBSE9WXWRrcnmAh46VnKOqsbi/xs3U2+Lp8Pf+BQwTGiEoLzY9REtSWWBnbnV8g4qRmJ+mrbS7wsnQ197l7PP6AQgPFh0kKzI5QEdOVVxjanF4f4aNlJuiqbC3vsXM09rh6O/2/QQLEhkgJy41PENKUVhfZm10e4KJkJeepayzusHIz9bd5Ovy+QAHDhUcIyoxOD9GTVRbYmlwd36FjJOaoaivtr3Ey9LZ4Ofu9fwDChEYHyYt"; - - [TestCase("FooBar", "yspqcK7xCvd5c+1OSB7kxw==")] - [TestCase("true", "lfWdFxOQukFHfUs767dBOA==")] - [TestCase("123", "c5E+1E8Q73XGrrSEWenz/A==")] [TestCase("pässwörd 🐙 with spaces & symbols!", "nMmwC8Uzkg/bEwaDChRL86dTMzY4gCyveDi0qCjOWNENjQzd3wYS8lJwMeGXNdEy")] - [TestCase(CertificateSizedText, "2qbSDqJXa0/Bz1SzohM21m3dg3mIPBjj4mgbfve/WW1cZFNAgccjx+Hot6Qp8/TC8Su4rLS8yp6i+WY4J8x7ga6DbFVD4pQkjy8ag37nxwBos4llfCRhRqV0LZWol2U66+znAfTscepLI1nVWgtJtloYLGky/6QDjvMQQG9S/MmQsBzANfI3lQG8ftYK/ilU6xX7eJwvWViEG3HI/3loc7k9jbJT13JF4f8NpI3yEH4Q4VCWY9j3z+ZK/2kImeqRDfv9cl4roUdtBQ4I333taVovDwILKqq2a6QPRZiAVJ34in2CrrJv2dTWgaQHsU74upUlKiKrZs6LgpZVP7y+5W/o52te+dvwCBVBqFmxFUmpk/1gAMUiqZ0fEXrz8GlyS4dcIXlFUwUXcdUb1E2ldqDMRr2zDHP0ATwdBcKm9yM4sJKrGhrSksl7U7chM4CpRVTUf1tWvU3SjcQ00haPM+RZP2pWDnkDZhkrDRfpQke/qFL8wG9RySpzWDF+zsN0yUxZJgqUvy9cHb/yHphxTqyEmmoGcAuzOaA9a2yYGPs=")] public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string plaintext, string legacyCiphertext) { // Arrange @@ -37,11 +31,7 @@ public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string pl decrypted.Should().Be(plaintext); } - [TestCase("FooBar", "sU7FAsi9LrgjCISbdFN4Kg==")] - [TestCase("true", "ks2Nbbl8OonD1r2CFim+VA==")] - [TestCase("123", "QL+mcAjSyVWEsVPlQeNvqA==")] [TestCase("pässwörd 🐙 with spaces & symbols!", "cVzJO4WpcDeZTWcG91jyln6rFJvjf08RkpiAb+FUMcOnzT8uB5emsPmEKS8vyg+p")] - [TestCase(CertificateSizedText, "NhUpBIgpSxmvYSXfn+cn5lKK5xB1LDf0NdKogqm1MAn4XQ8p84KJwVzEevn/T7Glk9Lirqa/RtUM9HuEEadDZ6XKhbnBdUJGLx1CFfHHw/3L3IProqBX/mD+W0SVIvnI54iq5PFdwtSSOH3a6PC+DT92rmXjy4/YoNzuGKkNcMoP/GG3g6URPHGdMq3NMs7t3wD7k8MbvU96F5qlTdqiwgILViruLJGZhECb99GmTdJ/PjCeFE87+up+vZllk1WVboGAIn6Vf+1Pgd7tDHgczDHZvgKIeP1k5gwH9dXzSd/OweG7eW7Yux0HIcI1oPMDcjx57ldDzYwhgIX5jPkMGFP3J4guwCIaSQTEyMLP85ZervJ0uWlAq/rlIK71dQ5c6wvFIVKkKeSo+qWReMRi9G4rMaelnagNTwUqBBfy+nff+tbvPrLV+CmKDCEgA+g1d7kF7+y/kBJ4NaZOpo6jBUVds/sV7ieVZhcUmHN2eML4/Zur5KyHvHsDnOWU3jgBxQ6oJJQB4yePmWivAXWlE4ISpIvM5i76XYqLbEJ+lbQ=")] public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plaintext, string legacyCiphertext) { // Arrange From 651f4738dbce3baf98ad51c5b881ce88d7973f00 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 09:36:18 +1100 Subject: [PATCH 075/124] Test that Tentacle still starts on legacy keys when the new key cannot be created --- .../ConfigurationEncryptionUpgradeTests.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 077bfbf1f..3aa723c26 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -122,6 +122,24 @@ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheCurrentTentac (await runningTentacle.Instance.ShowThumbprint(CancellationToken)).Should().Be(runningTentacle.Thumbprint, "the upgraded certificate must still decrypt to the same certificate"); } + [Test] + public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheNewKeyCannotBeCreated_ThenTheCurrentTentacleStillStartsAndTheCertificateIsUnchanged() + { + // Arrange + await using var runningTentacle = await new TentacleInstanceBuilder() + .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) + .RunAsListeningTentacle(TestCertificates.ServerPublicThumbprint) + .Build(Logger, CancellationToken); + var certificateEncryptedByVersion14 = runningTentacle.Instance.CertificateAsStoredInTheConfigurationFile(); + await File.WriteAllTextAsync(runningTentacle.Instance.DataDirectory, "a file where the data directory should be, so the key directory cannot be created"); + + // Act + await runningTentacle.StopAndStartWithCurrentVersionOfTentacle(CancellationToken); + + // Assert + runningTentacle.Instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedByVersion14); + } + [Test] public async Task WhenTentacleKeyFileIsDeleted_AndTheCurrentTentacleStarts_ThenTheCertificateIsLeftUntouched() { From 3764b2f185cf0ae0700dbc285c00f64ba9726065 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 09:44:25 +1100 Subject: [PATCH 076/124] Drop show-thumbprint checks from the package test; dotnet tests cover them --- linux-packages/test-scripts/test-linux-package.sh | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh index 0d365107b..e055fcd2f 100644 --- a/linux-packages/test-scripts/test-linux-package.sh +++ b/linux-packages/test-scripts/test-linux-package.sh @@ -91,17 +91,6 @@ for KEY_PATH in "$MACHINE_KEY_FILE" "$(dirname "$MACHINE_KEY_FILE")"; do fi done echo "The machine key was given to the owner of the configuration." - -THUMBPRINT=$(Tentacle show-thumbprint --instance "$INSTANCE_NAME") -if [[ -z "$THUMBPRINT" ]] || ! grep -qF "key=\"Tentacle.CertificateThumbprint\">$THUMBPRINT<" "$CONFIGURATION_FILE"; then - echo "'Tentacle show-thumbprint' reported '$THUMBPRINT', which is not the thumbprint recorded in $CONFIGURATION_FILE." - exit 1 -fi -echo "The certificate decrypts in a new process and matches the recorded thumbprint." - -# Selecting the instance by --config must still find the registered instance's key. -[[ "$(Tentacle show-thumbprint --config "$CONFIGURATION_FILE")" == "$THUMBPRINT" ]] || { echo "'Tentacle show-thumbprint --config' did not decrypt with the registered instance's key."; exit 1; } -echo "Selecting the instance by its configuration file uses that instance's key." echo "" echo "All tests passed." From e85a52e16a9c658a062ec570d937987729ad80d5 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 09:51:00 +1100 Subject: [PATCH 077/124] Say why the package test exercises the configuration encryption key --- linux-packages/test-scripts/test-linux-package.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/linux-packages/test-scripts/test-linux-package.sh b/linux-packages/test-scripts/test-linux-package.sh index e055fcd2f..3da47514f 100644 --- a/linux-packages/test-scripts/test-linux-package.sh +++ b/linux-packages/test-scripts/test-linux-package.sh @@ -56,7 +56,8 @@ fi echo "The installed Tentacle version matches the expected one." echo "" -# A new certificate must be encrypted with the instance's generated key, not one derived from /etc/machine-id. +# Creating, protecting and re-owning the configuration encryption key calls libc and OpenSSL directly, +# so it is exercised here on every distribution we package for. INSTANCE_NAME="package-test" CONFIGURATION_FILE="/etc/octopus/$INSTANCE_NAME/tentacle.config" MACHINE_KEY_FILE="/var/lib/octopus/tentacle/$INSTANCE_NAME/keys/config-encryption.key" From cda83408c97e0ae6e50ecb5189bab718f77502ac Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 10:00:03 +1100 Subject: [PATCH 078/124] Run a script on the Tentacle that started on legacy keys --- .../Configuration/ConfigurationEncryptionUpgradeTests.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 3aa723c26..4b0839872 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -6,9 +6,12 @@ using FluentAssertions; using NUnit.Framework; using Octopus.Tentacle.CommonTestUtils; +using Octopus.Tentacle.Contracts; using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Tests.Integration.Common; using Octopus.Tentacle.Tests.Integration.Support; using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; +using Octopus.Tentacle.Tests.Integration.Util.Builders; namespace Octopus.Tentacle.Tests.Integration.Configuration { @@ -137,6 +140,12 @@ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheNewKeyCannotB await runningTentacle.StopAndStartWithCurrentVersionOfTentacle(CancellationToken); // Assert + await using var serverHalibut = TestServerHalibut.BuildServerHalibutRuntime(); + var tentacleClient = TestServerHalibut.BuildTentacleClient(runningTentacle.ServiceUri, runningTentacle.Thumbprint, serverHalibut, _ => { }); + var (scriptResult, _) = await tentacleClient.ExecuteScript(new TestExecuteShellScriptCommandBuilder().SetScriptBody(b => b.Print("Hello")).Build(), CancellationToken); + scriptResult.State.Should().Be(ProcessState.Complete); + scriptResult.ExitCode.Should().Be(0); + runningTentacle.Instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedByVersion14); } From 4ee0107ed21ff19742305f92ccf6fa8a279e7d92 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 10:06:04 +1100 Subject: [PATCH 079/124] Use TemporaryDirectory in the non-root create-instance test --- .../Configuration/NonRootCreateInstanceTests.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs index 32a65cf1b..64dc08769 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs @@ -8,17 +8,20 @@ using CliWrap.Buffered; using FluentAssertions; using NUnit.Framework; +using Octopus.Tentacle.CommonTestUtils; +using Octopus.Tentacle.CommonTestUtils.Diagnostics; using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Tests.Integration.Support; using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; using Octopus.Tentacle.Tests.Integration.Util; +using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Integration.Configuration { [LinuxTest] [NonParallelizable] [UnsupportedOSPlatform("windows")] - public class NonRootCreateInstanceTests + public class NonRootCreateInstanceTests : IntegrationTest { [Test] [RequiresSudoOnLinux] @@ -26,7 +29,9 @@ public async Task WhenANonRootUserCannotCreateTheKeyThenTheCommandInTheErrorFixe { // Arrange var user = new LinuxTestUserPrincipal("octo-key-test"); - var root = Directory.CreateTempSubdirectory().FullName; + // Under /tmp rather than the default location, which is in the runner's home and not traversable by the test user. + using var temporaryDirectory = new TemporaryDirectory(new OctopusPhysicalFileSystem(new InMemoryLog()), Directory.CreateTempSubdirectory().FullName); + var root = temporaryDirectory.DirectoryPath; File.SetUnixFileMode(root, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); var dataDirectory = Path.Combine(root, "data"); Directory.CreateDirectory(dataDirectory); @@ -46,7 +51,9 @@ Task CreateInstanceAsUser() { // Act var refused = await CreateInstanceAsUser(); + Logger.Information("StdOut: {StdOut}, StdErr: {StdErr}", refused.StandardOutput, refused.StandardError); var fix = Regex.Match(refused.StandardOutput + refused.StandardError, "sudo mkdir[^`]*").Value; + Logger.Information("Running Fix: {Fix}", fix); await Cli.Wrap("/bin/bash").WithArguments(new[] { "-c", fix }).ExecuteBufferedAsync(); var created = await CreateInstanceAsUser(); @@ -58,7 +65,6 @@ Task CreateInstanceAsUser() } finally { - Directory.Delete(root, recursive: true); await Sudo("userdel", "-r", user.UserName); } } From 0d71712599cf7b23209bb9525ee203308fb423bf Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 10:24:21 +1100 Subject: [PATCH 080/124] Remove re-encryption typed-read test; re-encryption only moves strings --- .../XmlFileKeyValueStoreReEncryptionTests.cs | 54 ------------------- 1 file changed, 54 deletions(-) delete mode 100644 source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionTests.cs diff --git a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionTests.cs b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionTests.cs deleted file mode 100644 index 3f838e1bb..000000000 --- a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionTests.cs +++ /dev/null @@ -1,54 +0,0 @@ -#if !NETFRAMEWORK -using System; -using System.IO; -using System.Linq; -using FluentAssertions; -using NSubstitute; -using NUnit.Framework; -using Octopus.Tentacle.Configuration; -using Octopus.Tentacle.Configuration.Crypto; -using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Tests.Configuration.Crypto; -using Octopus.Tentacle.Tests.Support; -using Octopus.Tentacle.Util; - -namespace Octopus.Tentacle.Tests.Configuration -{ - public class XmlFileKeyValueStoreReEncryptionTests - { - [Test] - public void WhenSerialisedValuesAreReEncryptedThenTypedReadsStillWork() - { - // Arrange - var configurationFile = Path.GetTempFileName(); - var fileSystem = new OctopusPhysicalFileSystem(Substitute.For()); - fileSystem.OverwriteFile(configurationFile, @""); - var legacyKey = new InMemoryCryptoKeyNixSource(); - var encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), new[] { legacyKey }); - var legacyStore = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: new LegacySchemeEncryptor(legacyKey)); - var store = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: encryptor); - var names = new[] { "a.bool", "an.int", "an.enum", "an.object" }; - var configurationObject = new MyObject { IntField = 10, BooleanField = true, EnumField = SomeEnum.SomeOtherEnumValue, ArrayField = new[] { new MyNestedObject { Id = 1 } } }; - legacyStore.Set("a.bool", true, ProtectionLevel.MachineKey); - legacyStore.Set("an.int", 123, ProtectionLevel.MachineKey); - legacyStore.Set("an.enum", SomeEnum.SomeOtherEnumValue, ProtectionLevel.MachineKey); - legacyStore.Set("an.object", configurationObject, ProtectionLevel.MachineKey); - - // Act - var reEncrypted = names.Select(store.ReEncryptIfLegacy).ToArray(); - - // Assert - reEncrypted.Should().AllBeEquivalentTo(true); - var reloaded = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: encryptor); - reloaded.Get("a.bool", false, ProtectionLevel.MachineKey).Should().BeTrue(); - reloaded.Get("an.int", 0, ProtectionLevel.MachineKey).Should().Be(123); - reloaded.Get("an.enum", SomeEnum.SomeEnumValue, ProtectionLevel.MachineKey).Should().Be(SomeEnum.SomeOtherEnumValue); - var nested = reloaded.Get("an.object", null, ProtectionLevel.MachineKey); - nested.IntField.Should().Be(10); - nested.BooleanField.Should().BeTrue(); - nested.EnumField.Should().Be(SomeEnum.SomeOtherEnumValue); - nested.ArrayField.Single().Id.Should().Be(1); - } - } -} -#endif From 2871f8ce27782206a96ad57a5a35bc3c08b3b385 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 10:37:28 +1100 Subject: [PATCH 081/124] Move FakeOctopusServer to Tests.Integration.Common and test replace-certificate moves a version 14 Tentacle to its own key --- .../FakeOctopusServerContractTests.cs | 1 + .../LinuxTentacleAuthenticationTests.cs | 1 + .../LinuxTentacleConfigEncryptionTests.cs | 1 + .../LinuxTentacleContainerLifecycleTests.cs | 1 + .../LinuxTentacleImageTests.cs | 1 + .../LinuxTentacleUnregisteredTests.cs | 1 + .../LinuxTentacleWorkerTests.cs | 1 + ...s.Tentacle.Docker.Tests.Integration.csproj | 5 -- .../Setup/TentacleContainer.cs | 1 + .../Setup/TentacleContainerBuilder.cs | 2 + .../AssemblyInfo.cs | 3 +- .../FakeOctopus}/FakeOctopusServer.cs | 10 +++- .../FakeOctopus}/FakeOctopusServerBuilder.cs | 2 +- ...s.Tentacle.Tests.Integration.Common.csproj | 6 +++ .../ReplaceCertificateCommandTests.cs | 48 +++++++++++++++++++ 15 files changed, 75 insertions(+), 9 deletions(-) rename source/{Octopus.Tentacle.Docker.Tests.Integration/Setup => Octopus.Tentacle.Tests.Integration.Common/FakeOctopus}/FakeOctopusServer.cs (97%) rename source/{Octopus.Tentacle.Docker.Tests.Integration/Setup => Octopus.Tentacle.Tests.Integration.Common/FakeOctopus}/FakeOctopusServerBuilder.cs (91%) create mode 100644 source/Octopus.Tentacle.Tests.Integration/Commands/ReplaceCertificateCommandTests.cs diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/FakeOctopusServerContractTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/FakeOctopusServerContractTests.cs index 2719d21b2..fe7cb9731 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/FakeOctopusServerContractTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/FakeOctopusServerContractTests.cs @@ -5,6 +5,7 @@ using Octopus.Tentacle.Commands; using Octopus.Tentacle.CommonTestUtils; using Octopus.Tentacle.Docker.Tests.Integration.Setup; +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; namespace Octopus.Tentacle.Docker.Tests.Integration; diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleAuthenticationTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleAuthenticationTests.cs index 70caab3de..12ee0b018 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleAuthenticationTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleAuthenticationTests.cs @@ -1,5 +1,6 @@ using FluentAssertions; using Octopus.Tentacle.Docker.Tests.Integration.Setup; +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; namespace Octopus.Tentacle.Docker.Tests.Integration; diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs index f9d698c74..a2aa4929a 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs @@ -3,6 +3,7 @@ using Octopus.Tentacle.CommonTestUtils; using Octopus.Tentacle.Contracts; using Octopus.Tentacle.Docker.Tests.Integration.Setup; +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; namespace Octopus.Tentacle.Docker.Tests.Integration; diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleContainerLifecycleTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleContainerLifecycleTests.cs index 5ffa0c870..74941138d 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleContainerLifecycleTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleContainerLifecycleTests.cs @@ -4,6 +4,7 @@ using Octopus.Tentacle.CommonTestUtils; using Octopus.Tentacle.Contracts; using Octopus.Tentacle.Docker.Tests.Integration.Setup; +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; namespace Octopus.Tentacle.Docker.Tests.Integration; diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleImageTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleImageTests.cs index a82c60d57..a391c741c 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleImageTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleImageTests.cs @@ -3,6 +3,7 @@ using Octopus.Tentacle.CommonTestUtils; using Octopus.Tentacle.Contracts; using Octopus.Tentacle.Docker.Tests.Integration.Setup; +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; using Octopus.Tentacle.Tests.Integration.Util.Builders; namespace Octopus.Tentacle.Docker.Tests.Integration; diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleUnregisteredTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleUnregisteredTests.cs index 0ccd96baa..30c398d44 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleUnregisteredTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleUnregisteredTests.cs @@ -7,6 +7,7 @@ using Octopus.Tentacle.CommonTestUtils; using Octopus.Tentacle.Contracts; using Octopus.Tentacle.Docker.Tests.Integration.Setup; +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; namespace Octopus.Tentacle.Docker.Tests.Integration; diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleWorkerTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleWorkerTests.cs index 553797dbe..ce9066fcf 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleWorkerTests.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleWorkerTests.cs @@ -1,6 +1,7 @@ using System.Text.RegularExpressions; using FluentAssertions; using Octopus.Tentacle.Docker.Tests.Integration.Setup; +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; namespace Octopus.Tentacle.Docker.Tests.Integration; diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Octopus.Tentacle.Docker.Tests.Integration.csproj b/source/Octopus.Tentacle.Docker.Tests.Integration/Octopus.Tentacle.Docker.Tests.Integration.csproj index efad99028..c8270ff14 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Octopus.Tentacle.Docker.Tests.Integration.csproj +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Octopus.Tentacle.Docker.Tests.Integration.csproj @@ -16,11 +16,6 @@ false - - - - - diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs index 2f6526275..51321abd1 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainer.cs @@ -7,6 +7,7 @@ using Octopus.Tentacle.CommonTestUtils.Diagnostics; using Octopus.Tentacle.Contracts; using Octopus.Tentacle.Tests.Integration.Common; +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; namespace Octopus.Tentacle.Docker.Tests.Integration.Setup; diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs index ddc5eb1f4..68e13dc26 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs +++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs @@ -1,3 +1,5 @@ +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; + namespace Octopus.Tentacle.Docker.Tests.Integration.Setup; /// diff --git a/source/Octopus.Tentacle.Tests.Integration.Common/AssemblyInfo.cs b/source/Octopus.Tentacle.Tests.Integration.Common/AssemblyInfo.cs index a09e0c05a..1833eefba 100644 --- a/source/Octopus.Tentacle.Tests.Integration.Common/AssemblyInfo.cs +++ b/source/Octopus.Tentacle.Tests.Integration.Common/AssemblyInfo.cs @@ -2,4 +2,5 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Octopus.Tentacle.Tests.Integration")] -[assembly: InternalsVisibleTo("Octopus.Tentacle.Kubernetes.Tests.Integration")] \ No newline at end of file +[assembly: InternalsVisibleTo("Octopus.Tentacle.Kubernetes.Tests.Integration")] +[assembly: InternalsVisibleTo("Octopus.Tentacle.Docker.Tests.Integration")] \ No newline at end of file diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/FakeOctopusServer.cs b/source/Octopus.Tentacle.Tests.Integration.Common/FakeOctopus/FakeOctopusServer.cs similarity index 97% rename from source/Octopus.Tentacle.Docker.Tests.Integration/Setup/FakeOctopusServer.cs rename to source/Octopus.Tentacle.Tests.Integration.Common/FakeOctopus/FakeOctopusServer.cs index f53f4e509..ad181dd3f 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/FakeOctopusServer.cs +++ b/source/Octopus.Tentacle.Tests.Integration.Common/FakeOctopus/FakeOctopusServer.cs @@ -11,13 +11,13 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using NUnit.Framework; using Octopus.Client.Extensibility; using Octopus.Client.Model; using Octopus.Tentacle.CommonTestUtils; -using Octopus.Tentacle.Tests.Integration.Common; using ILogger = Serilog.ILogger; -namespace Octopus.Tentacle.Docker.Tests.Integration.Setup; +namespace Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; /// /// A stand-in Octopus Server for one test, built with . It has two parts: @@ -84,6 +84,7 @@ public sealed class FakeOctopusServer : IAsyncDisposable readonly ConcurrentDictionary<(string SpaceName, string MachineName), TaskCompletionSource> registrations = new(); readonly ConcurrentQueue unhandledRequests = new(); readonly ConcurrentDictionary<(string SpaceName, string MachineName), int> registrationCounts = new(); + readonly ConcurrentDictionary<(string SpaceName, string MachineName), RegisteredMachine> latestRegistrations = new(); readonly ConcurrentDictionary sessions = new(); readonly ConcurrentQueue requestLog = new(); readonly object spacesLock = new(); @@ -216,6 +217,10 @@ FakeSpace CreateSpace(string id, string name, string[] environmentNames) public int RegistrationCount(string spaceName, string machineName) => registrationCounts.TryGetValue((spaceName.ToLowerInvariant(), machineName.ToLowerInvariant()), out var count) ? count : 0; + /// The machine as last created or updated, e.g. after `replace-certificate` changed its thumbprint. + public RegisteredMachine? LatestRegistration(string spaceName, string machineName) + => latestRegistrations.TryGetValue((spaceName.ToLowerInvariant(), machineName.ToLowerInvariant()), out var machine) ? machine : null; + public Task WaitForRegistration(string spaceName, string machineName) => RegistrationFor(spaceName, machineName).Task; @@ -334,6 +339,7 @@ IResult Register(FakeSpace space, string collection, List items, Jso halibut.Trust(machine.Thumbprint); } + latestRegistrations[(space.Name.ToLowerInvariant(), machine.Name.ToLowerInvariant())] = machine; registrationCounts.AddOrUpdate((space.Name.ToLowerInvariant(), machine.Name.ToLowerInvariant()), 1, (_, count) => count + 1); RegistrationFor(space.Name, machine.Name).TrySetResult(machine); diff --git a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/FakeOctopusServerBuilder.cs b/source/Octopus.Tentacle.Tests.Integration.Common/FakeOctopus/FakeOctopusServerBuilder.cs similarity index 91% rename from source/Octopus.Tentacle.Docker.Tests.Integration/Setup/FakeOctopusServerBuilder.cs rename to source/Octopus.Tentacle.Tests.Integration.Common/FakeOctopus/FakeOctopusServerBuilder.cs index 3f3c2dcb8..810bee41e 100644 --- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/FakeOctopusServerBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration.Common/FakeOctopus/FakeOctopusServerBuilder.cs @@ -1,6 +1,6 @@ using Octopus.Tentacle.Tests.Integration.Common.Logging; -namespace Octopus.Tentacle.Docker.Tests.Integration.Setup; +namespace Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; /// /// Builds a for one test: diff --git a/source/Octopus.Tentacle.Tests.Integration.Common/Octopus.Tentacle.Tests.Integration.Common.csproj b/source/Octopus.Tentacle.Tests.Integration.Common/Octopus.Tentacle.Tests.Integration.Common.csproj index d5a68f559..41c9a1abb 100644 --- a/source/Octopus.Tentacle.Tests.Integration.Common/Octopus.Tentacle.Tests.Integration.Common.csproj +++ b/source/Octopus.Tentacle.Tests.Integration.Common/Octopus.Tentacle.Tests.Integration.Common.csproj @@ -26,6 +26,12 @@ + + + + + + diff --git a/source/Octopus.Tentacle.Tests.Integration/Commands/ReplaceCertificateCommandTests.cs b/source/Octopus.Tentacle.Tests.Integration/Commands/ReplaceCertificateCommandTests.cs new file mode 100644 index 000000000..ef680cd8a --- /dev/null +++ b/source/Octopus.Tentacle.Tests.Integration/Commands/ReplaceCertificateCommandTests.cs @@ -0,0 +1,48 @@ +#if NET +using System.IO; +using System.Runtime.Versioning; +using System.Threading.Tasks; +using CliWrap; +using FluentAssertions; +using NUnit.Framework; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; +using Octopus.Tentacle.Tests.Integration.Support; +using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; + +namespace Octopus.Tentacle.Tests.Integration.Commands +{ + [LinuxTest] + [UnsupportedOSPlatform("windows")] + public class ReplaceCertificateCommandTests : IntegrationTest + { + const string MachineName = "replace-certificate-test"; + + [Test] + public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndReplaceCertificateIsCalled_ThenTheNewCertificateIsEncryptedWithItsOwnKey() + { + // Arrange + await using var octopus = await new FakeOctopusServerBuilder().Build(); + using var instance = await new TentacleInstanceBuilder() + .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) + .WithNewCertificate() + .Build(Logger, CancellationToken); + var server = $"--server=http://localhost:{octopus.Port}"; + await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "register-with", CancellationToken, + server, "--apiKey=API-KEY", $"--space={FakeOctopusServerBuilder.SpaceName}", $"--environment={FakeOctopusServerBuilder.EnvironmentName}", + "--role=test", $"--name={MachineName}", "--comms-style=TentaclePassive"); + + // Act + var upgradedInstance = instance.WithCurrentTentacleExe(); + await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "replace-certificate", CancellationToken, server, "--apiKey=API-KEY"); + + // Assert + var newThumbprint = await upgradedInstance.ShowThumbprint(CancellationToken); + newThumbprint.Should().NotBe(instance.Thumbprint); + upgradedInstance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); + File.Exists(instance.ConfigurationEncryptionKeyFile).Should().BeTrue(); + octopus.LatestRegistration(FakeOctopusServerBuilder.SpaceName, MachineName)!.Thumbprint.Should().Be(newThumbprint); + } + } +} +#endif From 2bde0c842f18d0620ee730c034bdfdc8dbcd928b Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:12:20 +1100 Subject: [PATCH 082/124] Name the replace-certificate test after the Linux encryption upgrade it covers --- ...dTests.cs => LinuxReplaceCertificateEncryptionUpgradeTests.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename source/Octopus.Tentacle.Tests.Integration/Commands/{ReplaceCertificateCommandTests.cs => LinuxReplaceCertificateEncryptionUpgradeTests.cs} (100%) diff --git a/source/Octopus.Tentacle.Tests.Integration/Commands/ReplaceCertificateCommandTests.cs b/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxReplaceCertificateEncryptionUpgradeTests.cs similarity index 100% rename from source/Octopus.Tentacle.Tests.Integration/Commands/ReplaceCertificateCommandTests.cs rename to source/Octopus.Tentacle.Tests.Integration/Commands/LinuxReplaceCertificateEncryptionUpgradeTests.cs From bc5b0e601df9bf2d0be827cdd42ca59ef847a90b Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:13:26 +1100 Subject: [PATCH 083/124] Inline the single legacy ciphertext case in each test --- ...inuxReplaceCertificateEncryptionUpgradeTests.cs | 2 +- .../Crypto/LegacyCiphertextCompatibilityTests.cs | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxReplaceCertificateEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxReplaceCertificateEncryptionUpgradeTests.cs index ef680cd8a..de3cc0ab5 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxReplaceCertificateEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxReplaceCertificateEncryptionUpgradeTests.cs @@ -14,7 +14,7 @@ namespace Octopus.Tentacle.Tests.Integration.Commands { [LinuxTest] [UnsupportedOSPlatform("windows")] - public class ReplaceCertificateCommandTests : IntegrationTest + public class LinuxReplaceCertificateEncryptionUpgradeTests : IntegrationTest { const string MachineName = "replace-certificate-test"; diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs index 9dc45dfa1..29bed9796 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs @@ -15,10 +15,11 @@ namespace Octopus.Tentacle.Tests.Configuration.Crypto [LinuxOrMacTest] public class LegacyCiphertextCompatibilityTests { - [TestCase("pässwörd 🐙 with spaces & symbols!", "nMmwC8Uzkg/bEwaDChRL86dTMzY4gCyveDi0qCjOWNENjQzd3wYS8lJwMeGXNdEy")] - public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string plaintext, string legacyCiphertext) + [Test] + public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts() { // Arrange + const string legacyCiphertext = "nMmwC8Uzkg/bEwaDChRL86dTMzY4gCyveDi0qCjOWNENjQzd3wYS8lJwMeGXNdEy"; var fileSystem = Substitute.For(); fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(true); fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { "816490f117f14c7a8fa2697781ed795b" }); @@ -28,13 +29,14 @@ public void WhenAValueWasWrittenWithTheMachineIdKeyThenItStillDecrypts(string pl var decrypted = encryptor.Decrypt(legacyCiphertext); // Assert - decrypted.Should().Be(plaintext); + decrypted.Should().Be("pässwörd 🐙 with spaces & symbols!"); } - [TestCase("pässwörd 🐙 with spaces & symbols!", "cVzJO4WpcDeZTWcG91jyln6rFJvjf08RkpiAb+FUMcOnzT8uB5emsPmEKS8vyg+p")] - public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plaintext, string legacyCiphertext) + [Test] + public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts() { // Arrange + const string legacyCiphertext = "cVzJO4WpcDeZTWcG91jyln6rFJvjf08RkpiAb+FUMcOnzT8uB5emsPmEKS8vyg+p"; var fileSystem = Substitute.For(); fileSystem.FileExists("/etc/octopus/machinekey").Returns(true); fileSystem.ReadAllText("/etc/octopus/machinekey").Returns("MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=.ZmVkY2JhOTg3NjU0MzIxMA=="); @@ -44,7 +46,7 @@ public void WhenAValueWasWrittenWithoutAMachineIdThenItStillDecrypts(string plai var decrypted = encryptor.Decrypt(legacyCiphertext); // Assert - decrypted.Should().Be(plaintext); + decrypted.Should().Be("pässwörd 🐙 with spaces & symbols!"); } } } From 84def5b3dea0f9a62a70a55b96343dfd4c9b8bdd Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:16:01 +1100 Subject: [PATCH 084/124] Replace the key file fixture with self-contained tests --- ...nuxConfigurationEncryptionKeyFileTests.cs} | 46 ++++++++----------- 1 file changed, 18 insertions(+), 28 deletions(-) rename source/Octopus.Tentacle.Tests/Configuration/Crypto/{LinuxConfigurationFileSecurityFixture.cs => LinuxConfigurationEncryptionKeyFileTests.cs} (75%) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs similarity index 75% rename from source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs rename to source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs index 45747af51..af98659a4 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs @@ -13,45 +13,27 @@ using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Core.Util; +using Octopus.Tentacle.Tests.Support; using Octopus.Tentacle.Tests.Support.TestAttributes; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Configuration.Crypto { - [TestFixture] [LinuxTest] [SupportedOSPlatform("linux")] - public class LinuxConfigurationFileSecurityFixture + public class LinuxConfigurationEncryptionKeyFileTests { const UnixFileMode OwnerReadWrite = UnixFileMode.UserRead | UnixFileMode.UserWrite; - string directory; - string keyFilePath; - ISystemLog log; - OctopusPhysicalFileSystem fileSystem; - - [SetUp] - public void SetUp() - { - directory = Path.Combine(Path.GetTempPath(), "octopus-config-encryption-key-" + Guid.NewGuid()); - keyFilePath = Path.Combine(directory, ConfigurationEncryptionKey.KeyFileName); - log = Substitute.For(); - fileSystem = new OctopusPhysicalFileSystem(log); - } - - [TearDown] - public void TearDown() - { - if (Directory.Exists(directory)) - { - Directory.Delete(directory, recursive: true); - } - } - [Test] public void WhenTheKeyIsCreatedThenOnlyItsOwnerCanReadIt() { // Arrange + var log = Substitute.For(); + var fileSystem = new OctopusPhysicalFileSystem(log); + using var directory = new TemporaryDirectory(fileSystem); + var keyDirectory = Path.Combine(directory.DirectoryPath, "keys"); + var keyFilePath = Path.Combine(keyDirectory, ConfigurationEncryptionKey.KeyFileName); var keySource = new ConfigurationEncryptionKey(log, fileSystem, keyFilePath); // Act @@ -62,13 +44,17 @@ public void WhenTheKeyIsCreatedThenOnlyItsOwnerCanReadIt() File.Exists(keyFilePath).Should().BeTrue("the directory is created on demand, as it always was"); File.GetUnixFileMode(keyFilePath).Should().Be(OwnerReadWrite); File.ReadAllText(keyFilePath).Should().Be(Convert.ToBase64String(key)); - Directory.GetFiles(directory).Should().ContainSingle("the temporary file the key is written to first is not left behind"); + Directory.GetFiles(keyDirectory).Should().ContainSingle("the temporary file the key is written to first is not left behind"); } [Test] public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() { // Arrange + var log = Substitute.For(); + using var directory = new TemporaryDirectory(new OctopusPhysicalFileSystem(log)); + var keyDirectory = Path.Combine(directory.DirectoryPath, "keys"); + var keyFilePath = Path.Combine(keyDirectory, ConfigurationEncryptionKey.KeyFileName); const int racers = 32; using var start = new ManualResetEventSlim(false); var loads = Enumerable.Range(0, racers) @@ -88,7 +74,7 @@ public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() // Assert var onDisk = Convert.FromBase64String(File.ReadAllText(keyFilePath)); keys.Should().AllSatisfy(k => k.Should().Equal(onDisk)); - Directory.GetFiles(directory).Should().ContainSingle("no racer's temporary file is left behind"); + Directory.GetFiles(keyDirectory).Should().ContainSingle("no racer's temporary file is left behind"); } [Test] @@ -100,9 +86,13 @@ public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillRea } // Arrange + var log = Substitute.For(); + var fileSystem = new OctopusPhysicalFileSystem(log); + // Not created yet, so CreateIfMissing creates every directory down to the key under the hardened umask. + using var directory = new TemporaryDirectory(fileSystem, Path.Combine(Path.GetTempPath(), "octopus-config-encryption-key-" + Guid.NewGuid())); var user = "octo-key-" + Guid.NewGuid().ToString("N").Substring(0, 8); CreateUser(user).Should().Be(0); - var instanceKeyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); + var instanceKeyFilePath = Path.Combine(directory.DirectoryPath, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); var keySource = new ConfigurationEncryptionKey(log, fileSystem, instanceKeyFilePath); var previousUmask = umask(Convert.ToUInt32("027", 8)); try From 42a1a862d48e29e39e654346a97462e1bc4c8d92 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:16:11 +1100 Subject: [PATCH 085/124] Use LinuxOrMacTest rather than an inline platform check --- .../Configuration/ApplicationInstanceSelectorFixture.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs index 492df010a..6d4707388 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs @@ -10,6 +10,7 @@ using Octopus.Tentacle.Kubernetes; using Octopus.Tentacle.Kubernetes.Configuration; using Octopus.Tentacle.Kubernetes.Crypto; +using Octopus.Tentacle.Tests.Support.TestAttributes; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Configuration @@ -93,11 +94,9 @@ public void GivenConfigurationInstanceExists_WhenRequestingConfigurationInstance } [Test] + [LinuxOrMacTest] public void GivenARegisteredInstanceUsesTheConfiguration_WhenRequestingConfigurationInstance_ThenItUsesThatInstancesKey() { - if (PlatformDetection.IsRunningOnWindows) - Assert.Ignore("Configuration encryption keys are Linux only"); - var filePath = "/etc/octopus/tentacle.config"; var mock = CreateApplicationInstanceSelector(new StartUpConfigFileInstanceRequest(filePath)); octopusFileSystem.FileExists(filePath).Returns(true); From 4dc4d54693ec93cbf93a8fca27aa79d428271825 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:28:55 +1100 Subject: [PATCH 086/124] Write instance index files atomically so concurrent listings never read a partly written file --- .../Util/FileSystem/IOctopusFileSystem.cs | 1 + .../Util/OctopusPhysicalFileSystem.cs | 45 ++++++++++++++----- .../ApplicationInstanceStoreFixture.cs | 8 ++-- .../Configuration/Crypto/LinuxMachineIdKey.cs | 2 +- .../Instances/ApplicationInstanceStore.cs | 4 +- .../RetryingKubernetesPhysicalFileSystem.cs | 5 +++ 6 files changed, 47 insertions(+), 18 deletions(-) diff --git a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs index f004248bb..7800ea9ad 100644 --- a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs @@ -20,6 +20,7 @@ public interface IOctopusFileSystem string ReadFile(string path, bool withRetry = true); void OverwriteFile(string path, string contents); void OverwriteFile(string path, string contents, Encoding encoding); + void AtomicOverwriteFile(string path, string contents); void CopyFile(string source, string destination, bool overwrite); Stream OpenFile(string path, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read); Stream OpenFile(string path, FileMode mode = FileMode.OpenOrCreate, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read); diff --git a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs index c2f45cfab..9eeb8c093 100644 --- a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs @@ -252,6 +252,40 @@ public void WriteAllText(string path, string contents) File.WriteAllText(path, contents); } + // Readers see either the old or the new contents, never a partly written file. + public void AtomicOverwriteFile(string path, string contents) + { + var temporaryPath = TemporaryPathBeside(path); + try + { + File.WriteAllText(temporaryPath, contents); +#if NET + File.Move(temporaryPath, path, overwrite: true); +#else + if (File.Exists(path)) + File.Replace(temporaryPath, path, null); + else + File.Move(temporaryPath, path); +#endif + } + finally + { + DeleteIfExists(temporaryPath); + } + } + + static void DeleteIfExists(string path) + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + + // In the same directory, so it is on the same file system and can be moved or linked into place atomically. + static string TemporaryPathBeside(string path) + => path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + #if NET [UnsupportedOSPlatform("windows")] public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents) @@ -290,17 +324,6 @@ static void CreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) stream.Flush(flushToDisk: true); } - static void DeleteIfExists(string path) - { - if (File.Exists(path)) - { - File.Delete(path); - } - } - - // In the same directory, so it is on the same file system and can be linked into place atomically. - static string TemporaryPathBeside(string path) - => path + "." + Guid.NewGuid().ToString("N") + ".tmp"; #else public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents) => throw new PlatformNotSupportedException(UserOnlyFilesAreUnixOnly); diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceStoreFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceStoreFixture.cs index 9d021e1bc..68c9594aa 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceStoreFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceStoreFixture.cs @@ -33,7 +33,7 @@ public void ListInstance_NoRegistryEntries_ShouldListFromFileSystem() { registryStore.GetListFromRegistry().Returns(Enumerable.Empty()); fileSystem.DirectoryExists(Arg.Any()).Returns(true); - fileSystem.EnumerateFiles(Arg.Any()).Returns(new List { "file1", "file2" }); + fileSystem.EnumerateFiles(Arg.Any(), Arg.Any()).Returns(new List { "file1", "file2" }); fileSystem.FileExists(Arg.Any()).Returns(true); fileSystem.ReadFile(Arg.Is("file1")).Returns("{\"Name\": \"instance1\",\"ConfigurationFilePath\": \"configFilePath1\"}"); fileSystem.ReadFile(Arg.Is("file2")).Returns("{\"Name\": \"instance2\",\"ConfigurationFilePath\": \"configFilePath2\"}"); @@ -77,7 +77,7 @@ public void ListInstance_ShouldPreferFileSystemEntries() new ApplicationInstanceRecord("instance2", "registryFilePath2") }); fileSystem.DirectoryExists(Arg.Any()).Returns(true); - fileSystem.EnumerateFiles(Arg.Any()).Returns(new List { "file1", "file2" }); + fileSystem.EnumerateFiles(Arg.Any(), Arg.Any()).Returns(new List { "file1", "file2" }); fileSystem.FileExists(Arg.Any()).Returns(true); fileSystem.ReadFile(Arg.Is("file1")).Returns("{\"Name\": \"instance2\",\"ConfigurationFilePath\": \"fileConfigFilePath2\"}"); fileSystem.ReadFile(Arg.Is("file2")).Returns("{\"Name\": \"instance3\",\"ConfigurationFilePath\": \"fileConfigFilePath3\"}"); @@ -99,7 +99,7 @@ public void GetInstance_ShouldPreferFileSystemEntries() fileSystem.DirectoryExists(Arg.Any()).Returns(true); fileSystem.FileExists(Arg.Any()).Returns(true); - fileSystem.EnumerateFiles(instanceStore.InstancesFolder).Returns(new[] { configFilename}); + fileSystem.EnumerateFiles(instanceStore.InstancesFolder, "*.config").Returns(new[] { configFilename}); fileSystem.ReadFile(Arg.Is(configFilename)).Returns("{\"Name\": \"instance 1\",\"ConfigurationFilePath\": \"fileConfigFilePath2\"}"); var instance = instanceStore.LoadInstanceDetails("instance 1"); @@ -128,7 +128,7 @@ public void MigrateInstance() instanceStore.MigrateInstance(sourceInstance); fileSystem.Received().CreateDirectory(Arg.Any()); - fileSystem.Received().OverwriteFile(Arg.Is(x => x.Contains(sourceInstance.InstanceName)), Arg.Is(x => x.Contains(sourceInstance.ConfigurationFilePath))); + fileSystem.Received().AtomicOverwriteFile(Arg.Is(x => x.Contains(sourceInstance.InstanceName)), Arg.Is(x => x.Contains(sourceInstance.ConfigurationFilePath))); //we explicitly dont want to delete from the registry here, as we want to allow for customers who try to upgrade and have issues //but then rollback the database and install the old version. This would be a nasty thing to deal with in an already bad experience. diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs index c6d286e9c..39a1bb049 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs @@ -28,7 +28,7 @@ public LinuxMachineIdKey(IOctopusFileSystem fileSystem) { return (GetMachineId(), Iv); } - + byte[] GetMachineId() { if (!fileSystem.FileExists(FileName)) diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceStore.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceStore.cs index 4c2aacfe4..94e967e28 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceStore.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceStore.cs @@ -103,7 +103,7 @@ public IList ListInstances() var listFromRegistry = registryApplicationInstanceStore.GetListFromRegistry(); var listFromFileSystem = new List(); if (fileSystem.DirectoryExists(InstancesFolder)) - listFromFileSystem = fileSystem.EnumerateFiles(InstancesFolder) + listFromFileSystem = fileSystem.EnumerateFiles(InstancesFolder, "*.config") .Select(LoadInstanceConfiguration) .Select(instance => new ApplicationInstanceRecord(instance.Name, instance.ConfigurationFilePath)) .ToList(); @@ -198,7 +198,7 @@ void WriteInstanceConfiguration(Instance instance, string path) var data = JsonConvert.SerializeObject(instance, Formatting.Indented); try { - fileSystem.OverwriteFile(path, data); + fileSystem.AtomicOverwriteFile(path, data); } catch (UnauthorizedAccessException ex) { diff --git a/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs b/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs index 6cdc1f477..43284dcfe 100644 --- a/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs @@ -90,6 +90,11 @@ public void OverwriteFile(string path, string contents, Encoding encoding) syncRetryPolicy.Execute(() => inner.OverwriteFile(path, contents, encoding)); } + public void AtomicOverwriteFile(string path, string contents) + { + syncRetryPolicy.Execute(() => inner.AtomicOverwriteFile(path, contents)); + } + public void CopyFile(string source, string destination, bool overwrite) { syncRetryPolicy.Execute(() => inner.CopyFile(source, destination, overwrite)); From 65fecf98cf7b6e3e1e1ea00eebcae498bffe4ebf Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:30:04 +1100 Subject: [PATCH 087/124] Revert "Write instance index files atomically so concurrent listings never read a partly written file" This reverts commit 4dc4d54693ec93cbf93a8fca27aa79d428271825. --- .../Util/FileSystem/IOctopusFileSystem.cs | 1 - .../Util/OctopusPhysicalFileSystem.cs | 45 +++++-------------- .../ApplicationInstanceStoreFixture.cs | 8 ++-- .../Configuration/Crypto/LinuxMachineIdKey.cs | 2 +- .../Instances/ApplicationInstanceStore.cs | 4 +- .../RetryingKubernetesPhysicalFileSystem.cs | 5 --- 6 files changed, 18 insertions(+), 47 deletions(-) diff --git a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs index 7800ea9ad..f004248bb 100644 --- a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs @@ -20,7 +20,6 @@ public interface IOctopusFileSystem string ReadFile(string path, bool withRetry = true); void OverwriteFile(string path, string contents); void OverwriteFile(string path, string contents, Encoding encoding); - void AtomicOverwriteFile(string path, string contents); void CopyFile(string source, string destination, bool overwrite); Stream OpenFile(string path, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read); Stream OpenFile(string path, FileMode mode = FileMode.OpenOrCreate, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read); diff --git a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs index 9eeb8c093..c2f45cfab 100644 --- a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs @@ -252,40 +252,6 @@ public void WriteAllText(string path, string contents) File.WriteAllText(path, contents); } - // Readers see either the old or the new contents, never a partly written file. - public void AtomicOverwriteFile(string path, string contents) - { - var temporaryPath = TemporaryPathBeside(path); - try - { - File.WriteAllText(temporaryPath, contents); -#if NET - File.Move(temporaryPath, path, overwrite: true); -#else - if (File.Exists(path)) - File.Replace(temporaryPath, path, null); - else - File.Move(temporaryPath, path); -#endif - } - finally - { - DeleteIfExists(temporaryPath); - } - } - - static void DeleteIfExists(string path) - { - if (File.Exists(path)) - { - File.Delete(path); - } - } - - // In the same directory, so it is on the same file system and can be moved or linked into place atomically. - static string TemporaryPathBeside(string path) - => path + "." + Guid.NewGuid().ToString("N") + ".tmp"; - #if NET [UnsupportedOSPlatform("windows")] public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents) @@ -324,6 +290,17 @@ static void CreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) stream.Flush(flushToDisk: true); } + static void DeleteIfExists(string path) + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + + // In the same directory, so it is on the same file system and can be linked into place atomically. + static string TemporaryPathBeside(string path) + => path + "." + Guid.NewGuid().ToString("N") + ".tmp"; #else public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents) => throw new PlatformNotSupportedException(UserOnlyFilesAreUnixOnly); diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceStoreFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceStoreFixture.cs index 68c9594aa..9d021e1bc 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceStoreFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceStoreFixture.cs @@ -33,7 +33,7 @@ public void ListInstance_NoRegistryEntries_ShouldListFromFileSystem() { registryStore.GetListFromRegistry().Returns(Enumerable.Empty()); fileSystem.DirectoryExists(Arg.Any()).Returns(true); - fileSystem.EnumerateFiles(Arg.Any(), Arg.Any()).Returns(new List { "file1", "file2" }); + fileSystem.EnumerateFiles(Arg.Any()).Returns(new List { "file1", "file2" }); fileSystem.FileExists(Arg.Any()).Returns(true); fileSystem.ReadFile(Arg.Is("file1")).Returns("{\"Name\": \"instance1\",\"ConfigurationFilePath\": \"configFilePath1\"}"); fileSystem.ReadFile(Arg.Is("file2")).Returns("{\"Name\": \"instance2\",\"ConfigurationFilePath\": \"configFilePath2\"}"); @@ -77,7 +77,7 @@ public void ListInstance_ShouldPreferFileSystemEntries() new ApplicationInstanceRecord("instance2", "registryFilePath2") }); fileSystem.DirectoryExists(Arg.Any()).Returns(true); - fileSystem.EnumerateFiles(Arg.Any(), Arg.Any()).Returns(new List { "file1", "file2" }); + fileSystem.EnumerateFiles(Arg.Any()).Returns(new List { "file1", "file2" }); fileSystem.FileExists(Arg.Any()).Returns(true); fileSystem.ReadFile(Arg.Is("file1")).Returns("{\"Name\": \"instance2\",\"ConfigurationFilePath\": \"fileConfigFilePath2\"}"); fileSystem.ReadFile(Arg.Is("file2")).Returns("{\"Name\": \"instance3\",\"ConfigurationFilePath\": \"fileConfigFilePath3\"}"); @@ -99,7 +99,7 @@ public void GetInstance_ShouldPreferFileSystemEntries() fileSystem.DirectoryExists(Arg.Any()).Returns(true); fileSystem.FileExists(Arg.Any()).Returns(true); - fileSystem.EnumerateFiles(instanceStore.InstancesFolder, "*.config").Returns(new[] { configFilename}); + fileSystem.EnumerateFiles(instanceStore.InstancesFolder).Returns(new[] { configFilename}); fileSystem.ReadFile(Arg.Is(configFilename)).Returns("{\"Name\": \"instance 1\",\"ConfigurationFilePath\": \"fileConfigFilePath2\"}"); var instance = instanceStore.LoadInstanceDetails("instance 1"); @@ -128,7 +128,7 @@ public void MigrateInstance() instanceStore.MigrateInstance(sourceInstance); fileSystem.Received().CreateDirectory(Arg.Any()); - fileSystem.Received().AtomicOverwriteFile(Arg.Is(x => x.Contains(sourceInstance.InstanceName)), Arg.Is(x => x.Contains(sourceInstance.ConfigurationFilePath))); + fileSystem.Received().OverwriteFile(Arg.Is(x => x.Contains(sourceInstance.InstanceName)), Arg.Is(x => x.Contains(sourceInstance.ConfigurationFilePath))); //we explicitly dont want to delete from the registry here, as we want to allow for customers who try to upgrade and have issues //but then rollback the database and install the old version. This would be a nasty thing to deal with in an already bad experience. diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs index 39a1bb049..c6d286e9c 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs @@ -28,7 +28,7 @@ public LinuxMachineIdKey(IOctopusFileSystem fileSystem) { return (GetMachineId(), Iv); } - + byte[] GetMachineId() { if (!fileSystem.FileExists(FileName)) diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceStore.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceStore.cs index 94e967e28..4c2aacfe4 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceStore.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceStore.cs @@ -103,7 +103,7 @@ public IList ListInstances() var listFromRegistry = registryApplicationInstanceStore.GetListFromRegistry(); var listFromFileSystem = new List(); if (fileSystem.DirectoryExists(InstancesFolder)) - listFromFileSystem = fileSystem.EnumerateFiles(InstancesFolder, "*.config") + listFromFileSystem = fileSystem.EnumerateFiles(InstancesFolder) .Select(LoadInstanceConfiguration) .Select(instance => new ApplicationInstanceRecord(instance.Name, instance.ConfigurationFilePath)) .ToList(); @@ -198,7 +198,7 @@ void WriteInstanceConfiguration(Instance instance, string path) var data = JsonConvert.SerializeObject(instance, Formatting.Indented); try { - fileSystem.AtomicOverwriteFile(path, data); + fileSystem.OverwriteFile(path, data); } catch (UnauthorizedAccessException ex) { diff --git a/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs b/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs index 43284dcfe..6cdc1f477 100644 --- a/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs @@ -90,11 +90,6 @@ public void OverwriteFile(string path, string contents, Encoding encoding) syncRetryPolicy.Execute(() => inner.OverwriteFile(path, contents, encoding)); } - public void AtomicOverwriteFile(string path, string contents) - { - syncRetryPolicy.Execute(() => inner.AtomicOverwriteFile(path, contents)); - } - public void CopyFile(string source, string destination, bool overwrite) { syncRetryPolicy.Execute(() => inner.CopyFile(source, destination, overwrite)); From e13995328dcf838226c8e8c894bb200ea9070383 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:39:49 +1100 Subject: [PATCH 088/124] Decrypt protected settings outside the parse catch so their recovery message is not hidden --- .../ProtectedSettingDecryptionException.cs | 16 +++ .../FlatDictionaryKeyValueStore.cs | 98 +++++++++---------- 2 files changed, 63 insertions(+), 51 deletions(-) create mode 100644 source/Octopus.Tentacle/Configuration/Crypto/ProtectedSettingDecryptionException.cs diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ProtectedSettingDecryptionException.cs b/source/Octopus.Tentacle/Configuration/Crypto/ProtectedSettingDecryptionException.cs new file mode 100644 index 000000000..4be6dec31 --- /dev/null +++ b/source/Octopus.Tentacle/Configuration/Crypto/ProtectedSettingDecryptionException.cs @@ -0,0 +1,16 @@ +using System; + +namespace Octopus.Tentacle.Configuration.Crypto +{ + public class ProtectedSettingDecryptionException : Exception + { + public ProtectedSettingDecryptionException(string settingName, Exception inner) + // Include inner message so it shows when Tentacle is run on the command line. + : base($"Unable to decrypt the protected configuration setting '{settingName}'. {inner.Message}", inner) + { + SettingName = settingName; + } + + public string SettingName { get; } + } +} diff --git a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs index 354246a98..4d85dd4ec 100644 --- a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs @@ -19,68 +19,72 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti public override TData? Get(string name, TData? defaultValue = default, ProtectionLevel protectionLevel = ProtectionLevel.None) where TData : default { - if (name == null) throw new ArgumentNullException(nameof(name)); - - string? valueAsString = null; - try + if (name == null) { - var data = Read(name); - if (data == null) - return defaultValue; - valueAsString = data as string; - if (valueAsString == null || string.IsNullOrWhiteSpace(valueAsString)) - return defaultValue; - - if (protectionLevel == ProtectionLevel.MachineKey) - data = Decrypt(name, valueAsString); - - if (typeof(TData) == typeof(string)) - return (TData)data; - if (typeof(TData) == typeof(bool)) //bool is tricky - .NET uses 'True', whereas JSON uses 'true' - need to allow both, because UX/legacy - return (TData)(object)bool.Parse((string)data); - if (typeof(TData).IsEnum) - return (TData)Enum.Parse(typeof(TData), ((string)data).Trim('"')); + throw new ArgumentNullException(nameof(name)); + } - return JsonConvert.DeserializeObject((string)data, JsonSerializerSettings); + if (Read(name) is not string valueAsString || string.IsNullOrWhiteSpace(valueAsString)) + { + return defaultValue; } - catch (Exception e) when (e is not DecryptionFailedException) + + if (protectionLevel == ProtectionLevel.MachineKey) { - if (protectionLevel == ProtectionLevel.None) - throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'. Value was '{valueAsString}'.", e); - throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'.", e); + valueAsString = Decrypt(name, valueAsString); } + + return Parse(name, valueAsString, protectionLevel); } public (bool foundResult, TData? value) TryGet(string name, ProtectionLevel protectionLevel = ProtectionLevel.None) { - if (name == null) throw new ArgumentNullException(nameof(name)); + if (name == null) + { + throw new ArgumentNullException(nameof(name)); + } - string? valueAsString = null; - try + if (Read(name) is not string valueAsString || string.IsNullOrWhiteSpace(valueAsString)) { - var data = Read(name); - if (data == null) - return (false, default!); - valueAsString = data as string; - if (valueAsString == null || string.IsNullOrWhiteSpace(valueAsString)) - return (false, default!); + return (false, default!); + } - if (protectionLevel == ProtectionLevel.MachineKey) - data = Decrypt(name, valueAsString); + if (protectionLevel == ProtectionLevel.MachineKey) + { + valueAsString = Decrypt(name, valueAsString); + } + return (true, Parse(name, valueAsString, protectionLevel)); + } + + TData? Parse(string name, string value, ProtectionLevel protectionLevel) + { + try + { if (typeof(TData) == typeof(string)) - return (true, (TData)data); + { + return (TData)(object)value; + } + if (typeof(TData) == typeof(bool)) //bool is tricky - .NET uses 'True', whereas JSON uses 'true' - need to allow both, because UX/legacy - return (true, (TData)(object)bool.Parse((string)data)); + { + return (TData)(object)bool.Parse(value); + } + if (typeof(TData).IsEnum) - return (true, (TData)Enum.Parse(typeof(TData), ((string)data).Trim('"'))); + { + return (TData)Enum.Parse(typeof(TData), value.Trim('"')); + } - return (true, JsonConvert.DeserializeObject((string)data, JsonSerializerSettings)); + return JsonConvert.DeserializeObject(value, JsonSerializerSettings); } - catch (Exception e) when (e is not DecryptionFailedException) + catch (Exception e) { if (protectionLevel == ProtectionLevel.None) - throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'. Value was '{valueAsString}'.", e); + { + throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'. Value was '{value}'.", e); + } + throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'.", e); } } @@ -93,15 +97,7 @@ string Decrypt(string name, string value) } catch (Exception e) { - // The console does not always print inner messages, and this one says how to recover. - throw new DecryptionFailedException($"Unable to decrypt the protected configuration setting '{name}'. {e.Message}", e); - } - } - - class DecryptionFailedException : FormatException - { - public DecryptionFailedException(string message, Exception inner) : base(message, inner) - { + throw new ProtectedSettingDecryptionException(name, e); } } From 1bc0bfd8a41194fb508cdb6d2a352831d905eeaf Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:45:37 +1100 Subject: [PATCH 089/124] Shorten the hierarchical store's encryption guard comment --- .../Configuration/HierarchicalDictionaryKeyValueStore.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs index e72ea0655..7119fcaf2 100644 --- a/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs @@ -25,8 +25,7 @@ public override bool Set(string name, TData value, ProtectionLevel protec var valueAsObject = (object)value; - // This store only ever backs `show-configuration` output, which is never read back by Tentacle, so there is - // no key it could sensibly be encrypted with. Refuse rather than write a secret somewhere nothing can decrypt. + // This store can only be used for reading. if (protectionLevel == ProtectionLevel.MachineKey) throw new NotSupportedException($"{GetType().Name} cannot store {nameof(ProtectionLevel.MachineKey)} values; it is only used to display configuration."); From bd84f3eb2525b308c21c286d9f74c5bf31468f96 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:46:13 +1100 Subject: [PATCH 090/124] Say the hierarchical store is only for display --- .../Configuration/HierarchicalDictionaryKeyValueStore.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs index 7119fcaf2..134ec4d8d 100644 --- a/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs @@ -25,7 +25,7 @@ public override bool Set(string name, TData value, ProtectionLevel protec var valueAsObject = (object)value; - // This store can only be used for reading. + // This store is only used to display configuration. if (protectionLevel == ProtectionLevel.MachineKey) throw new NotSupportedException($"{GetType().Name} cannot store {nameof(ProtectionLevel.MachineKey)} values; it is only used to display configuration."); From 6e57e5dc5b0192a9a02c9fd5fbec8b67226451a8 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:51:02 +1100 Subject: [PATCH 091/124] Drop the unused encryption guard from the display-only configuration store --- .../Configuration/HierarchicalDictionaryKeyValueStore.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs index 134ec4d8d..94caea416 100644 --- a/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs @@ -25,10 +25,6 @@ public override bool Set(string name, TData value, ProtectionLevel protec var valueAsObject = (object)value; - // This store is only used to display configuration. - if (protectionLevel == ProtectionLevel.MachineKey) - throw new NotSupportedException($"{GetType().Name} cannot store {nameof(ProtectionLevel.MachineKey)} values; it is only used to display configuration."); - Write(name, valueAsObject); if (AutoSaveOnSet) return Save(); From 247cd31b9401f37233c2e16890fa6253457c92ec Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 11:53:14 +1100 Subject: [PATCH 092/124] Skip encrypted values in show-configuration output --- .../Configuration/HierarchicalDictionaryKeyValueStore.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs index 94caea416..770c89235 100644 --- a/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/HierarchicalDictionaryKeyValueStore.cs @@ -15,6 +15,12 @@ public override bool Set(string name, TData value, ProtectionLevel protec { if (name == null) throw new ArgumentNullException(nameof(name)); + // Encrypted values are not displayed in show-configuration. + if (protectionLevel == ProtectionLevel.MachineKey) + { + return true; + } + if (value == null || value is string s && string.IsNullOrWhiteSpace(s)) { Write(name, null); From eb5f992c9e5aeb77b4ebe40f5bb465682b16335f Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 13:19:40 +1100 Subject: [PATCH 093/124] Rename TentacleConfigurationUpgrade to ConfigurationEncryptionUpgrade --- .../Commands/ReplaceCertificateCommandTests.cs | 2 +- .../Commands/RunAgentCommandFixture.cs | 6 +++--- source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs | 4 ++-- .../Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs | 4 ++-- source/Octopus.Tentacle/Commands/RunAgentCommand.cs | 4 ++-- .../Commands/UpgradeConfigurationEncryptionCommand.cs | 4 ++-- ...gurationUpgrade.cs => ConfigurationEncryptionUpgrade.cs} | 6 +++--- .../Octopus.Tentacle/Configuration/ConfigurationModule.cs | 2 +- source/Octopus.Tentacle/Startup/ServiceCommand.cs | 4 ++-- 9 files changed, 18 insertions(+), 18 deletions(-) rename source/Octopus.Tentacle/Configuration/{TentacleConfigurationUpgrade.cs => ConfigurationEncryptionUpgrade.cs} (94%) diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs index c19fb938d..175e5ccf7 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs @@ -99,7 +99,7 @@ static void ReplaceCertificate(TemporaryTentacleConfiguration tentacle, FakeOcto => new ReplaceCertificateCommand( new Lazy(() => tentacle.Configuration), new Lazy(() => new CertificateGenerator(new NullLog())), - new Lazy(() => Substitute.For()), + new Lazy(() => Substitute.For()), octopus.ClientInitializer, Substitute.For(), Substitute.For(), diff --git a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs index 40ec49814..7071e8097 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs @@ -29,7 +29,7 @@ public class RunAgentCommandFixture : CommandFixture IHomeConfiguration home = null!; IApplicationInstanceSelector selector = null!; IBackgroundTask[] backgroundTasks = null!; - ITentacleConfigurationUpgrade configurationUpgrade = null!; + IConfigurationEncryptionUpgrade configurationUpgrade = null!; [SetUp] public override void SetUp() @@ -42,7 +42,7 @@ public override void SetUp() tentacleConfiguration.TentacleCertificate.Returns(certificate); home = Substitute.For(); sleep = Substitute.For(); - configurationUpgrade = Substitute.For(); + configurationUpgrade = Substitute.For(); backgroundTasks = new[] { @@ -63,7 +63,7 @@ public override void SetUp() new AppVersion(GetType().Assembly), Substitute.For(), backgroundTasks.Select(bt => new Lazy(() => bt)).ToList(), - new Lazy(() => configurationUpgrade)); + new Lazy(() => configurationUpgrade)); selector.Current.Returns(new ApplicationInstanceConfiguration("MyTentacle", null, null, null)); } diff --git a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs index c3cfd45c5..90aaf93da 100644 --- a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs +++ b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs @@ -8,12 +8,12 @@ namespace Octopus.Tentacle.Commands public class CreateInstanceCommand : AbstractCommand { readonly IApplicationInstanceManager instanceManager; - readonly Lazy configurationUpgrade; + readonly Lazy configurationUpgrade; string instanceName = null!; string config = null!; string home = null!; - public CreateInstanceCommand(IApplicationInstanceManager instanceManager, ILogFileOnlyLogger logFileOnlyLogger, Lazy configurationUpgrade) : base(logFileOnlyLogger) + public CreateInstanceCommand(IApplicationInstanceManager instanceManager, ILogFileOnlyLogger logFileOnlyLogger, Lazy configurationUpgrade) : base(logFileOnlyLogger) { this.instanceManager = instanceManager; this.configurationUpgrade = configurationUpgrade; diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs index e2c26cc00..4289e04be 100644 --- a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -20,7 +20,7 @@ public class ReplaceCertificateCommand : AbstractStandardCommand { readonly Lazy configuration; readonly Lazy certificateGenerator; - readonly Lazy configurationUpgrade; + readonly Lazy configurationUpgrade; readonly IOctopusClientInitializer octopusClientInitializer; readonly IProxyConfigParser proxyConfig; readonly ISystemLog log; @@ -30,7 +30,7 @@ public class ReplaceCertificateCommand : AbstractStandardCommand public ReplaceCertificateCommand( Lazy configuration, Lazy certificateGenerator, - Lazy configurationUpgrade, + Lazy configurationUpgrade, IOctopusClientInitializer octopusClientInitializer, IProxyConfigParser proxyConfig, ISystemLog log, diff --git a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs index 2c74704af..591b4b08a 100644 --- a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs +++ b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs @@ -27,7 +27,7 @@ public class RunAgentCommand : AbstractStandardCommand readonly Lazy home; readonly Lazy proxyConfiguration; readonly Lazy proxyInitializer; - readonly Lazy configurationUpgrade; + readonly Lazy configurationUpgrade; readonly ISleep sleep; readonly ISystemLog log; @@ -53,7 +53,7 @@ public RunAgentCommand( AppVersion appVersion, ILogFileOnlyLogger logFileOnlyLogger, IEnumerable> backgroundTasks, - Lazy configurationUpgrade) : base(selector, log, logFileOnlyLogger) + Lazy configurationUpgrade) : base(selector, log, logFileOnlyLogger) { this.halibut = halibut; this.configuration = configuration; diff --git a/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs b/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs index 76e5121b7..f4c382188 100644 --- a/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs +++ b/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs @@ -9,12 +9,12 @@ namespace Octopus.Tentacle.Commands { public class UpgradeConfigurationEncryptionCommand : AbstractStandardCommand { - readonly Lazy configurationUpgrade; + readonly Lazy configurationUpgrade; readonly IApplicationInstanceSelector instanceSelector; readonly ISystemLog log; public UpgradeConfigurationEncryptionCommand( - Lazy configurationUpgrade, + Lazy configurationUpgrade, IApplicationInstanceSelector instanceSelector, ISystemLog log, ILogFileOnlyLogger logFileOnlyLogger) diff --git a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs b/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs similarity index 94% rename from source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs rename to source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs index daa7272a7..59d97826f 100644 --- a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs +++ b/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs @@ -9,7 +9,7 @@ namespace Octopus.Tentacle.Configuration { - public interface ITentacleConfigurationUpgrade + public interface IConfigurationEncryptionUpgrade { // Creates the configuration encryption key if it is missing, and gives it to the configuration's owner when running as root. void PrepareKey(); @@ -23,7 +23,7 @@ public interface ITentacleConfigurationUpgrade } // Until Upgrade succeeds, Tentacle keeps working on the keys earlier versions used. - public class TentacleConfigurationUpgrade : ITentacleConfigurationUpgrade + public class ConfigurationEncryptionUpgrade : IConfigurationEncryptionUpgrade { public static readonly IReadOnlyList ProtectedSettingNames = new[] { @@ -38,7 +38,7 @@ public class TentacleConfigurationUpgrade : ITentacleConfigurationUpgrade readonly IOctopusFileSystem fileSystem; readonly ISystemLog log; - public TentacleConfigurationUpgrade(IApplicationInstanceSelector instanceSelector, IOctopusFileSystem fileSystem, ISystemLog log) + public ConfigurationEncryptionUpgrade(IApplicationInstanceSelector instanceSelector, IOctopusFileSystem fileSystem, ISystemLog log) { this.instanceSelector = instanceSelector; this.fileSystem = fileSystem; diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs b/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs index edd1872ed..ae8e4ed2a 100644 --- a/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs +++ b/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs @@ -97,7 +97,7 @@ protected override void Load(ContainerBuilder builder) builder.RegisterType().As(); builder.RegisterType().As(); builder.RegisterType().As().SingleInstance(); - builder.RegisterType().As().SingleInstance(); + builder.RegisterType().As().SingleInstance(); //Even though these are Kubernetes types, we need to include them in this module as they are used lazily in the base types builder.RegisterType().SingleInstance(); diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs index a3949bce0..8716ff392 100644 --- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs +++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs @@ -17,7 +17,7 @@ public class ServiceCommand : AbstractCommand readonly IApplicationInstanceSelector instanceSelector; readonly ServiceConfigurationState serviceConfigurationState; readonly IServiceConfigurator serviceConfigurator; - readonly Lazy configurationUpgrade; + readonly Lazy configurationUpgrade; private readonly ISystemLog log; readonly string ServicePasswordEnvVar = "OCTOPUS_SERVICE_PASSWORD"; readonly string ServiceUsernameEnvVar = "OCTOPUS_SERVICE_USERNAME"; @@ -32,7 +32,7 @@ public ServiceCommand(ApplicationName applicationName, IServiceConfigurator serviceConfigurator, ISystemLog log, ILogFileOnlyLogger logFileOnlyLogger, - Lazy configurationUpgrade) + Lazy configurationUpgrade) : base(logFileOnlyLogger) { this.configurationUpgrade = configurationUpgrade; From 564a1758957bb6f289ba7b89833cf404e431a04a Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 13:24:42 +1100 Subject: [PATCH 094/124] Mark the Linux unit test Docker script as local only --- testing/README.md | 6 +++--- ...cker.sh => local-only-run-linux-unit-tests-in-docker.sh} | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) rename testing/{run-linux-unit-tests-in-docker.sh => local-only-run-linux-unit-tests-in-docker.sh} (82%) diff --git a/testing/README.md b/testing/README.md index 3d3ea44b8..c157b4100 100644 --- a/testing/README.md +++ b/testing/README.md @@ -42,12 +42,12 @@ The script runs in four stages, each of which can be skipped: The `e2e` stage needs an Octopus Server licence, because an unlicensed server enforces a limit of 0 targets and no Tentacle can register. Set `OCTOPUS_SERVER_BASE64_LICENSE`, or let the script read a development licence from 1Password when run interactively. Without one, the stage still verifies configuration and server connectivity up to the licence refusal. Pass `--no-1password` anywhere `op` must not run. -## Linux-only unit tests +## Local only: Linux-only unit tests on macOS or Windows -Tests marked `[LinuxTest]` are skipped on macOS and Windows. [`run-linux-unit-tests-in-docker.sh`](./run-linux-unit-tests-in-docker.sh) runs them in a .NET SDK container for the host's architecture, as root and then as a non-root user: +**For running on a dev machine only. CI does not use this script.** Tests marked `[LinuxTest]` are skipped on macOS and Windows. [`local-only-run-linux-unit-tests-in-docker.sh`](./local-only-run-linux-unit-tests-in-docker.sh) runs them in a .NET SDK container for the host's architecture, as root and then as a non-root user: ``` -./testing/run-linux-unit-tests-in-docker.sh [dotnet test filter] +./testing/local-only-run-linux-unit-tests-in-docker.sh [dotnet test filter] ``` ## Linux Packages diff --git a/testing/run-linux-unit-tests-in-docker.sh b/testing/local-only-run-linux-unit-tests-in-docker.sh similarity index 82% rename from testing/run-linux-unit-tests-in-docker.sh rename to testing/local-only-run-linux-unit-tests-in-docker.sh index 21ad61ed2..7168716f1 100755 --- a/testing/run-linux-unit-tests-in-docker.sh +++ b/testing/local-only-run-linux-unit-tests-in-docker.sh @@ -1,9 +1,9 @@ #!/usr/bin/env bash # -# Runs Linux-only unit tests in a .NET SDK container for this host's architecture, first as root and then as a +# LOCAL ONLY, not used by CI. Runs Linux-only unit tests in a .NET SDK container for this host's architecture, first as root and then as a # non-root user. # -# Usage: ./testing/run-linux-unit-tests-in-docker.sh [dotnet test filter] +# Usage: ./testing/local-only-run-linux-unit-tests-in-docker.sh [dotnet test filter] # set -euo pipefail From ab5d1c6da085be73b5df3b542748ee9b7e7a6cca Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 13:25:40 +1100 Subject: [PATCH 095/124] Move the local-only Linux unit test script into testing/local --- testing/README.md | 4 ++-- .../run-linux-unit-tests-in-docker.sh} | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) rename testing/{local-only-run-linux-unit-tests-in-docker.sh => local/run-linux-unit-tests-in-docker.sh} (88%) diff --git a/testing/README.md b/testing/README.md index c157b4100..983c45177 100644 --- a/testing/README.md +++ b/testing/README.md @@ -44,10 +44,10 @@ The `e2e` stage needs an Octopus Server licence, because an unlicensed server en ## Local only: Linux-only unit tests on macOS or Windows -**For running on a dev machine only. CI does not use this script.** Tests marked `[LinuxTest]` are skipped on macOS and Windows. [`local-only-run-linux-unit-tests-in-docker.sh`](./local-only-run-linux-unit-tests-in-docker.sh) runs them in a .NET SDK container for the host's architecture, as root and then as a non-root user: +**For running on a dev machine only. CI does not use this script.** Tests marked `[LinuxTest]` are skipped on macOS and Windows. [`local/run-linux-unit-tests-in-docker.sh`](./local/run-linux-unit-tests-in-docker.sh) runs them in a .NET SDK container for the host's architecture, as root and then as a non-root user: ``` -./testing/local-only-run-linux-unit-tests-in-docker.sh [dotnet test filter] +./testing/local/run-linux-unit-tests-in-docker.sh [dotnet test filter] ``` ## Linux Packages diff --git a/testing/local-only-run-linux-unit-tests-in-docker.sh b/testing/local/run-linux-unit-tests-in-docker.sh similarity index 88% rename from testing/local-only-run-linux-unit-tests-in-docker.sh rename to testing/local/run-linux-unit-tests-in-docker.sh index 7168716f1..adcc5811a 100755 --- a/testing/local-only-run-linux-unit-tests-in-docker.sh +++ b/testing/local/run-linux-unit-tests-in-docker.sh @@ -3,11 +3,11 @@ # LOCAL ONLY, not used by CI. Runs Linux-only unit tests in a .NET SDK container for this host's architecture, first as root and then as a # non-root user. # -# Usage: ./testing/local-only-run-linux-unit-tests-in-docker.sh [dotnet test filter] +# Usage: ./testing/local/run-linux-unit-tests-in-docker.sh [dotnet test filter] # set -euo pipefail -REPO_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +REPO_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) FILTER=${1:-FullyQualifiedName~Octopus.Tentacle.Tests.Configuration} case "$(uname -m)" in arm64|aarch64) PLATFORM=linux/arm64 ;; From 3dc459003208d01625cbe64e6590322259687d36 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 13:33:06 +1100 Subject: [PATCH 096/124] Move the local Linux unit test script to its own PR --- testing/README.md | 8 ----- .../local/run-linux-unit-tests-in-docker.sh | 35 ------------------- 2 files changed, 43 deletions(-) delete mode 100755 testing/local/run-linux-unit-tests-in-docker.sh diff --git a/testing/README.md b/testing/README.md index 983c45177..ff979962b 100644 --- a/testing/README.md +++ b/testing/README.md @@ -42,14 +42,6 @@ The script runs in four stages, each of which can be skipped: The `e2e` stage needs an Octopus Server licence, because an unlicensed server enforces a limit of 0 targets and no Tentacle can register. Set `OCTOPUS_SERVER_BASE64_LICENSE`, or let the script read a development licence from 1Password when run interactively. Without one, the stage still verifies configuration and server connectivity up to the licence refusal. Pass `--no-1password` anywhere `op` must not run. -## Local only: Linux-only unit tests on macOS or Windows - -**For running on a dev machine only. CI does not use this script.** Tests marked `[LinuxTest]` are skipped on macOS and Windows. [`local/run-linux-unit-tests-in-docker.sh`](./local/run-linux-unit-tests-in-docker.sh) runs them in a .NET SDK container for the host's architecture, as root and then as a non-root user: - -``` -./testing/local/run-linux-unit-tests-in-docker.sh [dotnet test filter] -``` - ## Linux Packages Use [`linux-packages/test-packages-on-distros.sh`](./linux-packages/test-packages-on-distros.sh) to run NUKE's `TestLinuxPackages` target locally. That target installs the built `.deb`/`.rpm` on every distribution in the matrix in `build/Build.Tests.cs` and checks the installed Tentacle reports the expected version. diff --git a/testing/local/run-linux-unit-tests-in-docker.sh b/testing/local/run-linux-unit-tests-in-docker.sh deleted file mode 100755 index adcc5811a..000000000 --- a/testing/local/run-linux-unit-tests-in-docker.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash -# -# LOCAL ONLY, not used by CI. Runs Linux-only unit tests in a .NET SDK container for this host's architecture, first as root and then as a -# non-root user. -# -# Usage: ./testing/local/run-linux-unit-tests-in-docker.sh [dotnet test filter] -# -set -euo pipefail - -REPO_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) -FILTER=${1:-FullyQualifiedName~Octopus.Tentacle.Tests.Configuration} -case "$(uname -m)" in - arm64|aarch64) PLATFORM=linux/arm64 ;; - *) PLATFORM=linux/amd64 ;; -esac - -docker run --rm --platform "$PLATFORM" \ - -v "$REPO_DIR:/src:ro" \ - -e FILTER="$FILTER" \ - -e NUGET_PACKAGES=/work/.nuget-packages \ - mcr.microsoft.com/dotnet/sdk:10.0 \ - bash -euc ' - mkdir /work - tar -C /src --exclude=./.git --exclude="*/bin" --exclude="*/obj" --exclude=./_artifacts -cf - . | tar -C /work -xf - - cd /work - project=source/Octopus.Tentacle.Tests/Octopus.Tentacle.Tests.csproj - - echo "==> as root" - dotnet test "$project" -f net10.0 --filter "$FILTER" - - echo "==> as a non-root user" - useradd --create-home tester - chown -R tester /work - su tester -c "cd /work && NUGET_PACKAGES=$NUGET_PACKAGES dotnet test $project -f net10.0 --no-build --filter \"$FILTER\"" - ' From a44008e7d93229f0c1cbc69cce410a01c674af54 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 13:36:39 +1100 Subject: [PATCH 097/124] Rename configurationUpgrade to configurationEncryptionUpgrade --- .../Commands/RunAgentCommandFixture.cs | 6 +++--- source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs | 8 ++++---- .../Commands/ReplaceCertificateCommand.cs | 8 ++++---- source/Octopus.Tentacle/Commands/RunAgentCommand.cs | 8 ++++---- .../Commands/UpgradeConfigurationEncryptionCommand.cs | 8 ++++---- source/Octopus.Tentacle/Startup/ServiceCommand.cs | 8 ++++---- 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs index 7071e8097..f6707aed1 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs @@ -29,7 +29,7 @@ public class RunAgentCommandFixture : CommandFixture IHomeConfiguration home = null!; IApplicationInstanceSelector selector = null!; IBackgroundTask[] backgroundTasks = null!; - IConfigurationEncryptionUpgrade configurationUpgrade = null!; + IConfigurationEncryptionUpgrade configurationEncryptionUpgrade = null!; [SetUp] public override void SetUp() @@ -42,7 +42,7 @@ public override void SetUp() tentacleConfiguration.TentacleCertificate.Returns(certificate); home = Substitute.For(); sleep = Substitute.For(); - configurationUpgrade = Substitute.For(); + configurationEncryptionUpgrade = Substitute.For(); backgroundTasks = new[] { @@ -63,7 +63,7 @@ public override void SetUp() new AppVersion(GetType().Assembly), Substitute.For(), backgroundTasks.Select(bt => new Lazy(() => bt)).ToList(), - new Lazy(() => configurationUpgrade)); + new Lazy(() => configurationEncryptionUpgrade)); selector.Current.Returns(new ApplicationInstanceConfiguration("MyTentacle", null, null, null)); } diff --git a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs index 90aaf93da..ee32afc14 100644 --- a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs +++ b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs @@ -8,15 +8,15 @@ namespace Octopus.Tentacle.Commands public class CreateInstanceCommand : AbstractCommand { readonly IApplicationInstanceManager instanceManager; - readonly Lazy configurationUpgrade; + readonly Lazy configurationEncryptionUpgrade; string instanceName = null!; string config = null!; string home = null!; - public CreateInstanceCommand(IApplicationInstanceManager instanceManager, ILogFileOnlyLogger logFileOnlyLogger, Lazy configurationUpgrade) : base(logFileOnlyLogger) + public CreateInstanceCommand(IApplicationInstanceManager instanceManager, ILogFileOnlyLogger logFileOnlyLogger, Lazy configurationEncryptionUpgrade) : base(logFileOnlyLogger) { this.instanceManager = instanceManager; - this.configurationUpgrade = configurationUpgrade; + this.configurationEncryptionUpgrade = configurationEncryptionUpgrade; Options.Add("instance=", "Name of the instance to create", v => instanceName = v); Options.Add("config=", "Path to configuration file to create", v => config = v); Options.Add("home=", "[Optional] Path to the home directory - defaults to the same directory as the config file", v => home = v); @@ -34,7 +34,7 @@ protected override void Start() } // The key already exists; this gives it to the owner of a configuration file that was already there. - configurationUpgrade.Value.PrepareKey(); + configurationEncryptionUpgrade.Value.PrepareKey(); } } } diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs index 4289e04be..29e1bf92f 100644 --- a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -20,7 +20,7 @@ public class ReplaceCertificateCommand : AbstractStandardCommand { readonly Lazy configuration; readonly Lazy certificateGenerator; - readonly Lazy configurationUpgrade; + readonly Lazy configurationEncryptionUpgrade; readonly IOctopusClientInitializer octopusClientInitializer; readonly IProxyConfigParser proxyConfig; readonly ISystemLog log; @@ -30,7 +30,7 @@ public class ReplaceCertificateCommand : AbstractStandardCommand public ReplaceCertificateCommand( Lazy configuration, Lazy certificateGenerator, - Lazy configurationUpgrade, + Lazy configurationEncryptionUpgrade, IOctopusClientInitializer octopusClientInitializer, IProxyConfigParser proxyConfig, ISystemLog log, @@ -40,7 +40,7 @@ public ReplaceCertificateCommand( { this.configuration = configuration; this.certificateGenerator = certificateGenerator; - this.configurationUpgrade = configurationUpgrade; + this.configurationEncryptionUpgrade = configurationEncryptionUpgrade; this.octopusClientInitializer = octopusClientInitializer; this.proxyConfig = proxyConfig; this.log = log; @@ -75,7 +75,7 @@ async Task StartAsync() if (!keepCurrentCertificate) { // Creates a fresh configuration encryption key if it was lost, so the new certificate can be saved. - configurationUpgrade.Value.PrepareKey(); + configurationEncryptionUpgrade.Value.PrepareKey(); 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}"); diff --git a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs index 591b4b08a..ba8e9c078 100644 --- a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs +++ b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs @@ -27,7 +27,7 @@ public class RunAgentCommand : AbstractStandardCommand readonly Lazy home; readonly Lazy proxyConfiguration; readonly Lazy proxyInitializer; - readonly Lazy configurationUpgrade; + readonly Lazy configurationEncryptionUpgrade; readonly ISleep sleep; readonly ISystemLog log; @@ -53,13 +53,13 @@ public RunAgentCommand( AppVersion appVersion, ILogFileOnlyLogger logFileOnlyLogger, IEnumerable> backgroundTasks, - Lazy configurationUpgrade) : base(selector, log, logFileOnlyLogger) + Lazy configurationEncryptionUpgrade) : base(selector, log, logFileOnlyLogger) { this.halibut = halibut; this.configuration = configuration; this.home = home; this.proxyConfiguration = proxyConfiguration; - this.configurationUpgrade = configurationUpgrade; + this.configurationEncryptionUpgrade = configurationEncryptionUpgrade; this.sleep = sleep; this.log = log; this.selector = selector; @@ -101,7 +101,7 @@ protected override void Start() return; } - configurationUpgrade.Value.TryUpgrade(); + configurationEncryptionUpgrade.Value.TryUpgrade(); var currentPath = typeof(RunAgentCommand).Assembly.FullLocalPath(); var exePath = PlatformDetection.IsRunningOnWindows diff --git a/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs b/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs index f4c382188..450bb6e32 100644 --- a/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs +++ b/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs @@ -9,18 +9,18 @@ namespace Octopus.Tentacle.Commands { public class UpgradeConfigurationEncryptionCommand : AbstractStandardCommand { - readonly Lazy configurationUpgrade; + readonly Lazy configurationEncryptionUpgrade; readonly IApplicationInstanceSelector instanceSelector; readonly ISystemLog log; public UpgradeConfigurationEncryptionCommand( - Lazy configurationUpgrade, + Lazy configurationEncryptionUpgrade, IApplicationInstanceSelector instanceSelector, ISystemLog log, ILogFileOnlyLogger logFileOnlyLogger) : base(instanceSelector, log, logFileOnlyLogger) { - this.configurationUpgrade = configurationUpgrade; + this.configurationEncryptionUpgrade = configurationEncryptionUpgrade; this.instanceSelector = instanceSelector; this.log = log; } @@ -42,7 +42,7 @@ protected override void Start() + $"Register it with `create-instance --instance --config {instance.ConfigurationPath}`, then run this command again."); } - configurationUpgrade.Value.Upgrade(); + configurationEncryptionUpgrade.Value.Upgrade(); log.Info($"The configuration is protected with the encryption key `{instance.KeyFilePath}`."); } } diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs index 8716ff392..ec6a52304 100644 --- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs +++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs @@ -17,7 +17,7 @@ public class ServiceCommand : AbstractCommand readonly IApplicationInstanceSelector instanceSelector; readonly ServiceConfigurationState serviceConfigurationState; readonly IServiceConfigurator serviceConfigurator; - readonly Lazy configurationUpgrade; + readonly Lazy configurationEncryptionUpgrade; private readonly ISystemLog log; readonly string ServicePasswordEnvVar = "OCTOPUS_SERVICE_PASSWORD"; readonly string ServiceUsernameEnvVar = "OCTOPUS_SERVICE_USERNAME"; @@ -32,10 +32,10 @@ public ServiceCommand(ApplicationName applicationName, IServiceConfigurator serviceConfigurator, ISystemLog log, ILogFileOnlyLogger logFileOnlyLogger, - Lazy configurationUpgrade) + Lazy configurationEncryptionUpgrade) : base(logFileOnlyLogger) { - this.configurationUpgrade = configurationUpgrade; + this.configurationEncryptionUpgrade = configurationEncryptionUpgrade; this.applicationName = applicationName; this.instanceLocator = instanceLocator; this.instanceSelector = instanceSelector; @@ -129,7 +129,7 @@ protected override void Start() ConfigurationFilePermissions.RestrictToServiceUser(instanceSelector.Current.ConfigurationPath, serviceConfigurationState.Username, log); // A non-root service cannot create its key under /var/lib/octopus, so it is created here while running as root. - configurationUpgrade.Value.TryPrepareKey(); + configurationEncryptionUpgrade.Value.TryPrepareKey(); } } } From 90bb003aafb394c8e40b3543d62c495fdf1e5445 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 13:43:21 +1100 Subject: [PATCH 098/124] Explain why calling the runtime's stat shim is safe --- source/Octopus.Tentacle.Core/Util/UnixFile.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs index 6a6cec2c4..e6b15b13c 100644 --- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -65,7 +65,7 @@ public static void GiveTo(SafeFileHandle file, uint owner) [DllImport("libc", SetLastError = true)] static extern int fchown(SafeFileHandle fd, uint owner, uint group); - // The .NET runtime has no public API for a file's owner; its own stat shim has one struct layout on every libc and architecture. + // A private runtime shim, which is safe as Linux builds are self-contained and ship the runtime it belongs to. [DllImport("libSystem.Native", SetLastError = true)] static extern int SystemNative_Stat(string path, out FileStatus output); From 8a05a4d3389a60955f472024828c965985b421a1 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 13:44:47 +1100 Subject: [PATCH 099/124] Note the test that guards the stat shim layout --- source/Octopus.Tentacle.Core/Util/UnixFile.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs index e6b15b13c..609aeb4d2 100644 --- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -65,7 +65,7 @@ public static void GiveTo(SafeFileHandle file, uint owner) [DllImport("libc", SetLastError = true)] static extern int fchown(SafeFileHandle fd, uint owner, uint group); - // A private runtime shim, which is safe as Linux builds are self-contained and ship the runtime it belongs to. + // A private runtime shim: safe as Linux builds ship their own runtime, and test-linux-package.sh catches a layout change. [DllImport("libSystem.Native", SetLastError = true)] static extern int SystemNative_Stat(string path, out FileStatus output); From eb1f0da7e0e9ba5bab604c5558c9b7c51f725106 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 13:47:07 +1100 Subject: [PATCH 100/124] Stop telling users to regenerate the legacy machine key --- source/Octopus.Tentacle.Core/Util/UnixFile.cs | 6 ++++-- .../Configuration/Crypto/ConfigurationEncryptionKey.cs | 2 +- .../Configuration/Crypto/LinuxGeneratedMachineKey.cs | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs index 609aeb4d2..793193872 100644 --- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -64,8 +64,10 @@ public static void GiveTo(SafeFileHandle file, uint owner) [DllImport("libc", SetLastError = true)] static extern int fchown(SafeFileHandle fd, uint owner, uint group); - - // A private runtime shim: safe as Linux builds ship their own runtime, and test-linux-package.sh catches a layout change. + + // This is an internal shim that could change in the future, although it hasn't changed for years. + // This would only break when we update .net, which we do by commiting to this repo. Thus tests will catch the + // issue which would allow us to fix it. [DllImport("libSystem.Native", SetLastError = true)] static extern int SystemNative_Stat(string path, out FileStatus output); diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index 797d6cbd1..54b26d992 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -25,7 +25,7 @@ public class ConfigurationEncryptionKey const UnixFileMode TraversableByAll = OwnerOnly | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute; #endif - const string RecoveryWithoutBackup = "If there is no backup, the Tentacle's certificate is lost and it needs a new one: " + internal const string RecoveryWithoutBackup = "If there is no backup, the Tentacle's certificate is lost and it needs a new one: " + "run `replace-certificate` with an API key. " + "This creates a new key and certificate, and updates every deployment target and worker registered with the old certificate to trust it."; diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs index 5ce3821d4..46980e01b 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs @@ -43,7 +43,7 @@ public static string LegacyKeyFilePathForThisHost { throw new InvalidOperationException($"Machine key file at `{path}` is corrupt and cannot be loaded. " + "If this file previously contained a valid key to encrypt data, that data may no longer be retrievable. " - + $"Remove the file `{path}` and allow Octopus to regenerate the key."); + + "Restore it from a backup. " + ConfigurationEncryptionKey.RecoveryWithoutBackup); } } } From cf582a936cbc86fcbd21586513337aab2cb4badc Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 13:54:12 +1100 Subject: [PATCH 101/124] Explain why the upgrade loads the key first --- .../Configuration/ConfigurationEncryptionUpgrade.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs b/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs index 59d97826f..1b88ae5ad 100644 --- a/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs +++ b/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs @@ -75,6 +75,7 @@ public void Upgrade() } var (key, store) = prepared.Value; + // Verify the key loads, to prevent falling back to less secure legacy encryption keys. key.Load(); foreach (var name in ProtectedSettingNames) { From c9539bec55b900eb7b2199a78c550ec36c6290e9 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 13:59:36 +1100 Subject: [PATCH 102/124] Throw ControlledFailureException when the configuration key is missing on save --- .../Configuration/FlatDictionaryKeyValueStore.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs index 4d85dd4ec..f174fbd15 100644 --- a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs @@ -1,5 +1,4 @@ using System; -using System.Security.Cryptography; using Newtonsoft.Json; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Configuration.Instances; @@ -133,7 +132,7 @@ string EncryptWithoutDowngrading(string name, string raw) var encrypted = Encryptor.Encrypt(raw); if (Encryptor.RequiresReEncryption(encrypted) && Read(name) is string previous && !Encryptor.RequiresReEncryption(previous)) { - throw new CryptographicException($"Unable to update the protected setting '{name}': it is protected with the configuration encryption key, which is not available. Make sure the key file exists and is readable."); + throw new ControlledFailureException($"Unable to update the protected setting '{name}': it is protected with the configuration encryption key, which is not available. Make sure the key file exists and is readable."); } return encrypted; } From 54c796be519b90270fe519cf3ca0f02f5bf54435 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 14:00:53 +1100 Subject: [PATCH 103/124] Make keyFilePath a required ApplicationInstanceConfiguration parameter --- .../TentacleConfiguration/InstanceConfigurationLoader.cs | 2 +- .../Octopus.Tentacle.Tests/Commands/ConfigureCommandFixture.cs | 2 +- .../Commands/DeregisterMachineCommandFixture.cs | 2 +- .../Commands/DeregisterWorkerCommandFixture.cs | 2 +- .../Commands/ImportCertificateCommandFixture.cs | 2 +- source/Octopus.Tentacle.Tests/Commands/LivezCommandFixture.cs | 2 +- .../Commands/NewCertificateCommandFixture.cs | 2 +- .../Commands/ProxyConfigurationCommandFixture.cs | 2 +- .../RegisterKubernetesDeploymentTargetCommandFixture.cs | 2 +- .../Commands/RegisterKubernetesWorkerCommandFixture.cs | 2 +- .../Commands/RegisterMachineCommandFixture.cs | 2 +- .../Commands/RegisterWorkerCommandFixture.cs | 2 +- .../Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs | 2 +- .../Octopus.Tentacle.Tests/Commands/ServerCommsCommandTest.cs | 2 +- .../Commands/SetPollingConnectionCountCommandFixture.cs | 2 +- .../Support/TentacleConfigurationBuilder.cs | 2 +- .../Configuration/Instances/ApplicationInstanceConfiguration.cs | 2 +- 17 files changed, 17 insertions(+), 17 deletions(-) diff --git a/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs b/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs index fb6e13adb..06cf414af 100644 --- a/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs +++ b/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs @@ -118,7 +118,7 @@ public SimpleApplicationInstanceSelectorForTentacleManager( ApplicationInstanceConfiguration LoadInstance() { var (aggregatedKeyValueStore, writableConfig) = LoadConfigurationStore(configFilePath); - return new ApplicationInstanceConfiguration(null, configFilePath, aggregatedKeyValueStore, writableConfig); + return new ApplicationInstanceConfiguration(null, configFilePath, aggregatedKeyValueStore, writableConfig, null); } (IKeyValueStore, IWritableKeyValueStore) LoadConfigurationStore(string configurationPath) diff --git a/source/Octopus.Tentacle.Tests/Commands/ConfigureCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ConfigureCommandFixture.cs index 234cb44d5..352fec1f2 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ConfigureCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ConfigureCommandFixture.cs @@ -29,7 +29,7 @@ public override void SetUp() fileSystem = Substitute.For(); log = Substitute.For(); var selector = Substitute.For(); - selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); Command = new ConfigureCommand(new Lazy(() => tentacleConfiguration), new Lazy(() => new StubHomeConfiguration()), fileSystem, log, selector, Substitute.For()); } diff --git a/source/Octopus.Tentacle.Tests/Commands/DeregisterMachineCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/DeregisterMachineCommandFixture.cs index 5882078f5..81ca1c7d3 100644 --- a/source/Octopus.Tentacle.Tests/Commands/DeregisterMachineCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/DeregisterMachineCommandFixture.cs @@ -34,7 +34,7 @@ public override void SetUp() proxyConfig = Substitute.For(); log = Substitute.For(); selector = Substitute.For(); - selector.Current.Returns(new ApplicationInstanceConfiguration("my-instance", "myconfig.config", Substitute.For(), Substitute.For())); + selector.Current.Returns(new ApplicationInstanceConfiguration("my-instance", "myconfig.config", Substitute.For(), Substitute.For(), null)); } [Test] diff --git a/source/Octopus.Tentacle.Tests/Commands/DeregisterWorkerCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/DeregisterWorkerCommandFixture.cs index 9e56b9c77..b238f041f 100644 --- a/source/Octopus.Tentacle.Tests/Commands/DeregisterWorkerCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/DeregisterWorkerCommandFixture.cs @@ -34,7 +34,7 @@ public override void SetUp() proxyConfig = Substitute.For(); log = Substitute.For(); selector = Substitute.For(); - selector.Current.Returns(new ApplicationInstanceConfiguration("my-instance", "myconfig.config", Substitute.For(), Substitute.For())); + selector.Current.Returns(new ApplicationInstanceConfiguration("my-instance", "myconfig.config", Substitute.For(), Substitute.For(), null)); } [Test] diff --git a/source/Octopus.Tentacle.Tests/Commands/ImportCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ImportCertificateCommandFixture.cs index ad6693539..b6402c5b1 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ImportCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ImportCertificateCommandFixture.cs @@ -23,7 +23,7 @@ public void BeforeEachTest() { configuration = Substitute.For(); var selector = Substitute.For(); - selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); Command = new ImportCertificateCommand( new Lazy(() => configuration), Substitute.For(), diff --git a/source/Octopus.Tentacle.Tests/Commands/LivezCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/LivezCommandFixture.cs index 3fbca3536..0324d13d3 100644 --- a/source/Octopus.Tentacle.Tests/Commands/LivezCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/LivezCommandFixture.cs @@ -39,7 +39,7 @@ public override void SetUp() clock = Substitute.For(); instanceSelector = Substitute.For(); - instanceSelector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + instanceSelector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); Command = new LivezCommand( new Lazy(() => homeConfiguration), diff --git a/source/Octopus.Tentacle.Tests/Commands/NewCertificateCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/NewCertificateCommandFixture.cs index b32b20769..bb0be96e7 100644 --- a/source/Octopus.Tentacle.Tests/Commands/NewCertificateCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/NewCertificateCommandFixture.cs @@ -24,7 +24,7 @@ public override void SetUp() log = Substitute.For(); configuration = new StubTentacleConfiguration(); var selector = Substitute.For(); - selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); Command = new NewCertificateCommand(new Lazy(() => configuration), log, selector, new Lazy(() => Substitute.For()), Substitute.For()); } diff --git a/source/Octopus.Tentacle.Tests/Commands/ProxyConfigurationCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/ProxyConfigurationCommandFixture.cs index aa7973bb7..5ec688d9d 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ProxyConfigurationCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ProxyConfigurationCommandFixture.cs @@ -28,7 +28,7 @@ public void SetupForEachTest() configFile = $"{homeDirectory}\\File.config"; applicationInstanceSelector = Substitute.For(); - applicationInstanceSelector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + applicationInstanceSelector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); octopusFileSystem.AppendToFile(configFile, "\n" + diff --git a/source/Octopus.Tentacle.Tests/Commands/RegisterKubernetesDeploymentTargetCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RegisterKubernetesDeploymentTargetCommandFixture.cs index 92b6ac46a..400778aff 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RegisterKubernetesDeploymentTargetCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RegisterKubernetesDeploymentTargetCommandFixture.cs @@ -58,7 +58,7 @@ public void BeforeEachTest() octopusClientInitializer.CreateClient(Arg.Any(), false) .Returns(Task.FromResult(octopusAsyncClient)); var selector = Substitute.For(); - selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); Command = new RegisterKubernetesDeploymentTargetCommand(new Lazy(() => operation), new Lazy(() => configuration), log, diff --git a/source/Octopus.Tentacle.Tests/Commands/RegisterKubernetesWorkerCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RegisterKubernetesWorkerCommandFixture.cs index 88c8c3f18..4f18808fd 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RegisterKubernetesWorkerCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RegisterKubernetesWorkerCommandFixture.cs @@ -59,7 +59,7 @@ public void BeforeEachTest() .Returns(Task.FromResult(octopusAsyncClient)); var applicationInstanceSelector = Substitute.For(); - applicationInstanceSelector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + applicationInstanceSelector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); Command = new RegisterKubernetesWorkerCommand(new Lazy(() => operation), new Lazy(() => configuration), diff --git a/source/Octopus.Tentacle.Tests/Commands/RegisterMachineCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RegisterMachineCommandFixture.cs index 83436c641..4fc206253 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RegisterMachineCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RegisterMachineCommandFixture.cs @@ -70,7 +70,7 @@ public void BeforeEachTest() octopusClientInitializer.CreateClient(Arg.Any(), false) .Returns(Task.FromResult(octopusAsyncClient)); var selector = Substitute.For(); - selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); Command = new RegisterMachineCommand(new Lazy(() => operation), new Lazy(() => configuration), log, diff --git a/source/Octopus.Tentacle.Tests/Commands/RegisterWorkerCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RegisterWorkerCommandFixture.cs index a2dabad09..96ee5c158 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RegisterWorkerCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RegisterWorkerCommandFixture.cs @@ -60,7 +60,7 @@ public void BeforeEachTest() .Returns(Task.FromResult(octopusAsyncClient)); var applicationInstanceSelector = Substitute.For(); - applicationInstanceSelector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + applicationInstanceSelector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); Command = new RegisterWorkerCommand(new Lazy(() => operation), new Lazy(() => configuration), diff --git a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs index f6707aed1..b960d6e19 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs @@ -65,7 +65,7 @@ public override void SetUp() backgroundTasks.Select(bt => new Lazy(() => bt)).ToList(), new Lazy(() => configurationEncryptionUpgrade)); - selector.Current.Returns(new ApplicationInstanceConfiguration("MyTentacle", null, null, null)); + selector.Current.Returns(new ApplicationInstanceConfiguration("MyTentacle", null, null, null, null)); } [Test] diff --git a/source/Octopus.Tentacle.Tests/Commands/ServerCommsCommandTest.cs b/source/Octopus.Tentacle.Tests/Commands/ServerCommsCommandTest.cs index 6994c9c5f..8d26260e9 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ServerCommsCommandTest.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ServerCommsCommandTest.cs @@ -27,7 +27,7 @@ public void SetUp() { configuration = new StubTentacleConfiguration(); var selector = Substitute.For(); - selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); command = new ServerCommsCommand( new Lazy(() => configuration), new InMemoryLog(), diff --git a/source/Octopus.Tentacle.Tests/Commands/SetPollingConnectionCountCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/SetPollingConnectionCountCommandFixture.cs index 917aefa2c..7f99ae9fb 100644 --- a/source/Octopus.Tentacle.Tests/Commands/SetPollingConnectionCountCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/SetPollingConnectionCountCommandFixture.cs @@ -23,7 +23,7 @@ public override void SetUp() tentacleConfiguration = new StubTentacleConfiguration(); var log = Substitute.For(); var selector = Substitute.For(); - selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!)); + selector.Current.Returns(info => new ApplicationInstanceConfiguration(null, null!, null!, null!, null)); Command = new SetPollingConnectionCountCommand( new Lazy(() => tentacleConfiguration), selector, diff --git a/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs index e2b289604..44155ff9b 100644 --- a/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs +++ b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs @@ -29,7 +29,7 @@ public TemporaryTentacleConfiguration Build() var store = new XmlFileKeyValueStore(fileSystem, configFile, encryptor: TestMachineKeyEncryptor.Current); var selector = Substitute.For(); - selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, configFile, store, store)); + selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, configFile, store, store, null)); var configuration = new WritableTentacleConfiguration( selector, diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceConfiguration.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceConfiguration.cs index c7fb6fabd..b96508266 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceConfiguration.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceConfiguration.cs @@ -8,7 +8,7 @@ public ApplicationInstanceConfiguration( string? configurationPath, IKeyValueStore? configuration, IWritableKeyValueStore? writableConfiguration, - string? keyFilePath = null) + string? keyFilePath) { KeyFilePath = keyFilePath; InstanceName = instanceName; From 0f605889f1241d535be9738840ca15d66ad79a3c Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 14:01:50 +1100 Subject: [PATCH 104/124] Fix stale comment wording and add missing braces --- .../Configuration/Crypto/LinuxMachineKeyEncryptor.cs | 2 +- .../Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs index 682529aa7..d1cdbb80f 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs @@ -40,7 +40,7 @@ static bool IsLegacyCiphertext(string encrypted) public bool RequiresReEncryption(string encrypted) => IsLegacyCiphertext(encrypted); - // Until the configuration upgrade has created the key, values are written the way earlier versions wrote them. + // Until the configuration encryption upgrade has created the key, values are written the way earlier versions wrote them. public string Encrypt(string raw) { try diff --git a/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs index ab1d365ad..b17fcb714 100644 --- a/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs @@ -23,7 +23,10 @@ public XmlFileKeyValueStore(IOctopusFileSystem fileSystem, public bool ReEncryptIfLegacy(string name) { - if (name == null) throw new ArgumentNullException(nameof(name)); + if (name == null) + { + throw new ArgumentNullException(nameof(name)); + } var stored = Read(name) as string; if (stored == null || string.IsNullOrWhiteSpace(stored) || !Encryptor.RequiresReEncryption(stored)) From d6a31c9509dc7e1cc2f84657d8311a58ee00a40d Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 24 Nov 2026 15:45:29 +1100 Subject: [PATCH 105/124] +semver: major From 68948fe14f747dc39954582d2261a5034086bced Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 25 Nov 2026 09:22:53 +1100 Subject: [PATCH 106/124] Report an unreadable key directory instead of treating the key as missing --- ...inuxConfigurationEncryptionKeyFileTests.cs | 30 ++++++++++++++++ .../Crypto/ConfigurationEncryptionKey.cs | 36 ++++++++++--------- 2 files changed, 50 insertions(+), 16 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs index af98659a4..f8023cce8 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs @@ -77,6 +77,36 @@ public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() Directory.GetFiles(keyDirectory).Should().ContainSingle("no racer's temporary file is left behind"); } + [Test] + public void WhenTheKeyDirectoryCannotBeEnteredThenLoadingSaysHowToFixThePermissions() + { + if (geteuid() == 0) + { + Assert.Ignore("Root can enter any directory."); + } + + // Arrange + var log = Substitute.For(); + var fileSystem = new OctopusPhysicalFileSystem(log); + using var directory = new TemporaryDirectory(fileSystem); + var keyDirectory = Path.Combine(directory.DirectoryPath, "keys"); + var keyFilePath = Path.Combine(keyDirectory, ConfigurationEncryptionKey.KeyFileName); + new ConfigurationEncryptionKey(log, fileSystem, keyFilePath).CreateIfMissing(); + File.SetUnixFileMode(keyDirectory, UnixFileMode.None); + try + { + // Act + Action load = () => new ConfigurationEncryptionKey(log, fileSystem, keyFilePath).TryLoad(); + + // Assert + load.Should().Throw().WithMessage("*exists but the user Tentacle is running as*cannot read it*chown*"); + } + finally + { + File.SetUnixFileMode(keyDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + } + [Test] public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillReadIt() { diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index 54b26d992..ee4fd0684 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -73,12 +73,29 @@ public byte[] Load() return loaded; } - if (KeyFilePath == null || !fileSystem.FileExists(KeyFilePath)) + if (KeyFilePath == null) { return null; } - loaded = LoadFromFile(KeyFilePath); + string contents; + try + { + contents = fileSystem.ReadAllText(KeyFilePath); + } + catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) + { + return null; + } + catch (UnauthorizedAccessException e) + { + var user = Environment.UserName; + var directory = LinuxDirectoryOf(KeyFilePath); + throw new InvalidOperationException($"The configuration encryption key file `{KeyFilePath}` exists but the user Tentacle is running as ({user}) cannot read it. " + + $"It must be owned by and readable only by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {KeyFilePath}`.", e); + } + + loaded = Parse(KeyFilePath, contents); return loaded; } @@ -139,21 +156,8 @@ static byte[] RandomKey() return key; } - byte[] LoadFromFile(string path) + static byte[] Parse(string path, string contents) { - string contents; - try - { - contents = fileSystem.ReadAllText(path); - } - catch (UnauthorizedAccessException e) - { - var user = Environment.UserName; - var directory = LinuxDirectoryOf(path); - throw new InvalidOperationException($"The configuration encryption key file `{path}` exists but the user Tentacle is running as ({user}) cannot read it. " - + $"It must be owned by and readable only by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {path}`.", e); - } - try { var key = Convert.FromBase64String(contents.Trim()); From d6cac4d9485c35226935b555b10cc7ce09ab3926 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 25 Nov 2026 09:52:51 +1100 Subject: [PATCH 107/124] Test an unreadable key by running Tentacle as another user, and clean up test users --- .../ConfigurationEncryptionUpgradeTests.cs | 34 +++++++++++++ .../ConfigurationFilePermissionsTests.cs | 2 +- .../NonRootCreateInstanceTests.cs | 33 +++++-------- .../Support/TentacleInstanceBuilder.cs | 35 ++++++++++++++ .../Util/LinuxTestUserPrincipal.cs | 42 +++++++++------- ...inuxConfigurationEncryptionKeyFileTests.cs | 48 ++----------------- .../Util/LinuxTestUserPrincipal.cs | 47 ++++++++++-------- 7 files changed, 138 insertions(+), 103 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 4b0839872..cf9db86f8 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -6,12 +6,15 @@ using FluentAssertions; using NUnit.Framework; using Octopus.Tentacle.CommonTestUtils; +using Octopus.Tentacle.CommonTestUtils.Diagnostics; using Octopus.Tentacle.Contracts; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Tests.Integration.Common; using Octopus.Tentacle.Tests.Integration.Support; using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; +using Octopus.Tentacle.Tests.Integration.Util; using Octopus.Tentacle.Tests.Integration.Util.Builders; +using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Integration.Configuration { @@ -168,6 +171,37 @@ public async Task WhenTentacleKeyFileIsDeleted_AndTheCurrentTentacleStarts_ThenT output.Should().Contain(instance.ConfigurationEncryptionKeyFile, "the certificate cannot be decrypted without its key"); instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedWithTheKey); } + + [Test] + [RequiresSudoOnLinux] + public async Task WhenTentacleRunsAsAUserWhoCannotReadTheKey_ThenItSaysHowToFixThePermissions() + { + // Arrange + using var otherUser = new LinuxTestUserPrincipal("octo-key-reader"); + // Under /tmp rather than the default location, which is in the runner's home and not traversable by the other user. + using var home = new TemporaryDirectory(new OctopusPhysicalFileSystem(new InMemoryLog()), Directory.CreateTempSubdirectory().FullName); + using var instance = await new TentacleInstanceBuilder() + .WithHomeDirectory(home) + .WithNewCertificate() + .Build(Logger, CancellationToken); + await instance.SudoAllowEveryoneToReadTheHomeDirectory(); + await instance.SudoMakeTheKeyDirectoryOwnedAndOnlyAccessibleByRoot(); + try + { + // Act + var showThumbprint = await instance + .ExecuteTentacleCommandOnTheInstanceAsUser(otherUser, CommandResultValidation.None, "show-thumbprint", CancellationToken); + + // Assert + var output = showThumbprint.StandardOutput + showThumbprint.StandardError; + showThumbprint.ExitCode.Should().NotBe(0, output); + output.Should().Contain(instance.ConfigurationEncryptionKeyFile).And.Contain("cannot read it").And.Contain("sudo chown").And.NotContain("does not exist"); + } + finally + { + await instance.SudoDeleteTheKeyDirectory(); + } + } } } #endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsTests.cs index 7ae0b5e10..18e375d00 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsTests.cs @@ -23,7 +23,7 @@ public class ConfigurationFilePermissionsTests [RequiresSudoOnLinux] public async Task WhenRestrictedToTheServiceUserThenOnlyThatUserOwnsAndCanReadTheConfig() { - var user = new LinuxTestUserPrincipal("octo-config-perm-test"); + using var user = new LinuxTestUserPrincipal("octo-config-perm-test"); var configurationFile = Path.GetTempFileName(); File.SetUnixFileMode(configurationFile, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead); var log = new InMemoryLog(); diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs index 64dc08769..45108918c 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs @@ -28,7 +28,7 @@ public class NonRootCreateInstanceTests : IntegrationTest public async Task WhenANonRootUserCannotCreateTheKeyThenTheCommandInTheErrorFixesIt() { // Arrange - var user = new LinuxTestUserPrincipal("octo-key-test"); + using var user = new LinuxTestUserPrincipal("octo-key-test"); // Under /tmp rather than the default location, which is in the runner's home and not traversable by the test user. using var temporaryDirectory = new TemporaryDirectory(new OctopusPhysicalFileSystem(new InMemoryLog()), Directory.CreateTempSubdirectory().FullName); var root = temporaryDirectory.DirectoryPath; @@ -47,26 +47,19 @@ Task CreateInstanceAsUser() $"{EnvironmentVariables.TentacleMachineConfigurationHomeDirectory}={homeDirectory}", TentacleExeFinder.FindTentacleExe(), "create-instance", "--instance", "Tentacle", "--config", configurationFile); - try - { - // Act - var refused = await CreateInstanceAsUser(); - Logger.Information("StdOut: {StdOut}, StdErr: {StdErr}", refused.StandardOutput, refused.StandardError); - var fix = Regex.Match(refused.StandardOutput + refused.StandardError, "sudo mkdir[^`]*").Value; - Logger.Information("Running Fix: {Fix}", fix); - await Cli.Wrap("/bin/bash").WithArguments(new[] { "-c", fix }).ExecuteBufferedAsync(); - var created = await CreateInstanceAsUser(); + // Act + var refused = await CreateInstanceAsUser(); + Logger.Information("StdOut: {StdOut}, StdErr: {StdErr}", refused.StandardOutput, refused.StandardError); + var fix = Regex.Match(refused.StandardOutput + refused.StandardError, "sudo mkdir[^`]*").Value; + Logger.Information("Running Fix: {Fix}", fix); + await Cli.Wrap("/bin/bash").WithArguments(new[] { "-c", fix }).ExecuteBufferedAsync(); + var created = await CreateInstanceAsUser(); - // Assert - refused.ExitCode.Should().NotBe(0); - fix.Should().NotBeEmpty($"the error should say which command fixes it, but it was: {refused.StandardOutput}{refused.StandardError}"); - created.ExitCode.Should().Be(0, $"running `{fix}` should let the user create the instance, but: {created.StandardOutput}{created.StandardError}"); - File.Exists(configurationFile).Should().BeTrue(); - } - finally - { - await Sudo("userdel", "-r", user.UserName); - } + // Assert + refused.ExitCode.Should().NotBe(0); + fix.Should().NotBeEmpty($"the error should say which command fixes it, but it was: {refused.StandardOutput}{refused.StandardError}"); + created.ExitCode.Should().Be(0, $"running `{fix}` should let the user create the instance, but: {created.StandardOutput}{created.StandardError}"); + File.Exists(configurationFile).Should().BeTrue(); } static Task Sudo(params string[] arguments) diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index d0ced3f41..5fc476943 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -13,6 +13,7 @@ using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Tests.Integration.Support.TentacleFetchers; +using Octopus.Tentacle.Tests.Integration.Util; using Serilog; namespace Octopus.Tentacle.Tests.Integration.Support @@ -207,6 +208,40 @@ public async Task ExecuteTentacleCommandOnTheInstance(Com .Concat(Name is null ? new[] { "--config", ConfigurationFile } : new[] { "--instance", Name }) .ToArray()); + string KeyDirectory => Path.GetDirectoryName(ConfigurationEncryptionKeyFile)!; + + internal async Task SudoAllowEveryoneToReadTheHomeDirectory() + => await Sudo("chmod", "-R", "o+rX", home.DirectoryPath); + + internal async Task SudoMakeTheKeyDirectoryOwnedAndOnlyAccessibleByRoot() + { + await Sudo("chown", "-R", "root:root", KeyDirectory); + await Sudo("chmod", "700", KeyDirectory); + await Sudo("chmod", "600", ConfigurationEncryptionKeyFile); + } + + // The test runner cannot delete a directory owned by root, so it must be deleted before the home directory is. + internal async Task SudoDeleteTheKeyDirectory() + => await Sudo("rm", "-rf", KeyDirectory); + + static async Task Sudo(params string[] arguments) + => await Cli.Wrap("sudo").WithArguments(arguments).ExecuteBufferedAsync(); + + // sudo resets the environment, so the instance's environment is passed through env instead. + internal async Task ExecuteTentacleCommandOnTheInstanceAsUser(LinuxTestUserPrincipal user, CommandResultValidation validation, string command, CancellationToken cancellationToken, params string[] arguments) + { + var sudoArguments = new[] { "-u", user.UserName, "env" } + .Concat(environmentVariables.Select(e => $"{e.Key}={e.Value}")) + .Concat(new[] { tentacleExe, command }) + .Concat(arguments) + .Concat(Name is null ? new[] { "--config", ConfigurationFile } : new[] { "--instance", Name }); + return await Cli.Wrap("sudo") + .WithArguments(sudoArguments) + .WithValidation(validation) + .WithWorkingDirectory(home.DirectoryPath) + .ExecuteBufferedAsync(cancellationToken); + } + // Older Tentacles share the machine's instance registry, so a command can fail while another test registers an instance. public async Task ExecuteTentacleCommand(CommandResultValidation validation, CancellationToken cancellationToken, params string[] arguments) => await RetryHelper.RetryAsync( diff --git a/source/Octopus.Tentacle.Tests.Integration/Util/LinuxTestUserPrincipal.cs b/source/Octopus.Tentacle.Tests.Integration/Util/LinuxTestUserPrincipal.cs index 241457316..04399f712 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Util/LinuxTestUserPrincipal.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Util/LinuxTestUserPrincipal.cs @@ -1,43 +1,51 @@ using System; +using System.IO; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Integration.Util { - class LinuxTestUserPrincipal + // Creates a Linux user for the test and tries to delete it again when disposed. + class LinuxTestUserPrincipal : IDisposable { public LinuxTestUserPrincipal(string username) { UserName = username; Password = Guid.NewGuid().ToString(); - RunCommand($"-c \"sudo userdel {username}\"", failOnNonZeroExitCode: false); - RunCommand($"-c \"sudo useradd -m -c \\\"Linux test User for OctopusShared tests\\\" {username} -s /bin/bash\""); - RunCommand($"-c \"echo {username}:\"{Password}\" | sudo chpasswd\""); + RunCommand(DeleteUserCommand, failOnNonZeroExitCode: false); + RunCommand(IsAlpine + ? $"-c \"{Sudo}adduser -D -s /bin/sh {username}\"" + : $"-c \"{Sudo}useradd -m -c \\\"Linux test User for OctopusShared tests\\\" {username} -s /bin/bash\"", failOnNonZeroExitCode: true); + RunCommand($"-c \"echo {username}:\"{Password}\" | {Sudo}chpasswd\"", failOnNonZeroExitCode: true); } public string Password { get; } - public string UserName { get; } + public string UserName { get; } - static void RunCommand(string arguments, bool failOnNonZeroExitCode = true) + public void Dispose() => RunCommand(DeleteUserCommand, failOnNonZeroExitCode: false); + + // Alpine has BusyBox's adduser and deluser rather than useradd and userdel. + static bool IsAlpine => File.Exists("/etc/alpine-release"); + + static string Sudo => Environment.UserName == "root" ? "" : "sudo "; + + string DeleteUserCommand => IsAlpine ? $"-c \"{Sudo}deluser --remove-home {UserName}\"" : $"-c \"{Sudo}userdel -r {UserName}\""; + + static void RunCommand(string arguments, bool failOnNonZeroExitCode) { - var commandLineInvocation = new CommandLineInvocation("/bin/bash", arguments); - // We're in a synchronous test helper called from the LinuxTestUserPrincipal - // constructor. Constructors must return synchronously, so we block on the - // async call with .GetAwaiter().GetResult(). This is sync-over-async but is - // safe because the NUnit test runner dispatches us on a worker thread without - // a captured SynchronizationContext, so no deadlock. - // See https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html + var commandLineInvocation = new CommandLineInvocation("/bin/sh", arguments); + // Constructors can't be async, and NUnit runs tests without a SynchronizationContext, so blocking can't deadlock. var result = commandLineInvocation.ExecuteCommandAsync().GetAwaiter().GetResult(); - foreach (var line in result.Errors) - Console.WriteLine(line); foreach (var error in result.Errors) + { Console.Error.WriteLine(error); + } + if (result.ExitCode != 0 && failOnNonZeroExitCode) { - Console.Error.WriteLine($"Creating linux test user failed with exit code: {result.ExitCode}"); - throw new ApplicationException("Unable to create linux test user"); + throw new ApplicationException($"Unable to create linux test user, exit code {result.ExitCode}"); } } } diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs index f8023cce8..e2b1a763d 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs @@ -15,6 +15,7 @@ using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Tests.Support; using Octopus.Tentacle.Tests.Support.TestAttributes; +using Octopus.Tentacle.Tests.Util; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Configuration.Crypto @@ -77,36 +78,6 @@ public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() Directory.GetFiles(keyDirectory).Should().ContainSingle("no racer's temporary file is left behind"); } - [Test] - public void WhenTheKeyDirectoryCannotBeEnteredThenLoadingSaysHowToFixThePermissions() - { - if (geteuid() == 0) - { - Assert.Ignore("Root can enter any directory."); - } - - // Arrange - var log = Substitute.For(); - var fileSystem = new OctopusPhysicalFileSystem(log); - using var directory = new TemporaryDirectory(fileSystem); - var keyDirectory = Path.Combine(directory.DirectoryPath, "keys"); - var keyFilePath = Path.Combine(keyDirectory, ConfigurationEncryptionKey.KeyFileName); - new ConfigurationEncryptionKey(log, fileSystem, keyFilePath).CreateIfMissing(); - File.SetUnixFileMode(keyDirectory, UnixFileMode.None); - try - { - // Act - Action load = () => new ConfigurationEncryptionKey(log, fileSystem, keyFilePath).TryLoad(); - - // Assert - load.Should().Throw().WithMessage("*exists but the user Tentacle is running as*cannot read it*chown*"); - } - finally - { - File.SetUnixFileMode(keyDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); - } - } - [Test] public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillReadIt() { @@ -120,8 +91,7 @@ public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillRea var fileSystem = new OctopusPhysicalFileSystem(log); // Not created yet, so CreateIfMissing creates every directory down to the key under the hardened umask. using var directory = new TemporaryDirectory(fileSystem, Path.Combine(Path.GetTempPath(), "octopus-config-encryption-key-" + Guid.NewGuid())); - var user = "octo-key-" + Guid.NewGuid().ToString("N").Substring(0, 8); - CreateUser(user).Should().Be(0); + using var user = new LinuxTestUserPrincipal("octo-key-" + Guid.NewGuid().ToString("N").Substring(0, 8)); var instanceKeyFilePath = Path.Combine(directory.DirectoryPath, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); var keySource = new ConfigurationEncryptionKey(log, fileSystem, instanceKeyFilePath); var previousUmask = umask(Convert.ToUInt32("027", 8)); @@ -129,30 +99,20 @@ public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillRea { // Act keySource.CreateIfMissing(); - var owner = uint.Parse(RunAndRead("id", $"-u {user}")); + var owner = uint.Parse(RunAndRead("id", $"-u {user.UserName}")); UnixFile.SetOwnerIfRunningAsRoot(owner, keySource.KeyDirectory!); UnixFile.SetOwnerIfRunningAsRoot(owner, instanceKeyFilePath); // Assert - Run("su", $"-s /bin/sh -c \"cat {instanceKeyFilePath}\" {user}").Should().Be(0, "the owner must be able to traverse the shared directories to its key"); + Run("su", $"-s /bin/sh -c \"cat {instanceKeyFilePath}\" {user.UserName}").Should().Be(0, "the owner must be able to traverse the shared directories to its key"); File.GetUnixFileMode(keySource.KeyDirectory!).Should().Be(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); } finally { umask(previousUmask); - DeleteUser(user); } } - // Alpine has BusyBox's adduser and deluser rather than useradd and userdel. - static bool IsAlpine => File.Exists("/etc/alpine-release"); - - static int CreateUser(string user) - => IsAlpine ? Run("adduser", $"-D -H {user}") : Run("useradd", $"--no-create-home {user}"); - - static int DeleteUser(string user) - => IsAlpine ? Run("deluser", user) : Run("userdel", user); - static int Run(string fileName, string arguments) { using var process = Process.Start(fileName, arguments); diff --git a/source/Octopus.Tentacle.Tests/Util/LinuxTestUserPrincipal.cs b/source/Octopus.Tentacle.Tests/Util/LinuxTestUserPrincipal.cs index 219fa5b6a..7f89ace95 100644 --- a/source/Octopus.Tentacle.Tests/Util/LinuxTestUserPrincipal.cs +++ b/source/Octopus.Tentacle.Tests/Util/LinuxTestUserPrincipal.cs @@ -1,46 +1,51 @@ using System; +using System.IO; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Util { - class LinuxTestUserPrincipal + // Creates a Linux user for the test and tries to delete it again when disposed. + class LinuxTestUserPrincipal : IDisposable { public LinuxTestUserPrincipal(string username) { UserName = username; Password = Guid.NewGuid().ToString(); - RunCommand($"-c \"sudo userdel {username}\"", failOnNonZeroExitCode: false); - RunCommand($"-c \"sudo useradd -m -c \\\"Linux test User for OctopusShared tests\\\" {username} -s /bin/bash\""); - RunCommand($"-c \"echo {username}:\"{Password}\" | sudo chpasswd\""); + RunCommand(DeleteUserCommand, failOnNonZeroExitCode: false); + RunCommand(IsAlpine + ? $"-c \"{Sudo}adduser -D -s /bin/sh {username}\"" + : $"-c \"{Sudo}useradd -m -c \\\"Linux test User for OctopusShared tests\\\" {username} -s /bin/bash\"", failOnNonZeroExitCode: true); + RunCommand($"-c \"echo {username}:\"{Password}\" | {Sudo}chpasswd\"", failOnNonZeroExitCode: true); } public string Password { get; } - public string UserName { get; } - - // Why this is sync: RunCommand is called from the constructor, which can't - // be async. - // - // Why blocking on the async call is safe: this only runs under NUnit, which - // dispatches us on a worker thread with no SynchronizationContext. - // - // Why low risk: this is test code. The worst case for a wrong call here is - // a hung test, not a production incident. - // See https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html - static void RunCommand(string arguments, bool failOnNonZeroExitCode = true) + public string UserName { get; } + + public void Dispose() => RunCommand(DeleteUserCommand, failOnNonZeroExitCode: false); + + // Alpine has BusyBox's adduser and deluser rather than useradd and userdel. + static bool IsAlpine => File.Exists("/etc/alpine-release"); + + static string Sudo => Environment.UserName == "root" ? "" : "sudo "; + + string DeleteUserCommand => IsAlpine ? $"-c \"{Sudo}deluser --remove-home {UserName}\"" : $"-c \"{Sudo}userdel -r {UserName}\""; + + static void RunCommand(string arguments, bool failOnNonZeroExitCode) { - var commandLineInvocation = new CommandLineInvocation("/bin/bash", arguments); + var commandLineInvocation = new CommandLineInvocation("/bin/sh", arguments); + // Constructors can't be async, and NUnit runs tests without a SynchronizationContext, so blocking can't deadlock. var result = commandLineInvocation.ExecuteCommandAsync().GetAwaiter().GetResult(); - foreach (var line in result.Errors) - Console.WriteLine(line); foreach (var error in result.Errors) + { Console.Error.WriteLine(error); + } + if (result.ExitCode != 0 && failOnNonZeroExitCode) { - Console.Error.WriteLine($"Creating linux test user failed with exit code: {result.ExitCode}"); - throw new ApplicationException("Unable to create linux test user"); + throw new ApplicationException($"Unable to create linux test user, exit code {result.ExitCode}"); } } } From 290283ead4a64341ab39cda042928f6748c577ec Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 25 Nov 2026 15:25:20 +1100 Subject: [PATCH 108/124] Create the configuration encryption key without hard links on filesystems that don't support them --- source/Octopus.Tentacle.Core/Util/UnixFile.cs | 51 ++++++++++++++++++- .../Crypto/ConfigurationEncryptionKey.cs | 24 +++++++-- 2 files changed, 69 insertions(+), 6 deletions(-) diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs index 793193872..6fcf38881 100644 --- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -10,7 +10,9 @@ namespace Octopus.Tentacle.Core.Util public static class UnixFile { const uint UnchangedGroup = uint.MaxValue; + const int NotPermittedError = 1; const int FileExistsError = 17; + const int NotSupportedError = 95; // Unlike rename(2), link(2) never replaces an existing file. public static bool TryLinkWithoutReplacing(string existingPath, string newPath) @@ -20,11 +22,56 @@ public static bool TryLinkWithoutReplacing(string existingPath, string newPath) return true; } - return Marshal.GetLastPInvokeError() == FileExistsError - ? false + var error = Marshal.GetLastPInvokeError(); + if (error == FileExistsError) + { + return false; + } + + return error == NotPermittedError || error == NotSupportedError + ? TryCopyWithoutReplacing(existingPath, newPath) : throw new IOException($"Unable to create `{newPath}`: {Marshal.GetLastPInvokeErrorMessage()}"); } + // For file systems without hard links, such as SMB shares. Another process may briefly see the new file empty. + static bool TryCopyWithoutReplacing(string existingPath, string newPath) + { + var options = new FileStreamOptions + { + Mode = FileMode.CreateNew, + Access = FileAccess.Write, + Share = FileShare.None, + UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite + }; + + FileStream destination; + try + { + destination = new FileStream(newPath, options); + } + catch (IOException) when (File.Exists(newPath)) + { + return false; + } + + try + { + using (destination) + { + using var source = File.OpenRead(existingPath); + source.CopyTo(destination); + destination.Flush(flushToDisk: true); + } + + return true; + } + catch + { + File.Delete(newPath); + throw; + } + } + public static uint OwnerOf(string path) { return SystemNative_Stat(path, out var status) == 0 diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index ee4fd0684..ef035b5c2 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -4,6 +4,7 @@ using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; +using System.Threading; using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Util; @@ -19,6 +20,8 @@ public class ConfigurationEncryptionKey public const string DefaultInstancesDataDirectory = "/var/lib/octopus/tentacle"; const int KeySizeInBytes = 32; + const int EmptyKeyReadAttempts = 20; + const int EmptyKeyReadDelayMilliseconds = 50; #if NET const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; @@ -62,7 +65,7 @@ public static string KeyFilePathFor(string instanceName) } public byte[] Load() - => TryLoad() ?? throw new InvalidOperationException(KeyFilePath == null + => TryLoad() ?? throw new ConfigurationEncryptionKeyException(KeyFilePath == null ? "The configuration encryption key for this configuration is not available. Register the configuration with `create-instance --instance `." : $"The configuration encryption key file `{KeyFilePath}` does not exist, so the values it protected cannot be decrypted. Restore it from a backup. " + RecoveryWithoutBackup); @@ -81,7 +84,7 @@ public byte[] Load() string contents; try { - contents = fileSystem.ReadAllText(KeyFilePath); + contents = ReadAllTextWaitingForContent(KeyFilePath); } catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) { @@ -91,7 +94,7 @@ public byte[] Load() { var user = Environment.UserName; var directory = LinuxDirectoryOf(KeyFilePath); - throw new InvalidOperationException($"The configuration encryption key file `{KeyFilePath}` exists but the user Tentacle is running as ({user}) cannot read it. " + throw new ConfigurationEncryptionKeyException($"The configuration encryption key file `{KeyFilePath}` exists but the user Tentacle is running as ({user}) cannot read it. " + $"It must be owned by and readable only by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {KeyFilePath}`.", e); } @@ -124,6 +127,19 @@ public void CreateIfMissing() log.Info($"Generated a new configuration encryption key at `{path}`. Back it up with the configuration file it protects: the configuration cannot be decrypted without it."); } + // Without hard links the key file is created in place, so a racing process can see it before it is written. + string ReadAllTextWaitingForContent(string path) + { + var contents = fileSystem.ReadAllText(path); + for (var attempt = 0; attempt < EmptyKeyReadAttempts && string.IsNullOrWhiteSpace(contents); attempt++) + { + Thread.Sleep(EmptyKeyReadDelayMilliseconds); + contents = fileSystem.ReadAllText(path); + } + + return contents; + } + // Ancestors are shared by every instance's service user, so they must stay traversable whatever the umask. void CreateKeyDirectory(string keyDirectory) { @@ -170,7 +186,7 @@ static byte[] Parse(string path, string contents) { } - throw new InvalidOperationException($"The configuration encryption key file `{path}` is corrupt: it must hold a base64-encoded {KeySizeInBytes * 8}-bit key. " + throw new ConfigurationEncryptionKeyException($"The configuration encryption key file `{path}` is corrupt: it must hold a base64-encoded {KeySizeInBytes * 8}-bit key. " + "Restore it from a backup; values encrypted with a lost key cannot be recovered. " + RecoveryWithoutBackup); } From 16d2564b532bce6b9fc63b989f661f020789e76f Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 25 Nov 2026 15:25:20 +1100 Subject: [PATCH 109/124] Report configuration encryption key failures as themselves rather than as an x509stores problem --- .../ConfigurationEncryptionKeyException.cs | 17 +++++++++++++++++ .../Crypto/LinuxMachineKeyEncryptor.cs | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKeyException.cs diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKeyException.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKeyException.cs new file mode 100644 index 000000000..bbf932de8 --- /dev/null +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKeyException.cs @@ -0,0 +1,17 @@ +using System; + +namespace Octopus.Tentacle.Configuration.Crypto +{ + public class ConfigurationEncryptionKeyException : Exception + { + public ConfigurationEncryptionKeyException(string message) + : base(message) + { + } + + public ConfigurationEncryptionKeyException(string message, Exception inner) + : base(message, inner) + { + } + } +} diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs index d1cdbb80f..12596da2c 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs @@ -43,9 +43,9 @@ public bool RequiresReEncryption(string encrypted) // Until the configuration encryption upgrade has created the key, values are written the way earlier versions wrote them. public string Encrypt(string raw) { + var currentKey = configurationKey.TryLoad(); try { - var currentKey = configurationKey.TryLoad(); return currentKey == null ? EncryptLegacy(raw) : EncryptCurrent(currentKey, raw); } catch (Exception e) From 816a763e24b4e0ee8979a3974e7e2e5296a2db8e Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 25 Nov 2026 15:32:51 +1100 Subject: [PATCH 110/124] Add reset-configuration-encryption to recover from a lost key, and stop replace-certificate creating keys --- ...eplaceCertificateEncryptionUpgradeTests.cs | 48 ----------- .../LinuxResetConfigurationEncryptionTests.cs | 65 ++++++++++++++ .../ReplaceCertificateCommandTests.cs | 1 - .../Commands/ReplaceCertificateCommand.cs | 5 -- .../ResetConfigurationEncryptionCommand.cs | 86 +++++++++++++++++++ .../Crypto/ConfigurationEncryptionKey.cs | 5 +- .../Configuration/XmlFileKeyValueStore.cs | 3 + source/Octopus.Tentacle/Program.cs | 1 + 8 files changed, 157 insertions(+), 57 deletions(-) delete mode 100644 source/Octopus.Tentacle.Tests.Integration/Commands/LinuxReplaceCertificateEncryptionUpgradeTests.cs create mode 100644 source/Octopus.Tentacle.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs create mode 100644 source/Octopus.Tentacle/Commands/ResetConfigurationEncryptionCommand.cs diff --git a/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxReplaceCertificateEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxReplaceCertificateEncryptionUpgradeTests.cs deleted file mode 100644 index de3cc0ab5..000000000 --- a/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxReplaceCertificateEncryptionUpgradeTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#if NET -using System.IO; -using System.Runtime.Versioning; -using System.Threading.Tasks; -using CliWrap; -using FluentAssertions; -using NUnit.Framework; -using Octopus.Tentacle.Configuration.Crypto; -using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; -using Octopus.Tentacle.Tests.Integration.Support; -using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; - -namespace Octopus.Tentacle.Tests.Integration.Commands -{ - [LinuxTest] - [UnsupportedOSPlatform("windows")] - public class LinuxReplaceCertificateEncryptionUpgradeTests : IntegrationTest - { - const string MachineName = "replace-certificate-test"; - - [Test] - public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndReplaceCertificateIsCalled_ThenTheNewCertificateIsEncryptedWithItsOwnKey() - { - // Arrange - await using var octopus = await new FakeOctopusServerBuilder().Build(); - using var instance = await new TentacleInstanceBuilder() - .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) - .WithNewCertificate() - .Build(Logger, CancellationToken); - var server = $"--server=http://localhost:{octopus.Port}"; - await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "register-with", CancellationToken, - server, "--apiKey=API-KEY", $"--space={FakeOctopusServerBuilder.SpaceName}", $"--environment={FakeOctopusServerBuilder.EnvironmentName}", - "--role=test", $"--name={MachineName}", "--comms-style=TentaclePassive"); - - // Act - var upgradedInstance = instance.WithCurrentTentacleExe(); - await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "replace-certificate", CancellationToken, server, "--apiKey=API-KEY"); - - // Assert - var newThumbprint = await upgradedInstance.ShowThumbprint(CancellationToken); - newThumbprint.Should().NotBe(instance.Thumbprint); - upgradedInstance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(LinuxMachineKeyEncryptor.Specifier + "$"); - File.Exists(instance.ConfigurationEncryptionKeyFile).Should().BeTrue(); - octopus.LatestRegistration(FakeOctopusServerBuilder.SpaceName, MachineName)!.Thumbprint.Should().Be(newThumbprint); - } - } -} -#endif diff --git a/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs b/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs new file mode 100644 index 000000000..33d2c2136 --- /dev/null +++ b/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs @@ -0,0 +1,65 @@ +#if NET +using System.IO; +using System.Linq; +using System.Runtime.Versioning; +using System.Threading.Tasks; +using System.Xml.Linq; +using CliWrap; +using FluentAssertions; +using NUnit.Framework; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Tests.Integration.Support; +using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; + +namespace Octopus.Tentacle.Tests.Integration.Commands +{ + [LinuxTest] + [UnsupportedOSPlatform("windows")] + public class LinuxResetConfigurationEncryptionTests : IntegrationTest + { + [Test] + public async Task WhenTheKeyIsLost_AndResetConfigurationEncryptionIsCalled_ThenProtectedSettingsAreRemovedAndANewKeyIsCreated() + { + // Arrange + using var instance = await new TentacleInstanceBuilder() + .WithNewCertificate() + .Build(Logger, CancellationToken); + await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "polling-proxy", CancellationToken, + "--proxyEnable=true", "--proxyHost=proxy.example", "--proxyPort=8080", "--proxyUsername=user", "--proxyPassword=secret"); + File.Delete(instance.ConfigurationEncryptionKeyFile); + + // Act + var reset = await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "reset-configuration-encryption", CancellationToken); + + // Assert + File.Exists(instance.ConfigurationEncryptionKeyFile).Should().BeTrue(); + var settings = XDocument.Load(instance.ConfigurationFile).Root!.Elements("set") + .ToDictionary(e => (string)e.Attribute("key")!, e => e.Value); + settings.Should().NotContainKey(TentacleConfiguration.CertificateSettingName); + settings.Should().NotContainKey(PollingProxyConfiguration.ProxyPasswordSettingName); + settings[TentacleConfiguration.CertificateThumbprintSettingName].Should().Be(instance.Thumbprint); + reset.StandardOutput.Should().Contain(instance.Thumbprint); + } + + [Test] + public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndResetConfigurationEncryptionIsCalled_ThenItRefusesAndTheCertificateIsUnchanged() + { + // Arrange + using var instance = await new TentacleInstanceBuilder() + .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) + .WithNewCertificate() + .Build(Logger, CancellationToken); + var certificateEncryptedByVersion14 = instance.CertificateAsStoredInTheConfigurationFile(); + + // Act + var reset = await instance.WithCurrentTentacleExe().ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "reset-configuration-encryption", CancellationToken); + + // Assert + var output = reset.StandardOutput + reset.StandardError; + reset.ExitCode.Should().NotBe(0, output); + output.Should().Contain("upgrade-configuration-encryption"); + instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedByVersion14); + } + } +} +#endif diff --git a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs index 175e5ccf7..105ad47b1 100644 --- a/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs +++ b/source/Octopus.Tentacle.Tests/Commands/ReplaceCertificateCommandTests.cs @@ -99,7 +99,6 @@ static void ReplaceCertificate(TemporaryTentacleConfiguration tentacle, FakeOcto => new ReplaceCertificateCommand( new Lazy(() => tentacle.Configuration), new Lazy(() => new CertificateGenerator(new NullLog())), - new Lazy(() => Substitute.For()), octopus.ClientInitializer, Substitute.For(), Substitute.For(), diff --git a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs index 29e1bf92f..768938a07 100644 --- a/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs +++ b/source/Octopus.Tentacle/Commands/ReplaceCertificateCommand.cs @@ -20,7 +20,6 @@ public class ReplaceCertificateCommand : AbstractStandardCommand { readonly Lazy configuration; readonly Lazy certificateGenerator; - readonly Lazy configurationEncryptionUpgrade; readonly IOctopusClientInitializer octopusClientInitializer; readonly IProxyConfigParser proxyConfig; readonly ISystemLog log; @@ -30,7 +29,6 @@ public class ReplaceCertificateCommand : AbstractStandardCommand public ReplaceCertificateCommand( Lazy configuration, Lazy certificateGenerator, - Lazy configurationEncryptionUpgrade, IOctopusClientInitializer octopusClientInitializer, IProxyConfigParser proxyConfig, ISystemLog log, @@ -40,7 +38,6 @@ public ReplaceCertificateCommand( { this.configuration = configuration; this.certificateGenerator = certificateGenerator; - this.configurationEncryptionUpgrade = configurationEncryptionUpgrade; this.octopusClientInitializer = octopusClientInitializer; this.proxyConfig = proxyConfig; this.log = log; @@ -74,8 +71,6 @@ async Task StartAsync() if (!keepCurrentCertificate) { - // Creates a fresh configuration encryption key if it was lost, so the new certificate can be saved. - configurationEncryptionUpgrade.Value.PrepareKey(); 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}"); diff --git a/source/Octopus.Tentacle/Commands/ResetConfigurationEncryptionCommand.cs b/source/Octopus.Tentacle/Commands/ResetConfigurationEncryptionCommand.cs new file mode 100644 index 000000000..f241e2220 --- /dev/null +++ b/source/Octopus.Tentacle/Commands/ResetConfigurationEncryptionCommand.cs @@ -0,0 +1,86 @@ +using System; +using System.Linq; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Configuration.Crypto; +using Octopus.Tentacle.Configuration.Instances; +using Octopus.Tentacle.Core.Diagnostics; +using Octopus.Tentacle.Startup; +using Octopus.Tentacle.Util; + +namespace Octopus.Tentacle.Commands +{ + public class ResetConfigurationEncryptionCommand : AbstractStandardCommand + { + readonly Lazy configurationEncryptionUpgrade; + readonly IApplicationInstanceSelector instanceSelector; + readonly IOctopusFileSystem fileSystem; + readonly ISystemLog log; + + public ResetConfigurationEncryptionCommand( + Lazy configurationEncryptionUpgrade, + IApplicationInstanceSelector instanceSelector, + IOctopusFileSystem fileSystem, + ISystemLog log, + ILogFileOnlyLogger logFileOnlyLogger) + : base(instanceSelector, log, logFileOnlyLogger) + { + this.configurationEncryptionUpgrade = configurationEncryptionUpgrade; + this.instanceSelector = instanceSelector; + this.fileSystem = fileSystem; + this.log = log; + } + + protected override void Start() + { + base.Start(); + + var instance = instanceSelector.Current; + if (PlatformDetection.IsRunningOnWindows || !(instance.WritableConfiguration is XmlFileKeyValueStore store)) + { + log.Info("Configuration encryption keys only apply to Linux Tentacles with a configuration file; nothing to do."); + return; + } + + if (instance.KeyFilePath == null) + { + throw new ControlledFailureException($"The configuration `{instance.ConfigurationPath}` is not in the instance registry, so it has no encryption key of its own. " + + $"Register it with `create-instance --instance --config {instance.ConfigurationPath}`, then run this command again."); + } + + // Only a key that is genuinely missing may be replaced. + try + { + if (new ConfigurationEncryptionKey(log, fileSystem, instance.KeyFilePath).TryLoad() != null) + { + throw new ControlledFailureException($"The configuration encryption key `{instance.KeyFilePath}` exists, so there is nothing to reset."); + } + } + catch (ConfigurationEncryptionKeyException e) + { + throw new ControlledFailureException($"{e.Message} If it is corrupt and there is no backup, move it aside and run this command again."); + } + + var lost = ConfigurationEncryptionUpgrade.ProtectedSettingNames.Where(store.IsEncryptedWithCurrentKey).ToArray(); + if (lost.Length == 0) + { + throw new ControlledFailureException("No setting is encrypted with the configuration encryption key, so it is not needed yet. Run `upgrade-configuration-encryption` instead."); + } + + var oldThumbprint = store.Get(TentacleConfiguration.CertificateThumbprintSettingName); + foreach (var name in lost) + { + store.Remove(name); + } + + store.Save(); + log.Info($"Removed {string.Join(", ", lost)}, which cannot be decrypted without the lost key."); + + configurationEncryptionUpgrade.Value.PrepareKey(); + + log.Info($"The old certificate thumbprint was {oldThumbprint}. " + + "If you use a proxy password, re-enter it with `proxy` or `polling-proxy`. " + + "Then run `replace-certificate` to give this Tentacle a new certificate and update Octopus Server to trust it. " + + $"If the Tentacle has already generated a new certificate, run `replace-certificate --apply-current-cert-to-tentacles-with-thumbprint {oldThumbprint}` instead."); + } + } +} diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index ef035b5c2..d74e8b4a3 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -28,9 +28,8 @@ public class ConfigurationEncryptionKey const UnixFileMode TraversableByAll = OwnerOnly | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute; #endif - internal const string RecoveryWithoutBackup = "If there is no backup, the Tentacle's certificate is lost and it needs a new one: " - + "run `replace-certificate` with an API key. " - + "This creates a new key and certificate, and updates every deployment target and worker registered with the old certificate to trust it."; + internal const string RecoveryWithoutBackup = "If there is no backup, run `reset-configuration-encryption` to create a new key, " + + "then `replace-certificate` with an API key to give the Tentacle a new certificate."; static string InstancesDataDirectory => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleInstancesDataDirectory) is { Length: > 0 } directory ? directory : DefaultInstancesDataDirectory; diff --git a/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs index b17fcb714..537ae3a08 100644 --- a/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs @@ -21,6 +21,9 @@ public XmlFileKeyValueStore(IOctopusFileSystem fileSystem, this.configurationFile = fileSystem.GetFullPath(configurationFile); } + public bool IsEncryptedWithCurrentKey(string name) + => Read(name) is string stored && !string.IsNullOrWhiteSpace(stored) && !Encryptor.RequiresReEncryption(stored); + public bool ReEncryptIfLegacy(string name) { if (name == null) diff --git a/source/Octopus.Tentacle/Program.cs b/source/Octopus.Tentacle/Program.cs index 0362e177c..00e65eead 100644 --- a/source/Octopus.Tentacle/Program.cs +++ b/source/Octopus.Tentacle/Program.cs @@ -95,6 +95,7 @@ public override IContainer BuildContainer(StartUpInstanceRequest startUpInstance builder.RegisterCommand("livez", "Checks that the Tentacle agent process is alive (suitable for a Kubernetes liveness probe)."); builder.RegisterCommand("show-configuration", "Outputs the Tentacle configuration"); builder.RegisterCommand("upgrade-configuration-encryption", "Creates this instance's configuration encryption key, gives it to the configuration's owner, and re-encrypts protected settings with it"); + builder.RegisterCommand("reset-configuration-encryption", "Recovers from a lost configuration encryption key: removes the settings it protected and creates a new key"); return builder.Build(); } From 3217c5ae8cf6075c20d5d090f54e71e008103630 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Wed, 25 Nov 2026 16:00:36 +1100 Subject: [PATCH 111/124] Move the configuration encryption key into place with File.Move instead of linking it ourselves --- .../Util/FileSystem/IOctopusFileSystem.cs | 2 +- .../Util/OctopusPhysicalFileSystem.cs | 14 ++-- source/Octopus.Tentacle.Core/Util/UnixFile.cs | 64 ------------------- .../Support/SharedTentacleCryptoState.cs | 2 +- .../Crypto/ConfigurationEncryptionKey.cs | 21 +----- .../RetryingKubernetesPhysicalFileSystem.cs | 4 +- 6 files changed, 15 insertions(+), 92 deletions(-) diff --git a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs index f004248bb..c27ef1e2c 100644 --- a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs @@ -48,7 +48,7 @@ public interface IOctopusFileSystem #if NET [UnsupportedOSPlatform("windows")] #endif - bool AtomicCreateFileWithOnlyUserReadWritePermissions(string filePath, byte[] contents); + bool TryAtomicCreateFileWithOnlyUserReadWritePermissions(string filePath, byte[] contents); string ReadAllText(string scriptFile); string[] ReadAllLines(string scriptFile); diff --git a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs index c2f45cfab..ab6ed1547 100644 --- a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs @@ -254,7 +254,7 @@ public void WriteAllText(string path, string contents) #if NET [UnsupportedOSPlatform("windows")] - public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents) + public bool TryAtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents) { if (OperatingSystem.IsWindows()) { @@ -265,8 +265,12 @@ public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] try { CreateFileWithUserReadWriteAccessOnly(temporaryPath, contents); - // Unlike File.Move, link(2) is atomic about not replacing: two racing processes cannot each keep their own file. - return UnixFile.TryLinkWithoutReplacing(temporaryPath, path); + File.Move(temporaryPath, path); + return true; + } + catch (IOException) when (File.Exists(path)) + { + return false; } finally { @@ -298,11 +302,11 @@ static void DeleteIfExists(string path) } } - // In the same directory, so it is on the same file system and can be linked into place atomically. + // In the same directory, so it is on the same file system and is renamed rather than copied. static string TemporaryPathBeside(string path) => path + "." + Guid.NewGuid().ToString("N") + ".tmp"; #else - public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents) + public bool TryAtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents) => throw new PlatformNotSupportedException(UserOnlyFilesAreUnixOnly); #endif diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs index 6fcf38881..d60fe9de6 100644 --- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -10,67 +10,6 @@ namespace Octopus.Tentacle.Core.Util public static class UnixFile { const uint UnchangedGroup = uint.MaxValue; - const int NotPermittedError = 1; - const int FileExistsError = 17; - const int NotSupportedError = 95; - - // Unlike rename(2), link(2) never replaces an existing file. - public static bool TryLinkWithoutReplacing(string existingPath, string newPath) - { - if (link(existingPath, newPath) == 0) - { - return true; - } - - var error = Marshal.GetLastPInvokeError(); - if (error == FileExistsError) - { - return false; - } - - return error == NotPermittedError || error == NotSupportedError - ? TryCopyWithoutReplacing(existingPath, newPath) - : throw new IOException($"Unable to create `{newPath}`: {Marshal.GetLastPInvokeErrorMessage()}"); - } - - // For file systems without hard links, such as SMB shares. Another process may briefly see the new file empty. - static bool TryCopyWithoutReplacing(string existingPath, string newPath) - { - var options = new FileStreamOptions - { - Mode = FileMode.CreateNew, - Access = FileAccess.Write, - Share = FileShare.None, - UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite - }; - - FileStream destination; - try - { - destination = new FileStream(newPath, options); - } - catch (IOException) when (File.Exists(newPath)) - { - return false; - } - - try - { - using (destination) - { - using var source = File.OpenRead(existingPath); - source.CopyTo(destination); - destination.Flush(flushToDisk: true); - } - - return true; - } - catch - { - File.Delete(newPath); - throw; - } - } public static uint OwnerOf(string path) { @@ -100,9 +39,6 @@ public static void GiveTo(SafeFileHandle file, uint owner) } } - [DllImport("libc", SetLastError = true)] - static extern int link(string oldpath, string newpath); - [DllImport("libc")] static extern uint geteuid(); diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs index b6a622e7d..32520266b 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs @@ -95,7 +95,7 @@ static void CreateLegacyMachineKeyIfMissing(OctopusPhysicalFileSystem fileSystem aes.GenerateKey(); var contents = Convert.ToBase64String(aes.Key) + "." + Convert.ToBase64String(aes.IV); fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(path)!); - fileSystem.AtomicCreateFileWithOnlyUserReadWritePermissions(path, Encoding.ASCII.GetBytes(contents)); + fileSystem.TryAtomicCreateFileWithOnlyUserReadWritePermissions(path, Encoding.ASCII.GetBytes(contents)); } // A Tentacle only reuses the stored certificate when it comes back with its private key. diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index d74e8b4a3..28d1b6d2b 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -4,7 +4,6 @@ using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; -using System.Threading; using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Util; @@ -20,8 +19,6 @@ public class ConfigurationEncryptionKey public const string DefaultInstancesDataDirectory = "/var/lib/octopus/tentacle"; const int KeySizeInBytes = 32; - const int EmptyKeyReadAttempts = 20; - const int EmptyKeyReadDelayMilliseconds = 50; #if NET const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; @@ -83,7 +80,7 @@ public byte[] Load() string contents; try { - contents = ReadAllTextWaitingForContent(KeyFilePath); + contents = fileSystem.ReadAllText(KeyFilePath); } catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) { @@ -116,8 +113,7 @@ public void CreateIfMissing() CreateKeyDirectory(KeyDirectory!); - // Several instances starting at once after an upgrade must all end up with the same key. - if (!fileSystem.AtomicCreateFileWithOnlyUserReadWritePermissions(path, Encoding.ASCII.GetBytes(raw))) + if (!fileSystem.TryAtomicCreateFileWithOnlyUserReadWritePermissions(path, Encoding.ASCII.GetBytes(raw))) { log.Verbose($"Another process created the configuration encryption key `{path}` first; using its key."); return; @@ -126,19 +122,6 @@ public void CreateIfMissing() log.Info($"Generated a new configuration encryption key at `{path}`. Back it up with the configuration file it protects: the configuration cannot be decrypted without it."); } - // Without hard links the key file is created in place, so a racing process can see it before it is written. - string ReadAllTextWaitingForContent(string path) - { - var contents = fileSystem.ReadAllText(path); - for (var attempt = 0; attempt < EmptyKeyReadAttempts && string.IsNullOrWhiteSpace(contents); attempt++) - { - Thread.Sleep(EmptyKeyReadDelayMilliseconds); - contents = fileSystem.ReadAllText(path); - } - - return contents; - } - // Ancestors are shared by every instance's service user, so they must stay traversable whatever the umask. void CreateKeyDirectory(string keyDirectory) { diff --git a/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs b/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs index 6cdc1f477..1a4ed75fd 100644 --- a/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle/Kubernetes/RetryingKubernetesPhysicalFileSystem.cs @@ -143,9 +143,9 @@ public void WriteAllText(string filePath, string contents) #if NET [UnsupportedOSPlatform("windows")] #endif - public bool AtomicCreateFileWithOnlyUserReadWritePermissions(string filePath, byte[] contents) + public bool TryAtomicCreateFileWithOnlyUserReadWritePermissions(string filePath, byte[] contents) { - return syncRetryPolicy.Execute(() => inner.AtomicCreateFileWithOnlyUserReadWritePermissions(filePath, contents)); + return syncRetryPolicy.Execute(() => inner.TryAtomicCreateFileWithOnlyUserReadWritePermissions(filePath, contents)); } public string ReadAllText(string scriptFile) From 4c1332ded2715d9fb9843241e9b4d2d90c514a70 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 09:02:56 +1100 Subject: [PATCH 112/124] Test recovering a Tentacle from a lost key end to end, through to running a script --- .../LinuxResetConfigurationEncryptionTests.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs b/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs index 33d2c2136..02eb0e999 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs @@ -7,6 +7,12 @@ using CliWrap; using FluentAssertions; using NUnit.Framework; +using Octopus.Tentacle.CommonTestUtils; +using Octopus.Tentacle.Contracts; +using Octopus.Tentacle.Tests.Integration.Common; +using Octopus.Tentacle.Tests.Integration.Common.FakeOctopus; +using Octopus.Tentacle.Tests.Integration.Util; +using Octopus.Tentacle.Tests.Integration.Util.Builders; using Octopus.Tentacle.Configuration; using Octopus.Tentacle.Tests.Integration.Support; using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; @@ -41,6 +47,38 @@ await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroE reset.StandardOutput.Should().Contain(instance.Thumbprint); } + [Test] + public async Task WhenTheKeyIsLost_AndTheTentacleIsResetAndGivenANewCertificate_ThenOctopusCanRunScriptsOnItAgain() + { + // Arrange + await using var server = await new FakeOctopusServerBuilder().Build(); + var octopusUrl = $"http://localhost:{server.Port}"; + await using var runningTentacle = await new TentacleInstanceBuilder() + .RunAsListeningTentacle(TestCertificates.ServerPublicThumbprint) + .Build(Logger, CancellationToken); + var instance = runningTentacle.Instance; + await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "register-with", CancellationToken, + $"--server={octopusUrl}", "--apiKey=API-NOTAREALKEY", $"--space={FakeOctopusServerBuilder.SpaceName}", + $"--environment={FakeOctopusServerBuilder.EnvironmentName}", "--role=web", "--name=recovered"); + await runningTentacle.Stop(CancellationToken); + File.Delete(instance.ConfigurationEncryptionKeyFile); + + // Act + await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "reset-configuration-encryption", CancellationToken); + await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "replace-certificate", CancellationToken, + $"--server={octopusUrl}", "--apiKey=API-NOTAREALKEY"); + await runningTentacle.Start(CancellationToken); + + // Assert + var newThumbprint = await instance.ShowThumbprint(CancellationToken); + newThumbprint.Should().NotBe(runningTentacle.Thumbprint); + server.LatestRegistration(FakeOctopusServerBuilder.SpaceName, "recovered")!.Thumbprint.Should().Be(newThumbprint); + var tentacleClient = TestServerHalibut.BuildTentacleClient(runningTentacle.ServiceUri, newThumbprint, server.Halibut, _ => { }); + var (scriptResult, _) = await tentacleClient.ExecuteScript(new TestExecuteShellScriptCommandBuilder().SetScriptBody(b => b.Print("Hello")).Build(), CancellationToken); + scriptResult.State.Should().Be(ProcessState.Complete); + scriptResult.ExitCode.Should().Be(0); + } + [Test] public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndResetConfigurationEncryptionIsCalled_ThenItRefusesAndTheCertificateIsUnchanged() { From 956310a2fcdb16193d85ac38e7df87296f53571f Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 09:12:21 +1100 Subject: [PATCH 113/124] . --- .../Configuration/ConfigurationEncryptionUpgradeTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index cf9db86f8..231e8e25e 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -153,7 +153,7 @@ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheNewKeyCannotB } [Test] - public async Task WhenTentacleKeyFileIsDeleted_AndTheCurrentTentacleStarts_ThenTheCertificateIsLeftUntouched() + public async Task WhenTentacleKeyFileIsDeleted_AndTheCurrentTentacleStarts_ThenTheUserIsToldTheKeyIsMissing() { // Arrange using var instance = await new TentacleInstanceBuilder() From 79c6dc1203c0b449ec6985ef1cba905c2d008dc7 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 09:33:34 +1100 Subject: [PATCH 114/124] . --- .../Configuration/NonRootCreateInstanceTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs index 45108918c..97f75951e 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs @@ -25,7 +25,7 @@ public class NonRootCreateInstanceTests : IntegrationTest { [Test] [RequiresSudoOnLinux] - public async Task WhenANonRootUserCannotCreateTheKeyThenTheCommandInTheErrorFixesIt() + public async Task WhenANonRootUserCreatesAnIntance_AndCannotCreateTheKey_ThenRunningTheCommandInTheErrorFixesTheIssue() { // Arrange using var user = new LinuxTestUserPrincipal("octo-key-test"); From b683c34be8e04b8b171483c1e09200ce2570e674 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 11:35:01 +1100 Subject: [PATCH 115/124] Delete the unused LegacySchemeEncryptor test helper --- .../Crypto/LegacySchemeEncryption.cs | 38 ------------------- 1 file changed, 38 deletions(-) delete mode 100644 source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacySchemeEncryption.cs diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacySchemeEncryption.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacySchemeEncryption.cs deleted file mode 100644 index af82a4898..000000000 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacySchemeEncryption.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Security.Cryptography; -using System.Text; -using Octopus.Tentacle.Configuration.Crypto; - -namespace Octopus.Tentacle.Tests.Configuration.Crypto -{ - public class LegacySchemeEncryptor : IMachineKeyEncryptor - { - readonly ICryptoKeyNixSource keySource; - - public LegacySchemeEncryptor(ICryptoKeyNixSource keySource) - { - this.keySource = keySource; - } - - public string Encrypt(string raw) - { - var plaintext = Encoding.UTF8.GetBytes(raw); - var (key, iv) = keySource.Load(); - using var aes = Aes.Create(); - using var encryptor = aes.CreateEncryptor(key, iv); - return Convert.ToBase64String(encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length)); - } - - public string Decrypt(string encrypted) - { - var (key, iv) = keySource.Load(); - using var aes = Aes.Create(); - using var decryptor = aes.CreateDecryptor(key, iv); - var payload = Convert.FromBase64String(encrypted); - return Encoding.UTF8.GetString(decryptor.TransformFinalBlock(payload, 0, payload.Length)); - } - - public bool RequiresReEncryption(string encrypted) - => false; - } -} From e8207904142750024ea40c8fc0fd2c8b7f45a76c Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 11:36:27 +1100 Subject: [PATCH 116/124] Delete the concurrent key creation test; each instance has its own key --- ...inuxConfigurationEncryptionKeyFileTests.cs | 33 ------------------- 1 file changed, 33 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs index e2b1a763d..e89a26673 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs @@ -2,11 +2,8 @@ using System; using System.Diagnostics; using System.IO; -using System.Linq; using System.Runtime.InteropServices; using System.Runtime.Versioning; -using System.Threading; -using System.Threading.Tasks; using FluentAssertions; using NSubstitute; using NUnit.Framework; @@ -48,36 +45,6 @@ public void WhenTheKeyIsCreatedThenOnlyItsOwnerCanReadIt() Directory.GetFiles(keyDirectory).Should().ContainSingle("the temporary file the key is written to first is not left behind"); } - [Test] - public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey() - { - // Arrange - var log = Substitute.For(); - using var directory = new TemporaryDirectory(new OctopusPhysicalFileSystem(log)); - var keyDirectory = Path.Combine(directory.DirectoryPath, "keys"); - var keyFilePath = Path.Combine(keyDirectory, ConfigurationEncryptionKey.KeyFileName); - const int racers = 32; - using var start = new ManualResetEventSlim(false); - var loads = Enumerable.Range(0, racers) - .Select(_ => Task.Run(() => - { - start.Wait(); - var keySource = new ConfigurationEncryptionKey(log, new OctopusPhysicalFileSystem(log), keyFilePath); - keySource.CreateIfMissing(); - return keySource.Load(); - })) - .ToArray(); - - // Act - start.Set(); - var keys = await Task.WhenAll(loads); - - // Assert - var onDisk = Convert.FromBase64String(File.ReadAllText(keyFilePath)); - keys.Should().AllSatisfy(k => k.Should().Equal(onDisk)); - Directory.GetFiles(keyDirectory).Should().ContainSingle("no racer's temporary file is left behind"); - } - [Test] public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillReadIt() { From 0ea30615f1cf23aa4866292290022a3e1de0bc45 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 11:45:02 +1100 Subject: [PATCH 117/124] Test a hardened umask by running the real Tentacle as root, rather than changing the test process's umask --- .../ConfigurationEncryptionUpgradeTests.cs | 33 ++++++++++ .../Support/TentacleInstanceBuilder.cs | 20 +++++++ ...inuxConfigurationEncryptionKeyFileTests.cs | 60 ------------------- 3 files changed, 53 insertions(+), 60 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 231e8e25e..20704a29b 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -172,6 +172,39 @@ public async Task WhenTentacleKeyFileIsDeleted_AndTheCurrentTentacleStarts_ThenT instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedWithTheKey); } + [Test] + [RequiresSudoOnLinux] + public async Task WhenRootUpgradesUnderAHardenedUmask_ThenTheServiceUserCanStillReadItsKey() + { + // Arrange + using var serviceUser = new LinuxTestUserPrincipal("octo-umask-svc"); + // Under /tmp rather than the default location, which is in the runner's home and not traversable by the service user. + using var home = new TemporaryDirectory(new OctopusPhysicalFileSystem(new InMemoryLog()), Directory.CreateTempSubdirectory().FullName); + using var instance = await new TentacleInstanceBuilder() + .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption) + .WithHomeDirectory(home) + .WithNewCertificate() + .Build(Logger, CancellationToken); + await instance.SudoAllowEveryoneToReadTheHomeDirectory(); + await instance.SudoGiveTheConfigurationFileTo(serviceUser); + var upgradedInstance = instance.WithCurrentTentacleExe(); + try + { + // Act + await upgradedInstance.ExecuteTentacleCommandOnTheInstanceAsRootWithUmask("027", CommandResultValidation.ZeroExitCode, "upgrade-configuration-encryption", CancellationToken); + + // Assert + var showThumbprint = await upgradedInstance + .ExecuteTentacleCommandOnTheInstanceAsUser(serviceUser, CommandResultValidation.None, "show-thumbprint", CancellationToken); + showThumbprint.ExitCode.Should().Be(0, showThumbprint.StandardOutput + showThumbprint.StandardError); + showThumbprint.StandardOutput.Should().Contain(instance.Thumbprint); + } + finally + { + await instance.SudoDeleteTheDataDirectory(); + } + } + [Test] [RequiresSudoOnLinux] public async Task WhenTentacleRunsAsAUserWhoCannotReadTheKey_ThenItSaysHowToFixThePermissions() diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index 5fc476943..c4612751a 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -224,6 +224,13 @@ internal async Task SudoMakeTheKeyDirectoryOwnedAndOnlyAccessibleByRoot() internal async Task SudoDeleteTheKeyDirectory() => await Sudo("rm", "-rf", KeyDirectory); + internal async Task SudoGiveTheConfigurationFileTo(LinuxTestUserPrincipal user) + => await Sudo("chown", user.UserName, ConfigurationFile); + + // Root owns everything a root Tentacle creates in the data directory, so it must be deleted before the home directory is. + internal async Task SudoDeleteTheDataDirectory() + => await Sudo("rm", "-rf", DataDirectory); + static async Task Sudo(params string[] arguments) => await Cli.Wrap("sudo").WithArguments(arguments).ExecuteBufferedAsync(); @@ -242,6 +249,19 @@ internal async Task ExecuteTentacleCommandOnTheInstanceAs .ExecuteBufferedAsync(cancellationToken); } + internal async Task ExecuteTentacleCommandOnTheInstanceAsRootWithUmask(string umask, CommandResultValidation validation, string command, CancellationToken cancellationToken) + { + var sudoArguments = new[] { "sh", "-c", $"umask {umask} && exec \"$@\"", "sh", "env" } + .Concat(environmentVariables.Select(e => $"{e.Key}={e.Value}")) + .Concat(new[] { tentacleExe, command }) + .Concat(Name is null ? new[] { "--config", ConfigurationFile } : new[] { "--instance", Name }); + return await Cli.Wrap("sudo") + .WithArguments(sudoArguments) + .WithValidation(validation) + .WithWorkingDirectory(home.DirectoryPath) + .ExecuteBufferedAsync(cancellationToken); + } + // Older Tentacles share the machine's instance registry, so a command can fail while another test registers an instance. public async Task ExecuteTentacleCommand(CommandResultValidation validation, CancellationToken cancellationToken, params string[] arguments) => await RetryHelper.RetryAsync( diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs index e89a26673..898367704 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs @@ -1,18 +1,14 @@ #if !NETFRAMEWORK using System; -using System.Diagnostics; using System.IO; -using System.Runtime.InteropServices; using System.Runtime.Versioning; using FluentAssertions; using NSubstitute; using NUnit.Framework; using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Core.Util; using Octopus.Tentacle.Tests.Support; using Octopus.Tentacle.Tests.Support.TestAttributes; -using Octopus.Tentacle.Tests.Util; using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Configuration.Crypto @@ -44,62 +40,6 @@ public void WhenTheKeyIsCreatedThenOnlyItsOwnerCanReadIt() File.ReadAllText(keyFilePath).Should().Be(Convert.ToBase64String(key)); Directory.GetFiles(keyDirectory).Should().ContainSingle("the temporary file the key is written to first is not left behind"); } - - [Test] - public void WhenRootCreatesTheKeyUnderAHardenedUmaskThenANonRootOwnerCanStillReadIt() - { - if (geteuid() != 0) - { - Assert.Ignore("Creating a key for another user needs root."); - } - - // Arrange - var log = Substitute.For(); - var fileSystem = new OctopusPhysicalFileSystem(log); - // Not created yet, so CreateIfMissing creates every directory down to the key under the hardened umask. - using var directory = new TemporaryDirectory(fileSystem, Path.Combine(Path.GetTempPath(), "octopus-config-encryption-key-" + Guid.NewGuid())); - using var user = new LinuxTestUserPrincipal("octo-key-" + Guid.NewGuid().ToString("N").Substring(0, 8)); - var instanceKeyFilePath = Path.Combine(directory.DirectoryPath, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName); - var keySource = new ConfigurationEncryptionKey(log, fileSystem, instanceKeyFilePath); - var previousUmask = umask(Convert.ToUInt32("027", 8)); - try - { - // Act - keySource.CreateIfMissing(); - var owner = uint.Parse(RunAndRead("id", $"-u {user.UserName}")); - UnixFile.SetOwnerIfRunningAsRoot(owner, keySource.KeyDirectory!); - UnixFile.SetOwnerIfRunningAsRoot(owner, instanceKeyFilePath); - - // Assert - Run("su", $"-s /bin/sh -c \"cat {instanceKeyFilePath}\" {user.UserName}").Should().Be(0, "the owner must be able to traverse the shared directories to its key"); - File.GetUnixFileMode(keySource.KeyDirectory!).Should().Be(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); - } - finally - { - umask(previousUmask); - } - } - - static int Run(string fileName, string arguments) - { - using var process = Process.Start(fileName, arguments); - process.WaitForExit(); - return process.ExitCode; - } - - static string RunAndRead(string fileName, string arguments) - { - using var process = Process.Start(new ProcessStartInfo(fileName, arguments) { RedirectStandardOutput = true })!; - var output = process.StandardOutput.ReadToEnd().Trim(); - process.WaitForExit(); - return output; - } - - [DllImport("libc")] - static extern uint geteuid(); - - [DllImport("libc")] - static extern uint umask(uint mask); } } #endif From 458d33311a8c0cc0b803d79384202ec37f09423e Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 14:04:04 +1100 Subject: [PATCH 118/124] Add known-answer test for AESGCM-V1 format --- .../Crypto/LinuxMachineKeyEncryptorTests.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorTests.cs index 45a8ebc95..e9a778812 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorTests.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorTests.cs @@ -7,6 +7,7 @@ using Octopus.Tentacle.Configuration.Crypto; using Octopus.Tentacle.Core.Diagnostics; using Octopus.Tentacle.Tests.Support; +using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Configuration.Crypto { @@ -27,6 +28,25 @@ public void WhenAValueIsEncryptedThenItIsVersionedAndDecrypts() encryptor.Decrypt(encrypted).Should().Be("FooBar"); } + [Test] + public void WhenAValueWasWrittenInTheV1FormatThenItStillDecrypts() + { + // Arrange + const string keyFilePath = "/etc/octopus/config-encryption.key"; + const string storedValue = "AESGCM-V1$AAECAwQFBgcICQoL$I7lSH4DKt1wvmL7GctHp4w==$N8FyaLaSAa3/Jbd7LnnhTfS/81zQCC8dWwKWpTtJc8tscsGQ3OA="; + var fileSystem = Substitute.For(); + fileSystem.FileExists(keyFilePath).Returns(true); + fileSystem.ReadAllText(keyFilePath).Returns("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="); + var key = new ConfigurationEncryptionKey(Substitute.For(), fileSystem, keyFilePath); + var encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), key, Array.Empty()); + + // Act + var decrypted = encryptor.Decrypt(storedValue); + + // Assert + decrypted.Should().Be("pässwörd 🐙 with spaces & symbols!"); + } + [Test] public void WhenACurrentValueWasEncryptedWithAnotherKeyThenALegacyKeyIsNotTried() { From 8cfd0a935ddc84d8d6a6d91af072cea3cca56caa Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 14:50:58 +1100 Subject: [PATCH 119/124] Make the suggested key directory fix work under a hardened umask --- .../Configuration/NonRootCreateInstanceTests.cs | 8 +++++--- .../Configuration/Crypto/ConfigurationEncryptionKey.cs | 2 +- .../Configuration/Instances/ApplicationInstanceManager.cs | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs index 97f75951e..f751e6d64 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs @@ -25,7 +25,7 @@ public class NonRootCreateInstanceTests : IntegrationTest { [Test] [RequiresSudoOnLinux] - public async Task WhenANonRootUserCreatesAnIntance_AndCannotCreateTheKey_ThenRunningTheCommandInTheErrorFixesTheIssue() + public async Task WhenANonRootUserCreatesAnIntance_AndCannotCreateTheKey_ThenRunningTheCommandInTheErrorUnderAHardenedUmaskFixesTheIssue() { // Arrange using var user = new LinuxTestUserPrincipal("octo-key-test"); @@ -50,9 +50,11 @@ Task CreateInstanceAsUser() // Act var refused = await CreateInstanceAsUser(); Logger.Information("StdOut: {StdOut}, StdErr: {StdErr}", refused.StandardOutput, refused.StandardError); - var fix = Regex.Match(refused.StandardOutput + refused.StandardError, "sudo mkdir[^`]*").Value; + var fix = Regex.Match(refused.StandardOutput + refused.StandardError, "`(sudo [^`]*)`").Groups[1].Value; Logger.Information("Running Fix: {Fix}", fix); - await Cli.Wrap("/bin/bash").WithArguments(new[] { "-c", fix }).ExecuteBufferedAsync(); + // sudo normally applies its own umask, so wrap it to behave like a hardened host where root's umask is 027. + const string sudoWithHardenedUmask = "sudo() { command sudo sh -c 'umask 027 && exec \"$@\"' sh \"$@\"; }"; + await Cli.Wrap("/bin/bash").WithArguments(new[] { "-c", $"{sudoWithHardenedUmask}; {fix}" }).ExecuteBufferedAsync(); var created = await CreateInstanceAsUser(); // Assert diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index 28d1b6d2b..583902f5e 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -91,7 +91,7 @@ public byte[] Load() var user = Environment.UserName; var directory = LinuxDirectoryOf(KeyFilePath); throw new ConfigurationEncryptionKeyException($"The configuration encryption key file `{KeyFilePath}` exists but the user Tentacle is running as ({user}) cannot read it. " - + $"It must be owned by and readable only by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {KeyFilePath}`.", e); + + $"It must be owned by and readable only by that user, and every parent directory must be traversable by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {KeyFilePath}`.", e); } loaded = Parse(KeyFilePath, contents); diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs index ecb3c8276..0bfb0c4e9 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs @@ -71,7 +71,7 @@ void EnsureConfigurationEncryptionKeyExists(string instanceName) var user = Environment.UserName; var directory = key.KeyDirectory; throw new ControlledFailureException($"Unable to create the configuration encryption key `{keyFilePath}` for the instance `{instanceName}`, so the instance was not created: {e.Message} " - + $"Run this command as root, or give the user ({user}) access to the directory, for example: `sudo mkdir -p {directory} && sudo chown -R {user} {directory} && sudo chmod 700 {directory}`.", e); + + $"Run this command as root, or give the user ({user}) access to the directory, for example: `sudo sh -c 'umask 022 && mkdir -p {directory} && chown {user} {directory} && chmod 700 {directory}'`.", e); } } From abae66c817193a12eae444b38617cece4ef82441 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 15:51:44 +1100 Subject: [PATCH 120/124] Revert "Make the suggested key directory fix work under a hardened umask" This reverts commit 8cfd0a935ddc84d8d6a6d91af072cea3cca56caa. --- .../Configuration/NonRootCreateInstanceTests.cs | 8 +++----- .../Configuration/Crypto/ConfigurationEncryptionKey.cs | 2 +- .../Configuration/Instances/ApplicationInstanceManager.cs | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs index f751e6d64..97f75951e 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs @@ -25,7 +25,7 @@ public class NonRootCreateInstanceTests : IntegrationTest { [Test] [RequiresSudoOnLinux] - public async Task WhenANonRootUserCreatesAnIntance_AndCannotCreateTheKey_ThenRunningTheCommandInTheErrorUnderAHardenedUmaskFixesTheIssue() + public async Task WhenANonRootUserCreatesAnIntance_AndCannotCreateTheKey_ThenRunningTheCommandInTheErrorFixesTheIssue() { // Arrange using var user = new LinuxTestUserPrincipal("octo-key-test"); @@ -50,11 +50,9 @@ Task CreateInstanceAsUser() // Act var refused = await CreateInstanceAsUser(); Logger.Information("StdOut: {StdOut}, StdErr: {StdErr}", refused.StandardOutput, refused.StandardError); - var fix = Regex.Match(refused.StandardOutput + refused.StandardError, "`(sudo [^`]*)`").Groups[1].Value; + var fix = Regex.Match(refused.StandardOutput + refused.StandardError, "sudo mkdir[^`]*").Value; Logger.Information("Running Fix: {Fix}", fix); - // sudo normally applies its own umask, so wrap it to behave like a hardened host where root's umask is 027. - const string sudoWithHardenedUmask = "sudo() { command sudo sh -c 'umask 027 && exec \"$@\"' sh \"$@\"; }"; - await Cli.Wrap("/bin/bash").WithArguments(new[] { "-c", $"{sudoWithHardenedUmask}; {fix}" }).ExecuteBufferedAsync(); + await Cli.Wrap("/bin/bash").WithArguments(new[] { "-c", fix }).ExecuteBufferedAsync(); var created = await CreateInstanceAsUser(); // Assert diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs index 583902f5e..28d1b6d2b 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs @@ -91,7 +91,7 @@ public byte[] Load() var user = Environment.UserName; var directory = LinuxDirectoryOf(KeyFilePath); throw new ConfigurationEncryptionKeyException($"The configuration encryption key file `{KeyFilePath}` exists but the user Tentacle is running as ({user}) cannot read it. " - + $"It must be owned by and readable only by that user, and every parent directory must be traversable by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {KeyFilePath}`.", e); + + $"It must be owned by and readable only by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {KeyFilePath}`.", e); } loaded = Parse(KeyFilePath, contents); diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs index 0bfb0c4e9..ecb3c8276 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs @@ -71,7 +71,7 @@ void EnsureConfigurationEncryptionKeyExists(string instanceName) var user = Environment.UserName; var directory = key.KeyDirectory; throw new ControlledFailureException($"Unable to create the configuration encryption key `{keyFilePath}` for the instance `{instanceName}`, so the instance was not created: {e.Message} " - + $"Run this command as root, or give the user ({user}) access to the directory, for example: `sudo sh -c 'umask 022 && mkdir -p {directory} && chown {user} {directory} && chmod 700 {directory}'`.", e); + + $"Run this command as root, or give the user ({user}) access to the directory, for example: `sudo mkdir -p {directory} && sudo chown -R {user} {directory} && sudo chmod 700 {directory}`.", e); } } From 0ab33cc919e344dce98715b5e9ede120428e8b96 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 16:06:32 +1100 Subject: [PATCH 121/124] Test that installing the service for another user leaves the key readable by that user --- .../ConfigurationEncryptionUpgradeTests.cs | 33 +++++++++++++++++++ .../Support/TentacleInstanceBuilder.cs | 3 +- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 20704a29b..353b45e84 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -205,6 +205,39 @@ public async Task WhenRootUpgradesUnderAHardenedUmask_ThenTheServiceUserCanStill } } + [Test] + [RequiresSudoOnLinux] + [NonParallelizable] + public async Task WhenRootInstallsTheServiceForAnotherUser_ThenThatUserCanReadItsKey() + { + // Arrange + using var serviceUser = new LinuxTestUserPrincipal("octo-install-svc"); + // Under /tmp rather than the default location, which is in the runner's home and not traversable by the service user. + using var home = new TemporaryDirectory(new OctopusPhysicalFileSystem(new InMemoryLog()), Directory.CreateTempSubdirectory().FullName); + // Opened before building, so the key is still created readable only by its owner. + File.SetUnixFileMode(home.DirectoryPath, File.GetUnixFileMode(home.DirectoryPath) | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + using var instance = await new TentacleInstanceBuilder() + .WithHomeDirectory(home) + .WithNewCertificate() + .Build(Logger, CancellationToken); + try + { + // Act + await instance.ExecuteTentacleCommandOnTheInstanceAsRootWithUmask("022", CommandResultValidation.ZeroExitCode, "service", CancellationToken, "--install", "--username", serviceUser.UserName); + + // Assert + var showThumbprint = await instance + .ExecuteTentacleCommandOnTheInstanceAsUser(serviceUser, CommandResultValidation.None, "show-thumbprint", CancellationToken); + showThumbprint.ExitCode.Should().Be(0, showThumbprint.StandardOutput + showThumbprint.StandardError); + showThumbprint.StandardOutput.Should().Contain(instance.Thumbprint); + } + finally + { + await instance.ExecuteTentacleCommandOnTheInstanceAsRootWithUmask("022", CommandResultValidation.None, "service", CancellationToken, "--uninstall"); + await instance.SudoDeleteTheDataDirectory(); + } + } + [Test] [RequiresSudoOnLinux] public async Task WhenTentacleRunsAsAUserWhoCannotReadTheKey_ThenItSaysHowToFixThePermissions() diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index c4612751a..f6732b31b 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -249,11 +249,12 @@ internal async Task ExecuteTentacleCommandOnTheInstanceAs .ExecuteBufferedAsync(cancellationToken); } - internal async Task ExecuteTentacleCommandOnTheInstanceAsRootWithUmask(string umask, CommandResultValidation validation, string command, CancellationToken cancellationToken) + internal async Task ExecuteTentacleCommandOnTheInstanceAsRootWithUmask(string umask, CommandResultValidation validation, string command, CancellationToken cancellationToken, params string[] arguments) { var sudoArguments = new[] { "sh", "-c", $"umask {umask} && exec \"$@\"", "sh", "env" } .Concat(environmentVariables.Select(e => $"{e.Key}={e.Value}")) .Concat(new[] { tentacleExe, command }) + .Concat(arguments) .Concat(Name is null ? new[] { "--config", ConfigurationFile } : new[] { "--instance", Name }); return await Cli.Wrap("sudo") .WithArguments(sudoArguments) From 76f4d13ca11c936f7ba9f52b1d2585b4565798fe Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 16:08:25 +1100 Subject: [PATCH 122/124] Run the service install test as plain root rather than with a umask --- .../ConfigurationEncryptionUpgradeTests.cs | 4 ++-- .../Support/TentacleInstanceBuilder.cs | 10 ++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs index 353b45e84..e8a8b6076 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs @@ -223,7 +223,7 @@ public async Task WhenRootInstallsTheServiceForAnotherUser_ThenThatUserCanReadIt try { // Act - await instance.ExecuteTentacleCommandOnTheInstanceAsRootWithUmask("022", CommandResultValidation.ZeroExitCode, "service", CancellationToken, "--install", "--username", serviceUser.UserName); + await instance.ExecuteTentacleCommandOnTheInstanceAsRoot(CommandResultValidation.ZeroExitCode, "service", CancellationToken, "--install", "--username", serviceUser.UserName); // Assert var showThumbprint = await instance @@ -233,7 +233,7 @@ public async Task WhenRootInstallsTheServiceForAnotherUser_ThenThatUserCanReadIt } finally { - await instance.ExecuteTentacleCommandOnTheInstanceAsRootWithUmask("022", CommandResultValidation.None, "service", CancellationToken, "--uninstall"); + await instance.ExecuteTentacleCommandOnTheInstanceAsRoot(CommandResultValidation.None, "service", CancellationToken, "--uninstall"); await instance.SudoDeleteTheDataDirectory(); } } diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs index f6732b31b..5ff2b2769 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs @@ -249,9 +249,15 @@ internal async Task ExecuteTentacleCommandOnTheInstanceAs .ExecuteBufferedAsync(cancellationToken); } - internal async Task ExecuteTentacleCommandOnTheInstanceAsRootWithUmask(string umask, CommandResultValidation validation, string command, CancellationToken cancellationToken, params string[] arguments) + internal async Task ExecuteTentacleCommandOnTheInstanceAsRoot(CommandResultValidation validation, string command, CancellationToken cancellationToken, params string[] arguments) + => await ExecuteAsRoot(new[] { "env" }, validation, command, cancellationToken, arguments); + + internal async Task ExecuteTentacleCommandOnTheInstanceAsRootWithUmask(string umask, CommandResultValidation validation, string command, CancellationToken cancellationToken) + => await ExecuteAsRoot(new[] { "sh", "-c", $"umask {umask} && exec \"$@\"", "sh", "env" }, validation, command, cancellationToken); + + async Task ExecuteAsRoot(string[] launcher, CommandResultValidation validation, string command, CancellationToken cancellationToken, params string[] arguments) { - var sudoArguments = new[] { "sh", "-c", $"umask {umask} && exec \"$@\"", "sh", "env" } + var sudoArguments = launcher .Concat(environmentVariables.Select(e => $"{e.Key}={e.Value}")) .Concat(new[] { tentacleExe, command }) .Concat(arguments) From 7c31c0e19661746ab4f7f39df61374c7aa904c3b Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 16:13:07 +1100 Subject: [PATCH 123/124] Run Linux integration tests with systemd in the local Docker helper --- testing/README.md | 8 +-- .../local/run-linux-unit-tests-in-docker.sh | 51 ++++++++++++++----- 2 files changed, 42 insertions(+), 17 deletions(-) diff --git a/testing/README.md b/testing/README.md index 9fc4bdd85..3ff29c2eb 100644 --- a/testing/README.md +++ b/testing/README.md @@ -42,11 +42,11 @@ The script runs in four stages, each of which can be skipped: The `e2e` stage needs an Octopus Server licence, because an unlicensed server enforces a limit of 0 targets and no Tentacle can register. Set `OCTOPUS_SERVER_BASE64_LICENSE`, or let the script read a development licence from 1Password when run interactively. Without one, the stage still verifies configuration and server connectivity up to the licence refusal. Pass `--no-1password` anywhere `op` must not run. -## Local only: Linux tests as root on macOS or Windows +## Local only: Linux tests on macOS or Windows **Local only. CI does not use this script.** -Tests marked `[LinuxTest]` are skipped on macOS and Windows. [`local/run-linux-unit-tests-in-docker.sh`](./local/run-linux-unit-tests-in-docker.sh) runs them as root in a .NET SDK container for the host's architecture. +Tests marked `[LinuxTest]` are skipped on macOS and Windows. [`local/run-linux-unit-tests-in-docker.sh`](./local/run-linux-unit-tests-in-docker.sh) runs them in a .NET SDK container for the host's architecture, with systemd running so tests that install a service work. Run the configuration tests (the default): @@ -57,10 +57,10 @@ Run the configuration tests (the default): Run tests matching a filter: ``` -./testing/local/run-linux-unit-tests-in-docker.sh "FullyQualifiedName~ConfigurationFilePermissionsFixture" +./testing/local/run-linux-unit-tests-in-docker.sh "FullyQualifiedName~LinuxConfigurationFilePermissionsTests" ``` -The filter is anything `dotnet test --filter` accepts. It only runs `Octopus.Tentacle.Tests` on net10.0, needs Docker running, and copies the repo into the container so your working tree isn't touched. +The filter is anything `dotnet test --filter` accepts, and is applied to both `Octopus.Tentacle.Tests` and `Octopus.Tentacle.Tests.Integration` on net10.0. Unit tests run as root; integration tests run as a non-root user with passwordless sudo, as `[RequiresSudoOnLinux]` tests expect. It needs Docker running, starts the container privileged so systemd can boot, and copies the repo into the container so your working tree isn't touched. ## Linux Packages diff --git a/testing/local/run-linux-unit-tests-in-docker.sh b/testing/local/run-linux-unit-tests-in-docker.sh index 741ba2d15..39d7eb228 100755 --- a/testing/local/run-linux-unit-tests-in-docker.sh +++ b/testing/local/run-linux-unit-tests-in-docker.sh @@ -1,27 +1,52 @@ #!/usr/bin/env bash # -# LOCAL ONLY, not used by CI. Runs Linux-only unit tests as root in a .NET SDK container for this host's architecture. +# LOCAL ONLY, not used by CI. Runs Linux-only tests in a .NET SDK container for this host's architecture, with systemd running. # # Usage: ./testing/local/run-linux-unit-tests-in-docker.sh [dotnet test filter] # +# Unit tests run as root. Integration tests run as a non-root user with passwordless sudo, as [RequiresSudoOnLinux] tests expect. +# set -euo pipefail REPO_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) -FILTER=${1:-FullyQualifiedName~Octopus.Tentacle.Tests.Configuration} +FILTER=${1:-FullyQualifiedName~.Configuration.} case "$(uname -m)" in arm64|aarch64) PLATFORM=linux/arm64 ;; *) PLATFORM=linux/amd64 ;; esac +IMAGE=tentacle-local-linux-tests +CONTAINER=tentacle-local-linux-tests-run + +docker build --quiet --platform "$PLATFORM" -t "$IMAGE" - >/dev/null <<'EOF' +FROM mcr.microsoft.com/dotnet/sdk:10.0 +RUN apt-get update && apt-get install -y --no-install-recommends systemd systemd-sysv sudo && rm -rf /var/lib/apt/lists/* +RUN useradd -m -s /bin/bash builder && echo 'builder ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/builder && chmod 440 /etc/sudoers.d/builder +RUN mkdir /work && chown builder /work +STOPSIGNAL SIGRTMIN+3 +CMD ["/lib/systemd/systemd"] +EOF -docker run --rm --platform "$PLATFORM" \ +# systemd must be the container's first process, so the tests run through docker exec. +docker rm -f "$CONTAINER" >/dev/null 2>&1 || true +docker run -d --name "$CONTAINER" --platform "$PLATFORM" \ + --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw --tmpfs /run --tmpfs /run/lock \ -v "$REPO_DIR:/src:ro" \ - -e FILTER="$FILTER" \ - -e NUGET_PACKAGES=/work/.nuget-packages \ - mcr.microsoft.com/dotnet/sdk:10.0 \ - bash -euc ' - mkdir /work - tar -C /src --exclude=./.git --exclude="*/bin" --exclude="*/obj" --exclude=./_artifacts -cf - . | tar -C /work -xf - - cd /work - project=source/Octopus.Tentacle.Tests/Octopus.Tentacle.Tests.csproj - dotnet test "$project" -f net10.0 --filter "$FILTER" - ' + "$IMAGE" >/dev/null +trap 'docker rm -f "$CONTAINER" >/dev/null' EXIT + +for _ in $(seq 1 30); do + state=$(docker exec "$CONTAINER" systemctl is-system-running 2>/dev/null || true) + [[ "$state" == running || "$state" == degraded ]] && break + sleep 1 +done + +docker exec "$CONTAINER" bash -euc 'tar -C /src --exclude=./.git --exclude="*/bin" --exclude="*/obj" --exclude=./_artifacts -cf - . | tar -C /work -xf -' + +run_tests() { + # Both runs share /work, so the build outputs must belong to whichever user runs next. + docker exec "$CONTAINER" chown -R "$1" /work + docker exec -u "$1" -e FILTER="$FILTER" -e NUGET_PACKAGES=/work/.nuget-packages -w /work "$CONTAINER" \ + dotnet test "$2" -f net10.0 --filter "$FILTER" +} +run_tests root source/Octopus.Tentacle.Tests/Octopus.Tentacle.Tests.csproj +run_tests builder source/Octopus.Tentacle.Tests.Integration/Octopus.Tentacle.Tests.Integration.csproj From 00cf7c05e80408515811937f6c144913bd2df77e Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Thu, 26 Nov 2026 16:14:11 +1100 Subject: [PATCH 124/124] . --- .../Configuration/ConfigurationEncryptionUpgrade.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs b/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs index 1b88ae5ad..88ed501c3 100644 --- a/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs +++ b/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs @@ -32,8 +32,6 @@ public class ConfigurationEncryptionUpgrade : IConfigurationEncryptionUpgrade PollingProxyConfiguration.ProxyPasswordSettingName }; - const string StillOnLegacyKeys = "so the configuration is still protected by the key earlier versions used. Tentacle will keep working and try again the next time it starts."; - readonly IApplicationInstanceSelector instanceSelector; readonly IOctopusFileSystem fileSystem; readonly ISystemLog log; @@ -62,7 +60,7 @@ void WarnOnFailure(Action action, string failure) } catch (Exception e) { - log.Warn(e, $"{failure}, {StillOnLegacyKeys}"); + log.Warn(e, $"{failure}, so the configuration is still protected by the key earlier versions used. Tentacle will keep working and try again the next time it starts."); } }