From f918c731c741f47cc13a656e5e72d74459518dd8 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 11:11:12 +1100 Subject: [PATCH 01/12] Split the per-instance configuration encryption key from the legacy machine key source --- .../Support/SharedTentacleCryptoState.cs | 20 ++- .../ApplicationInstanceSelectorFixture.cs | 2 +- .../LegacyCiphertextCompatibilityFixture.cs | 2 +- .../LinuxConfigurationFileSecurityFixture.cs | 14 +- .../Crypto/LinuxGeneratedMachineKeyFixture.cs | 4 +- .../Crypto/LinuxMachineKeyEncryptorFixture.cs | 6 +- .../TentacleConfigurationUpgradeFixture.cs | 20 +-- ...XmlFileKeyValueStoreReEncryptionFixture.cs | 2 +- .../Support/TestMachineKeyEncryptor.cs | 14 +- .../Crypto/ConfigurationEncryptionKey.cs | 145 ++++++++++++++++++ .../Crypto/ICryptoKeyNixSource.cs | 2 - .../Crypto/LinuxGeneratedMachineKey.cs | 118 ++------------ .../Configuration/Crypto/LinuxMachineIdKey.cs | 5 - .../Crypto/LinuxMachineKeyEncryptor.cs | 24 +-- .../Crypto/MachineKeyEncryptor.cs | 24 +-- .../Instances/ApplicationInstanceSelector.cs | 2 +- .../TentacleConfigurationUpgrade.cs | 8 +- 17 files changed, 225 insertions(+), 187 deletions(-) create mode 100644 source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs 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/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..6a86b8bab 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs @@ -52,7 +52,7 @@ 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"); @@ -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(); @@ -89,7 +89,7 @@ public void WhenOnlyTheKeyIsPreparedThenItIsCreatedAndValuesStayLegacy() public void WhenTheKeyCannotBeCreatedThenTentacleKeepsWorkingOnTheLegacyKey() { // 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(); @@ -110,7 +110,7 @@ public void WhenTheKeyCannotBeCreatedThenTentacleKeepsWorkingOnTheLegacyKey() 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(); @@ -128,7 +128,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 +145,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 +161,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 +178,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/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..2f483b871 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(); } @@ -97,8 +96,7 @@ string EncryptLegacy(string raw) { try { - var existing = keySource.TryLoad(); - return existing == null ? null : CheckSize(existing.Value.Key); + return configurationKey.TryLoad(); } catch (Exception e) { @@ -122,7 +120,7 @@ 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(configurationKey.Load(), payload, AssociatedData); return StrictUtf8.GetString(plaintext); } catch (InvalidOperationException e) when (e.InnerException is UnauthorizedAccessException) @@ -138,18 +136,6 @@ string DecryptCurrent(string encrypted) } } - byte[] LoadCurrentKey() - => CheckSize(keySource.Load().Key); - - static byte[] CheckSize(byte[] key) - { - if (key.Length != KeySizeInBytes) - { - throw new CryptographicException($"The machine key must be {KeySizeInBytes * 8} bits, but is {key.Length * 8}."); - } - return key; - } - string DecryptLegacy(string encrypted) { var errors = new List(); 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/Instances/ApplicationInstanceSelector.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs index 8ceeb90c0..3b29744f5 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) diff --git a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs index 05cf2ebfd..4acbc1d59 100644 --- a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs +++ b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs @@ -96,7 +96,7 @@ public void RunOrThrow() } #if NET - (LinuxGeneratedMachineKey Key, XmlFileKeyValueStore Store)? TryPrepareKey() + (ConfigurationEncryptionKey Key, XmlFileKeyValueStore Store)? TryPrepareKey() { if (OperatingSystem.IsWindows()) { @@ -117,12 +117,12 @@ 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); + UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyDirectory!); + UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyFilePath!); return (key, store); } From cc9bed10618fb46617024b19c403b7ed15a9129d Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 11:20:02 +1100 Subject: [PATCH 02/12] Do not fall back to legacy encryption when the configuration encryption key is unreadable --- .../Crypto/LinuxMachineKeyEncryptor.cs | 29 +++++++------------ .../FlatDictionaryKeyValueStore.cs | 2 +- 2 files changed, 12 insertions(+), 19 deletions(-) diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs index 2f483b871..c9a083b73 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs @@ -44,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) @@ -92,26 +92,23 @@ 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); } - byte[]? TryLoadCurrentKey() + public string Decrypt(string encrypted) + => IsLegacyCiphertext(encrypted) + ? DecryptLegacy(encrypted) + : DecryptCurrent(encrypted); + + string DecryptCurrent(string encrypted) { + byte[] key; try { - return configurationKey.TryLoad(); + 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)); @@ -120,13 +117,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(configurationKey.Load(), 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. diff --git a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs index b1e8ff781..84c12f32e 100644 --- a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs +++ b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs @@ -134,7 +134,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."); } From 1bef5d14fd0b68629dc499718840121a9d8085f0 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 11:28:59 +1100 Subject: [PATCH 03/12] Remove duplicated legacy key and decryption error handling --- .../Crypto/LinuxMachineKeyEncryptor.cs | 48 ++++++++++--------- .../FlatDictionaryKeyValueStore.cs | 47 +++++++++--------- 2 files changed, 50 insertions(+), 45 deletions(-) diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs index c9a083b73..74777b9cd 100644 --- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs +++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs @@ -70,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) { @@ -89,7 +98,7 @@ 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); } public string Decrypt(string encrypted) @@ -131,23 +140,18 @@ string DecryptCurrent(string encrypted) string DecryptLegacy(string encrypted) { - var errors = new List(); - foreach (var source in legacyKeySources) + var (decrypted, errors) = TryEachLegacyKey(legacy => { - 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); - } + 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); + }); + + if (decrypted != null) + { + 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/FlatDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs index 84c12f32e..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)); From dcbb9c8036d0f65c0d57418168c27847fca37979 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 11:39:21 +1100 Subject: [PATCH 04/12] Require callers to supply the encryptor when creating an XmlFileKeyValueStore --- .../TentacleConfiguration/InstanceConfigurationLoader.cs | 5 +++-- .../Configuration/Instances/ApplicationInstanceSelector.cs | 2 +- .../Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs | 5 ++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs b/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs index 29c1b0e8e..ba56bf78c 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,7 +53,7 @@ public InstanceConfigurationLoader( public InstanceConfiguration LoadConfiguration(ApplicationInstanceRecord applicationInstanceRecord) { - var keyStore = new XmlFileKeyValueStore(fileSystem, applicationInstanceRecord.ConfigurationFilePath); + var keyStore = new XmlFileKeyValueStore(fileSystem, applicationInstanceRecord.ConfigurationFilePath, MachineKeyEncryptor.ForKeyFile(fileSystem, null)); var selector = new SimpleApplicationInstanceSelectorForTentacleManager( instanceStrategies, @@ -120,7 +121,7 @@ ApplicationInstanceConfiguration LoadInstance() EnsureConfigurationExists(configurationPath); log.Verbose($"Loading configuration from {configurationPath}"); - var writable = new XmlFileKeyValueStore(fileSystem, configurationPath); + var writable = new XmlFileKeyValueStore(fileSystem, configurationPath, MachineKeyEncryptor.ForKeyFile(fileSystem, null)); return (ContributeAdditionalConfiguration(writable), writable); } diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs index 3b29744f5..14f50c9d8 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs @@ -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/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); From f088b1c87512a7cc4cae050a7d6203d6e06cfe8d Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 11:42:51 +1100 Subject: [PATCH 05/12] Reduce ITentacleConfigurationUpgrade to PrepareKey and Run, both throwing --- .../Commands/CreateInstanceCommandFixture.cs | 2 +- .../TentacleConfigurationUpgradeFixture.cs | 10 ++-- .../Commands/CreateInstanceCommand.cs | 2 +- .../Commands/RunAgentCommand.cs | 9 +++- .../UpgradeConfigurationEncryptionCommand.cs | 2 +- .../TentacleConfigurationUpgrade.cs | 51 +++---------------- .../Startup/ServiceCommand.cs | 9 +++- 7 files changed, 30 insertions(+), 55 deletions(-) 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/Configuration/TentacleConfigurationUpgradeFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs index 6a86b8bab..b33c5389e 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs @@ -86,7 +86,7 @@ public void WhenOnlyTheKeyIsPreparedThenItIsCreatedAndValuesStayLegacy() } [Test] - public void WhenTheKeyCannotBeCreatedThenTentacleKeepsWorkingOnTheLegacyKey() + public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() { // Arrange var keyFilePath = Path.Combine(configurationFile, "not-a-directory", ConfigurationEncryptionKey.KeyFileName); @@ -95,15 +95,11 @@ public void WhenTheKeyCannotBeCreatedThenTentacleKeepsWorkingOnTheLegacyKey() var legacyValue = RawCertificate(); // Act - CreateUpgrade(store, keyFilePath).Run(); - store.Set(ProxyConfiguration.ProxyPasswordSettingName, "secret", ProtectionLevel.MachineKey); + Action run = () => CreateUpgrade(store, keyFilePath).Run(); // 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] 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..7490fdbb5 100644 --- a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs +++ b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs @@ -101,7 +101,14 @@ protected override void Start() return; } - configurationUpgrade.Value.Run(); + try + { + configurationUpgrade.Value.Run(); + } + catch (Exception e) + { + log.Warn(e, "Unable to move the configuration to its own encryption key, " + TentacleConfigurationUpgrade.StillOnLegacyKeys); + } 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..8552d1d67 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.Run(); log.Info($"The configuration is protected with the encryption key `{instance.KeyFilePath}`."); } } diff --git a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs index 4acbc1d59..6b905b8aa 100644 --- a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs +++ b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs @@ -14,14 +14,8 @@ 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. @@ -34,7 +28,7 @@ public class TentacleConfigurationUpgrade : ITentacleConfigurationUpgrade 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."; + public 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; @@ -48,36 +42,11 @@ public TentacleConfigurationUpgrade(IApplicationInstanceSelector instanceSelecto } public void PrepareKey() - { - try - { - TryPrepareKey(); - } - catch (Exception e) - { - log.Warn(e, "Unable to prepare the configuration encryption key, " + StillOnLegacyKeys); - } - } - - public void CreateKey() - => TryPrepareKey(); + => PrepareInstanceKey(); 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(); + var prepared = PrepareInstanceKey(); if (prepared == null) { return; @@ -92,13 +61,12 @@ public void RunOrThrow() log.Info($"Re-encrypted the protected setting '{name}' with the configuration encryption key."); } } -#endif } -#if NET - (ConfigurationEncryptionKey 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; } @@ -120,17 +88,14 @@ public void RunOrThrow() var key = new ConfigurationEncryptionKey(log, fileSystem, instance.KeyFilePath); key.CreateIfMissing(); +#if NET var configurationOwner = UnixOwnership.OwnerOf(instance.ConfigurationPath); UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyDirectory!); UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyFilePath!); +#endif return (key, store); } -#else - void TryPrepareKey() - { - } -#endif #if NET static class UnixOwnership diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs index c3bf502ca..7b2279ed6 100644 --- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs +++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs @@ -129,7 +129,14 @@ 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(); + try + { + configurationUpgrade.Value.PrepareKey(); + } + catch (Exception e) + { + log.Warn(e, "Unable to prepare the configuration encryption key, " + TentacleConfigurationUpgrade.StillOnLegacyKeys); + } } } } From c65f762d39a543e47db32980d1a59363f58330d4 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 11:43:10 +1100 Subject: [PATCH 06/12] Move Unix P/Invoke into UnixFile --- source/Octopus.Tentacle.Core/Util/UnixFile.cs | 69 ++++++++++++++++++- .../ConfigurationFilePermissions.cs | 12 +--- .../TentacleConfigurationUpgrade.cs | 67 ++---------------- 3 files changed, 75 insertions(+), 73 deletions(-) diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs index 040ea8d90..1813a57ad 100644 --- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -1,16 +1,83 @@ #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; + // Unlike rename(2), link(2) never replaces an existing file. public static bool TryLinkWithoutReplacing(string existingPath, string newPath) => link(existingPath, newPath) == 0; + 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()}"); + } + } + + 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/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/TentacleConfigurationUpgrade.cs b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs index 6b905b8aa..8b5ff3498 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 @@ -89,71 +89,12 @@ public void Run() key.CreateIfMissing(); #if NET - var configurationOwner = UnixOwnership.OwnerOf(instance.ConfigurationPath); - UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyDirectory!); - UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyFilePath!); + var configurationOwner = UnixFile.OwnerOf(instance.ConfigurationPath); + UnixFile.GiveToIfRoot(configurationOwner, key.KeyDirectory!); + UnixFile.GiveToIfRoot(configurationOwner, key.KeyFilePath!); #endif return (key, store); } - -#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 } } From 455bae85680b5464695debb6c914f1e22204c018 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 11:45:56 +1100 Subject: [PATCH 07/12] Simplify AtomicCreateFileWithUserReadWriteAccessOnly to one implementation --- .../Util/FileSystem/IOctopusFileSystem.cs | 7 +- .../Util/OctopusPhysicalFileSystem.cs | 75 ++++++++----------- source/Octopus.Tentacle.Core/Util/UnixFile.cs | 3 + 3 files changed, 42 insertions(+), 43 deletions(-) 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..47f31b50a 100644 --- a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs @@ -250,73 +250,64 @@ 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; - } + WriteUserReadWriteOnly(temporaryPath, contents); + return PublishWithoutReplacing(temporaryPath, path); } finally { DeleteIfExists(temporaryPath); } } -#else - public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) + + static void WriteUserReadWriteOnly(string path, byte[] contents) { - var temporaryPath = TemporaryPathBeside(path); - try +#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()) { - CreateFileWithUserReadWriteAccessOnly(temporaryPath, contents); + options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + } + + using var stream = new FileStream(path, options); +#endif + stream.Write(contents, 0, contents.Length); + stream.Flush(flushToDisk: true); + } - // 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)) + 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. + if (UnixFile.TryLinkWithoutReplacing(temporaryPath, path)) { return true; } - if (File.Exists(path)) - { - return false; - } - File.Move(temporaryPath, path, overwrite: false); + return File.Exists(path) + ? false + : throw new IOException($"Unable to create `{path}`: {UnixFile.LastErrorMessage()}"); + } +#endif + try + { + // MoveFile never replaces an existing file. + File.Move(temporaryPath, path); 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) { diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs index 1813a57ad..4c2ca859b 100644 --- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -13,6 +13,9 @@ public static class UnixFile public static bool TryLinkWithoutReplacing(string existingPath, string newPath) => link(existingPath, newPath) == 0; + public static string LastErrorMessage() + => Marshal.GetLastPInvokeErrorMessage(); + public static uint OwnerOf(string path) { return SystemNative_Stat(path, out var status) == 0 From 889b1f1f1a227630b154887f6453a912c0d6bb14 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 13:30:02 +1100 Subject: [PATCH 08/12] Resolve the instance's key path in Tentacle Manager instead of passing null --- .../InstanceConfigurationLoader.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs b/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs index ba56bf78c..fb6e13adb 100644 --- a/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs +++ b/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs @@ -53,13 +53,15 @@ public InstanceConfigurationLoader( public InstanceConfiguration LoadConfiguration(ApplicationInstanceRecord applicationInstanceRecord) { - var keyStore = new XmlFileKeyValueStore(fileSystem, applicationInstanceRecord.ConfigurationFilePath, MachineKeyEncryptor.ForKeyFile(fileSystem, null)); + 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); @@ -81,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 { @@ -121,7 +126,7 @@ ApplicationInstanceConfiguration LoadInstance() EnsureConfigurationExists(configurationPath); log.Verbose($"Loading configuration from {configurationPath}"); - var writable = new XmlFileKeyValueStore(fileSystem, configurationPath, MachineKeyEncryptor.ForKeyFile(fileSystem, null)); + var writable = new XmlFileKeyValueStore(fileSystem, configurationPath, encryptor); return (ContributeAdditionalConfiguration(writable), writable); } From b9cd5adb7dc655c49fec1201cb9f73683f947082 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 13:37:27 +1100 Subject: [PATCH 09/12] Rename WriteUserReadWriteOnly to CreateOwnerOnlyFile --- .../Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs index 47f31b50a..1815bf8b1 100644 --- a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs @@ -255,7 +255,7 @@ public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] cont var temporaryPath = TemporaryPathBeside(path); try { - WriteUserReadWriteOnly(temporaryPath, contents); + CreateOwnerOnlyFile(temporaryPath, contents); return PublishWithoutReplacing(temporaryPath, path); } finally @@ -264,7 +264,7 @@ public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] cont } } - static void WriteUserReadWriteOnly(string path, byte[] contents) + static void CreateOwnerOnlyFile(string path, byte[] contents) { #if NETFRAMEWORK using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); From 7b843fb9353403bc36bc96424d00096c20fb54b6 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 13:41:28 +1100 Subject: [PATCH 10/12] Read the link error before another call can overwrite it --- .../Util/OctopusPhysicalFileSystem.cs | 13 +++---------- source/Octopus.Tentacle.Core/Util/UnixFile.cs | 15 +++++++++++---- .../Configuration/TentacleConfigurationUpgrade.cs | 4 ++-- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs index 1815bf8b1..edeca02b6 100644 --- a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs +++ b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs @@ -255,7 +255,7 @@ public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] cont var temporaryPath = TemporaryPathBeside(path); try { - CreateOwnerOnlyFile(temporaryPath, contents); + CreateFileWithUserReadWriteAccessOnly(temporaryPath, contents); return PublishWithoutReplacing(temporaryPath, path); } finally @@ -264,7 +264,7 @@ public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] cont } } - static void CreateOwnerOnlyFile(string path, byte[] contents) + static void CreateFileWithUserReadWriteAccessOnly(string path, byte[] contents) { #if NETFRAMEWORK using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); @@ -287,14 +287,7 @@ static bool PublishWithoutReplacing(string temporaryPath, string path) if (!PlatformDetection.IsRunningOnWindows) { // Unlike File.Move, link(2) is atomic about not replacing: two racing processes cannot each keep their own file. - if (UnixFile.TryLinkWithoutReplacing(temporaryPath, path)) - { - return true; - } - - return File.Exists(path) - ? false - : throw new IOException($"Unable to create `{path}`: {UnixFile.LastErrorMessage()}"); + return UnixFile.TryLinkWithoutReplacing(temporaryPath, path); } #endif try diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs index 4c2ca859b..6b6227f08 100644 --- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs +++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs @@ -8,13 +8,20 @@ namespace Octopus.Tentacle.Core.Util 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; + } - public static string LastErrorMessage() - => Marshal.GetLastPInvokeErrorMessage(); + return Marshal.GetLastPInvokeError() == FileExistsError + ? false + : throw new IOException($"Unable to create `{newPath}`: {Marshal.GetLastPInvokeErrorMessage()}"); + } public static uint OwnerOf(string path) { @@ -23,7 +30,7 @@ public static uint OwnerOf(string path) : throw new IOException($"Unable to find the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}"); } - public static void GiveToIfRoot(uint owner, string path) + public static void SetOwnerIfRunningAsRoot(uint owner, string path) { if (geteuid() != 0 || OwnerOf(path) == owner) { diff --git a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs index 8b5ff3498..7dca2c03b 100644 --- a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs +++ b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs @@ -90,8 +90,8 @@ public void Run() #if NET var configurationOwner = UnixFile.OwnerOf(instance.ConfigurationPath); - UnixFile.GiveToIfRoot(configurationOwner, key.KeyDirectory!); - UnixFile.GiveToIfRoot(configurationOwner, key.KeyFilePath!); + UnixFile.SetOwnerIfRunningAsRoot(configurationOwner, key.KeyDirectory!); + UnixFile.SetOwnerIfRunningAsRoot(configurationOwner, key.KeyFilePath!); #endif return (key, store); From cb7a78be61b249a20878a4eabab96aa6a8d7f18f Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 13:56:41 +1100 Subject: [PATCH 11/12] Move the upgrade's warn-and-continue handling into TentacleConfigurationUpgrade --- .../Commands/RunAgentCommandFixture.cs | 2 +- .../Commands/RunAgentCommand.cs | 9 +------ .../TentacleConfigurationUpgrade.cs | 24 ++++++++++++++++++- .../Startup/ServiceCommand.cs | 9 +------ 4 files changed, 26 insertions(+), 18 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs index bd43cb327..051d58583 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.TryRun(); halibut.Start(); }); } diff --git a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs index 7490fdbb5..8867e1907 100644 --- a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs +++ b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs @@ -101,14 +101,7 @@ protected override void Start() return; } - try - { - configurationUpgrade.Value.Run(); - } - catch (Exception e) - { - log.Warn(e, "Unable to move the configuration to its own encryption key, " + TentacleConfigurationUpgrade.StillOnLegacyKeys); - } + configurationUpgrade.Value.TryRun(); var currentPath = typeof(RunAgentCommand).Assembly.FullLocalPath(); var exePath = PlatformDetection.IsRunningOnWindows diff --git a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs index 7dca2c03b..c1a433cf5 100644 --- a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs +++ b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs @@ -16,6 +16,10 @@ public interface ITentacleConfigurationUpgrade // Prepares the key, then re-encrypts protected settings written with the keys earlier versions used. void Run(); + + // As PrepareKey and Run, but a failure is logged as a warning and Tentacle carries on with the keys earlier versions used. + void TryPrepareKey(); + void TryRun(); } // Until Run succeeds, Tentacle keeps working on the keys earlier versions used. @@ -28,7 +32,7 @@ public class TentacleConfigurationUpgrade : ITentacleConfigurationUpgrade PollingProxyConfiguration.ProxyPasswordSettingName }; - public 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."; + 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; @@ -44,6 +48,24 @@ public TentacleConfigurationUpgrade(IApplicationInstanceSelector instanceSelecto public void PrepareKey() => PrepareInstanceKey(); + public void TryPrepareKey() + => WarnOnFailure(PrepareKey, "Unable to prepare the configuration encryption key"); + + public void TryRun() + => WarnOnFailure(Run, "Unable to move the configuration to its own encryption key"); + + void WarnOnFailure(Action action, string failure) + { + try + { + action(); + } + catch (Exception e) + { + log.Warn(e, $"{failure}, {StillOnLegacyKeys}"); + } + } + public void Run() { var prepared = PrepareInstanceKey(); diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs index 7b2279ed6..3eb479805 100644 --- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs +++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs @@ -129,14 +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. - try - { - configurationUpgrade.Value.PrepareKey(); - } - catch (Exception e) - { - log.Warn(e, "Unable to prepare the configuration encryption key, " + TentacleConfigurationUpgrade.StillOnLegacyKeys); - } + configurationUpgrade.Value.TryPrepareKey(); } } } From f4bc58325423fb42af51b1824d3436d4347754a0 Mon Sep 17 00:00:00 2001 From: Luke Butters Date: Tue, 17 Nov 2026 14:06:27 +1100 Subject: [PATCH 12/12] Rename the configuration upgrade's Run to Upgrade --- .../Commands/RunAgentCommandFixture.cs | 2 +- .../TentacleConfigurationUpgradeFixture.cs | 6 +++--- .../Octopus.Tentacle/Commands/RunAgentCommand.cs | 2 +- .../UpgradeConfigurationEncryptionCommand.cs | 2 +- .../Configuration/TentacleConfigurationUpgrade.cs | 14 +++++++------- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs index 051d58583..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.TryRun(); + configurationUpgrade.TryUpgrade(); halibut.Start(); }); } diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs index b33c5389e..249dcb482 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs @@ -58,7 +58,7 @@ public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted() 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(); @@ -95,7 +95,7 @@ public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy() var legacyValue = RawCertificate(); // Act - Action run = () => CreateUpgrade(store, keyFilePath).Run(); + Action run = () => CreateUpgrade(store, keyFilePath).Upgrade(); // Assert run.Should().Throw(); @@ -112,7 +112,7 @@ public void WhenTheConfigurationIsNotInTheRegistryThenNoKeyIsCreatedAndValuesSta var legacyValue = RawCertificate(); // Act - CreateUpgrade(store, keyFilePath: null, instanceName: null).Run(); + CreateUpgrade(store, keyFilePath: null, instanceName: null).Upgrade(); // Assert File.Exists(keyFilePath).Should().BeFalse(); diff --git a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs index 8867e1907..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.TryRun(); + 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 8552d1d67..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.Run(); + configurationUpgrade.Value.Upgrade(); log.Info($"The configuration is protected with the encryption key `{instance.KeyFilePath}`."); } } diff --git a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs index c1a433cf5..daa7272a7 100644 --- a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs +++ b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs @@ -15,14 +15,14 @@ public interface ITentacleConfigurationUpgrade void PrepareKey(); // Prepares the key, then re-encrypts protected settings written with the keys earlier versions used. - void Run(); + void Upgrade(); - // As PrepareKey and Run, but a failure is logged as a warning and Tentacle carries on with the keys earlier versions used. + // 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 TryRun(); + 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[] @@ -51,8 +51,8 @@ public void PrepareKey() public void TryPrepareKey() => WarnOnFailure(PrepareKey, "Unable to prepare the configuration encryption key"); - public void TryRun() - => WarnOnFailure(Run, "Unable to move the configuration to its own encryption key"); + public void TryUpgrade() + => WarnOnFailure(Upgrade, "Unable to move the configuration to its own encryption key"); void WarnOnFailure(Action action, string failure) { @@ -66,7 +66,7 @@ void WarnOnFailure(Action action, string failure) } } - public void Run() + public void Upgrade() { var prepared = PrepareInstanceKey(); if (prepared == null)