diff --git a/docker/linux/Dockerfile b/docker/linux/Dockerfile
index af5fe799f..e0047a8ea 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 02e848083..d60c71724 100644
--- a/docker/linux/scripts/configure-and-run.sh
+++ b/docker/linux/scripts/configure-and-run.sh
@@ -1,6 +1,15 @@
#!/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_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/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
+
/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 5c1657cb4..365deab5e 100644
--- a/docker/readme.md
+++ b/docker/readme.md
@@ -118,6 +118,17 @@ The certificate includes its private key, so treat it as a secret. Pass it with
`ServerThumbprint` can't be combined with settings that only apply to registering or polling, such as `ServerUrl`, the credentials, `ServerCommsAddress`, `ServerPort` or the `Target*` variables; the container exits with an error if any are set.
+### Volumes
+
+Mount these to keep the Tentacle's identity when the container is re-created:
+
+| Path | Contains |
+| --- | --- |
+| `/etc/octopus` | Configuration, including the certificate |
+| `/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.
+
### 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..3da47514f 100644
--- a/linux-packages/test-scripts/test-linux-package.sh
+++ b/linux-packages/test-scripts/test-linux-package.sh
@@ -56,5 +56,43 @@ fi
echo "The installed Tentacle version matches the expected one."
echo ""
+# 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"
+
+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."
+echo ""
+
echo "All tests passed."
echo ""
diff --git a/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs b/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs
index 29c1b0e8e..06cf414af 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
{
@@ -112,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)
@@ -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.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/EnvironmentVariables.cs b/source/Octopus.Tentacle.Core/Util/EnvironmentVariables.cs
index 2b5f83a59..a66e43850 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 TentacleInstancesDataDirectory = "TentacleInstancesDataDirectory";
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..c27ef1e2c 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;
@@ -36,6 +37,19 @@ public interface IOctopusFileSystem
void WriteAllBytes(string filePath, byte[] data);
void WriteAllText(string filePath, string contents);
+
+ ///
+ /// 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.
+ /// 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.
+#if NET
+ [UnsupportedOSPlatform("windows")]
+#endif
+ 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 0cc039524..ab6ed1547 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,6 +252,64 @@ public void WriteAllText(string path, string contents)
File.WriteAllText(path, contents);
}
+#if NET
+ [UnsupportedOSPlatform("windows")]
+ public bool TryAtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents)
+ {
+ if (OperatingSystem.IsWindows())
+ {
+ throw new PlatformNotSupportedException(UserOnlyFilesAreUnixOnly);
+ }
+
+ var temporaryPath = TemporaryPathBeside(path);
+ try
+ {
+ CreateFileWithUserReadWriteAccessOnly(temporaryPath, contents);
+ File.Move(temporaryPath, path);
+ return true;
+ }
+ catch (IOException) when (File.Exists(path))
+ {
+ return false;
+ }
+ finally
+ {
+ DeleteIfExists(temporaryPath);
+ }
+ }
+
+ [UnsupportedOSPlatform("windows")]
+ static void CreateFileWithUserReadWriteAccessOnly(string path, byte[] contents)
+ {
+ var options = new FileStreamOptions
+ {
+ Mode = FileMode.CreateNew,
+ Access = FileAccess.Write,
+ Share = FileShare.None,
+ UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite
+ };
+
+ using var stream = new FileStream(path, options);
+ stream.Write(contents, 0, contents.Length);
+ 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 is renamed rather than copied.
+ static string TemporaryPathBeside(string path)
+ => path + "." + Guid.NewGuid().ToString("N") + ".tmp";
+#else
+ public bool TryAtomicCreateFileWithOnlyUserReadWritePermissions(string path, byte[] contents)
+ => throw new PlatformNotSupportedException(UserOnlyFilesAreUnixOnly);
+#endif
+
public void EnsureDirectoryExists(string directoryPath)
{
if (!DirectoryExists(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.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs
new file mode 100644
index 000000000..d60fe9de6
--- /dev/null
+++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs
@@ -0,0 +1,80 @@
+#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;
+
+ 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")]
+ 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);
+
+ // 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);
+
+ [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.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs
new file mode 100644
index 000000000..a2aa4929a
--- /dev/null
+++ b/source/Octopus.Tentacle.Docker.Tests.Integration/LinuxTentacleConfigEncryptionTests.cs
@@ -0,0 +1,92 @@
+using FluentAssertions;
+using Octopus.Tentacle.Client.Scripts.Models.Builders;
+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;
+
+///
+/// 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
+{
+ [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()
+ {
+ // 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();
+
+ RegisteredMachine registeredMachine;
+ await using (var tentacle = await new TentacleContainerBuilder(server)
+ .WithVolume(config, "/etc/octopus")
+ .WithVolume(data, "/var/lib/octopus/tentacle")
+ .Build())
+ {
+ registeredMachine = tentacle.RegisteredMachine;
+ }
+
+ var command = new ExecuteShellScriptCommandBuilder(LoggingUtils.CurrentTestHash(), ScriptIsolationLevel.NoIsolation)
+ .WithScriptBody("echo 'running after being re-created'\n")
+ .Build();
+
+ // Act
+ 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(command);
+
+ // Assert
+ result.ExitCode.Should().Be(0, output);
+ output.Should().Contain("running after being re-created");
+ }
+
+ [Test]
+ public async Task TheContainerRefusesToStartWhenOnlyTheConfigurationIsPersisted()
+ {
+ // Arrange
+ await using var config = await DockerVolume.Create(CancellationToken.None);
+ await using var server = await new FakeOctopusServerBuilder().Build();
+
+ // Act
+ var (exitCode, logs) = await new TentacleContainerBuilder(server)
+ .WithVolume(config, "/etc/octopus")
+ .RunUntilExit();
+
+ // Assert
+ exitCode.Should().NotBe(0, logs);
+ logs.Should().Contain("/var/lib/octopus/tentacle is not");
+ }
+}
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 0681265c5..68e13dc26 100644
--- a/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs
+++ b/source/Octopus.Tentacle.Docker.Tests.Integration/Setup/TentacleContainerBuilder.cs
@@ -28,6 +28,8 @@ public class TentacleContainerBuilder
string? serverThumbprint;
string? certificateBase64;
readonly Dictionary extraEnvironment = new();
+ readonly List volumeMounts = new();
+ RegisteredMachine? alreadyRegistered;
public TentacleContainerBuilder(FakeOctopusServer server)
{
@@ -83,6 +85,22 @@ public TentacleContainerBuilder WithEnvironmentVariable(string name, string valu
return this;
}
+ public TentacleContainerBuilder WithVolume(DockerVolume volume, string containerPath)
+ {
+ volumeMounts.Add(volume.MountAt(containerPath));
+ 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;
+ }
+
public async Task Build()
{
if (serverThumbprint is not null && communicationStyle == TentacleCommunicationStyle.Polling)
@@ -97,7 +115,9 @@ public async Task Build()
var image = TentacleImage.Resolve();
TestContext.Out.WriteLine($"Testing {image} as a {communicationStyle} Tentacle named {machineName}{(serverThumbprint is null ? "" : " that does not register")}");
- var registration = serverThumbprint is null ? server.WaitForRegistration(FakeOctopusServerBuilder.SpaceName, machineName) : null;
+ 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);
@@ -158,6 +178,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/source/Octopus.Tentacle.Tests.Integration.Common/FakeOctopus/FakeOctopusServer.cs b/source/Octopus.Tentacle.Tests.Integration.Common/FakeOctopus/FakeOctopusServer.cs
index 7d1f3be78..ad181dd3f 100644
--- a/source/Octopus.Tentacle.Tests.Integration.Common/FakeOctopus/FakeOctopusServer.cs
+++ b/source/Octopus.Tentacle.Tests.Integration.Common/FakeOctopus/FakeOctopusServer.cs
@@ -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.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs b/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs
new file mode 100644
index 000000000..02eb0e999
--- /dev/null
+++ b/source/Octopus.Tentacle.Tests.Integration/Commands/LinuxResetConfigurationEncryptionTests.cs
@@ -0,0 +1,103 @@
+#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.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;
+
+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 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()
+ {
+ // 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.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs
new file mode 100644
index 000000000..e8a8b6076
--- /dev/null
+++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationEncryptionUpgradeTests.cs
@@ -0,0 +1,273 @@
+#if NET
+using System.IO;
+using System.Runtime.Versioning;
+using System.Threading.Tasks;
+using CliWrap;
+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
+{
+ [LinuxTest]
+ [UnsupportedOSPlatform("windows")]
+ public class ConfigurationEncryptionUpgradeTests : IntegrationTest
+ {
+ static readonly string EncryptedWithItsOwnKey = LinuxMachineKeyEncryptor.Specifier + "$";
+
+ [Test]
+ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndUpgradeConfigurationEncryptionIsCalled_ThenTheCertificateIsReEncrypted()
+ {
+ // Arrange
+ using var instance = await new TentacleInstanceBuilder()
+ .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption)
+ .WithNewCertificate()
+ .Build(Logger, CancellationToken);
+ 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", CancellationToken);
+
+ // Assert
+ instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey);
+ File.Exists(instance.ConfigurationEncryptionKeyFile).Should().BeTrue();
+ (await upgradedInstance.ShowThumbprint(CancellationToken)).Should().Be(thumbprintBeforeUpgrade, "the upgraded certificate must still decrypt to the same certificate");
+ }
+
+ [Test]
+ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheNewKeyCannotBeCreated_ThenUpgradeConfigurationEncryptionFailsAndTheCertificateIsUnchanged()
+ {
+ // Arrange
+ using var instance = await new TentacleInstanceBuilder()
+ .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption)
+ .WithNewCertificate()
+ .Build(Logger, CancellationToken);
+ 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 upgradedInstance = instance.WithCurrentTentacleExe();
+ var upgrade = await upgradedInstance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "upgrade-configuration-encryption", CancellationToken);
+
+ // 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");
+ instance.CertificateAsStoredInTheConfigurationFile().Should().Be(certificateEncryptedByVersion14);
+ }
+
+ [Test]
+ public async Task WhenTentacleInstanceIsUnnamed_AndUpgradeConfigurationEncryptionIsCalled_ThenItFailsAndSaysToCreateANamedInstance()
+ {
+ // 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", CancellationToken);
+
+ // 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);
+ }
+
+ [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", CancellationToken);
+
+ // 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);
+ }
+
+ [Test]
+ public async Task WhenTentacleKeyIsEncryptedWithEtcMachineId_AndTheCurrentTentacleStarts_ThenTheCertificateIsReEncrypted()
+ {
+ // Arrange
+ await using var runningTentacle = await new TentacleInstanceBuilder()
+ .WithTentacleVersion(TentacleVersions.v14_0_4849_LastWithMachineIdConfigurationEncryption)
+ .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 runningTentacle.StopAndStartWithCurrentVersionOfTentacle(CancellationToken);
+
+ // Assert
+ runningTentacle.Instance.CertificateAsStoredInTheConfigurationFile().Should().StartWith(EncryptedWithItsOwnKey);
+ (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
+ 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);
+ }
+
+ [Test]
+ public async Task WhenTentacleKeyFileIsDeleted_AndTheCurrentTentacleStarts_ThenTheUserIsToldTheKeyIsMissing()
+ {
+ // Arrange
+ using var instance = await new TentacleInstanceBuilder()
+ .WithNewCertificate()
+ .Build(Logger, CancellationToken);
+ var certificateEncryptedWithTheKey = instance.CertificateAsStoredInTheConfigurationFile();
+ File.Delete(instance.ConfigurationEncryptionKeyFile);
+
+ // Act
+ var agent = await instance.ExecuteTentacleCommandOnTheInstance(CommandResultValidation.None, "agent", CancellationToken);
+
+ // Assert
+ 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);
+ }
+
+ [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]
+ [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.ExecuteTentacleCommandOnTheInstanceAsRoot(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.ExecuteTentacleCommandOnTheInstanceAsRoot(CommandResultValidation.None, "service", CancellationToken, "--uninstall");
+ await instance.SudoDeleteTheDataDirectory();
+ }
+ }
+
+ [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/LinuxConfigurationFilePermissionsTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/LinuxConfigurationFilePermissionsTests.cs
index 072aac762..58acb914e 100644
--- a/source/Octopus.Tentacle.Tests.Integration/Configuration/LinuxConfigurationFilePermissionsTests.cs
+++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/LinuxConfigurationFilePermissionsTests.cs
@@ -23,7 +23,7 @@ public class LinuxConfigurationFilePermissionsTests
[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
new file mode 100644
index 000000000..97f75951e
--- /dev/null
+++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/NonRootCreateInstanceTests.cs
@@ -0,0 +1,69 @@
+#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.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 : IntegrationTest
+ {
+ [Test]
+ [RequiresSudoOnLinux]
+ public async Task WhenANonRootUserCreatesAnIntance_AndCannotCreateTheKey_ThenRunningTheCommandInTheErrorFixesTheIssue()
+ {
+ // Arrange
+ 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;
+ 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);
+
+ // 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();
+ }
+
+ static Task Sudo(params string[] arguments)
+ => Cli.Wrap("sudo").WithArguments(arguments).WithValidation(CommandResultValidation.None).ExecuteBufferedAsync();
+ }
+}
+#endif
diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs
index 9f9f08c19..32520266b 100644
--- a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs
+++ b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs
@@ -1,11 +1,16 @@
using System;
+using System.IO;
using System.Linq;
+using System.Runtime.Versioning;
+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;
using Octopus.Tentacle.Diagnostics;
using Octopus.Tentacle.Security.Certificates;
+using Octopus.Tentacle.Util;
using Serilog;
namespace Octopus.Tentacle.Tests.Integration.Support
@@ -30,18 +35,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 +62,42 @@ 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)
+ {
+ CreateLegacyMachineKeyIfMissing(fileSystem, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost);
+ }
+ }
+
+ [UnsupportedOSPlatform("windows")]
+ 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.TryAtomicCreateFileWithOnlyUserReadWritePermissions(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.Integration/Support/TentacleInstanceBuilder.cs b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs
index fa2876c6e..5ff2b2769 100644
--- a/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs
+++ b/source/Octopus.Tentacle.Tests.Integration/Support/TentacleInstanceBuilder.cs
@@ -2,14 +2,18 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Xml.Linq;
using System.Threading;
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;
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
@@ -120,7 +124,10 @@ public async Task Build(ILogger logger, CancellationToken canc
? TentacleExeFinder.FindTentacleExe()
: await TentacleFetcher.GetTentacleVersion(download.DirectoryPath, tentacleVersion, DefaultTentacleRuntime.Value, logger, cancellationToken));
var instanceHome = home ?? new TemporaryDirectory();
- var environment = new Dictionary();
+ var environment = new Dictionary
+ {
+ [EnvironmentVariables.TentacleInstancesDataDirectory] = Path.Combine(instanceHome.DirectoryPath, "data")
+ };
if (!useDefaultMachineConfigurationHomeDirectory)
{
environment[EnvironmentVariables.TentacleMachineConfigurationHomeDirectory] = Path.Combine(instanceHome.DirectoryPath, "Octopus", "Tentacle", "Instances");
@@ -179,6 +186,8 @@ internal TentacleInstance(TemporaryDirectory home, string tentacleExe, string? n
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()
@@ -187,6 +196,9 @@ public TentacleInstance WithCurrentTentacleExe()
internal TentacleInstance WithThumbprint(string thumbprint)
=> 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(CancellationToken cancellationToken)
=> (await ExecuteTentacleCommandOnTheInstance(CommandResultValidation.ZeroExitCode, "show-thumbprint", cancellationToken)).StandardOutput.Trim();
@@ -196,6 +208,67 @@ 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);
+
+ 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();
+
+ // 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);
+ }
+
+ 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 = launcher
+ .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/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();
}
diff --git a/source/Octopus.Tentacle.Tests.Integration/TentacleCommandLineTests.cs b/source/Octopus.Tentacle.Tests.Integration/TentacleCommandLineTests.cs
index 1efc9c236..e5fa80baf 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.TentacleInstancesDataDirectory))
+ {
+ environmentVariablesToRunTentacleWith.Add(EnvironmentVariables.TentacleInstancesDataDirectory, Path.Combine(tempDirectory.DirectoryPath, "data"));
+ }
+
var tentacleExe = TentacleExeFinder.FindTentacleExe(tentacleConfigurationTestCase.TentacleRuntime);
var output = new StringBuilder();
var errorOut = new StringBuilder();
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/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 bb6d86510..5ec688d9d 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
@@ -27,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" +
@@ -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/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/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 80720309d..105ad47b1 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/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs
index 5dc535221..c4adf89a6 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!;
+ IConfigurationEncryptionUpgrade configurationEncryptionUpgrade = null!;
[SetUp]
public override void SetUp()
@@ -41,6 +42,7 @@ public override void SetUp()
tentacleConfiguration.TentacleCertificate.Returns(certificate);
home = Substitute.For();
sleep = Substitute.For();
+ configurationEncryptionUpgrade = Substitute.For();
backgroundTasks = new[]
{
@@ -61,9 +63,10 @@ public override void SetUp()
new AppVersion(GetType().Assembly),
Substitute.For(),
backgroundTasks.Select(bt => new Lazy(() => bt)).ToList(),
- Substitute.For());
+ Substitute.For(),
+ 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/Configuration/ApplicationInstanceSelectorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs
index 4ce170ef8..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
@@ -92,6 +93,23 @@ public void GivenConfigurationInstanceExists_WhenRequestingConfigurationInstance
mock.Current.ConfigurationPath.Should().Be(filePath);
}
+ [Test]
+ [LinuxOrMacTest]
+ public void GivenARegisteredInstanceUsesTheConfiguration_WhenRequestingConfigurationInstance_ThenItUsesThatInstancesKey()
+ {
+ 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()
{
diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs
new file mode 100644
index 000000000..29bed9796
--- /dev/null
+++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityTests.cs
@@ -0,0 +1,53 @@
+#if !NETFRAMEWORK
+using System;
+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
+{
+ // 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
+ {
+ [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" });
+ var encryptor = MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle"), "/etc/octopus/machinekey");
+
+ // Act
+ var decrypted = encryptor.Decrypt(legacyCiphertext);
+
+ // Assert
+ decrypted.Should().Be("pässwörd 🐙 with spaces & symbols!");
+ }
+
+ [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==");
+ var encryptor = MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle"), "/etc/octopus/machinekey");
+
+ // Act
+ var decrypted = encryptor.Decrypt(legacyCiphertext);
+
+ // Assert
+ decrypted.Should().Be("pässwörd 🐙 with spaces & symbols!");
+ }
+ }
+}
+#endif
diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs
new file mode 100644
index 000000000..898367704
--- /dev/null
+++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationEncryptionKeyFileTests.cs
@@ -0,0 +1,45 @@
+#if !NETFRAMEWORK
+using System;
+using System.IO;
+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;
+using Octopus.Tentacle.Tests.Support.TestAttributes;
+using Octopus.Tentacle.Util;
+
+namespace Octopus.Tentacle.Tests.Configuration.Crypto
+{
+ [LinuxTest]
+ [SupportedOSPlatform("linux")]
+ public class LinuxConfigurationEncryptionKeyFileTests
+ {
+ const UnixFileMode OwnerReadWrite = UnixFileMode.UserRead | UnixFileMode.UserWrite;
+
+ [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
+ 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(keyDirectory).Should().ContainSingle("the temporary file the key is written to first is not 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..4db41b01e 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()
+ {
+ ConfigurationEncryptionKey.KeyFilePathFor("Tentacle").Should().Be("/var/lib/octopus/tentacle/Tentacle/keys/config-encryption.key");
+ }
+
+ [TestCase("")]
+ [TestCase("..")]
+ [TestCase("../etc")]
+ [TestCase("a\\b")]
+ public void InstanceNamesThatAreNotASingleDirectoryNameAreRejected(string instanceName)
+ {
+ Assert.Throws(() => ConfigurationEncryptionKey.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
deleted file mode 100644
index 53dc2154b..000000000
--- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs
+++ /dev/null
@@ -1,86 +0,0 @@
-using System;
-using System.Security.Cryptography;
-using FluentAssertions;
-using NSubstitute;
-using NUnit.Framework;
-using Octopus.Tentacle.Configuration.Crypto;
-using Octopus.Tentacle.Core.Diagnostics;
-
-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);
-
- Assert.AreNotEqual(encrypted, "FooBar");
- Assert.AreEqual(decrypted, "FooBar");
- }
-
- [Test]
- public void GivenCorruptKeyProvided_ThenThrowsException()
- {
- 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});
-
- var roundTrip = lme.Decrypt(lme.Encrypt("FooBar"));
-
- roundTrip.Should().Be("FooBar");
- }
-
- [Test]
- public void GenMultipleKeys_FirstSuccessfulKeyIsUsed()
- {
- 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();
- }
-
- static ICryptoKeyNixSource DodgyKey()
- {
- var dodgyKey = Substitute.For();
- dodgyKey.Load().Returns(callInfo => (new byte[] {77}, new byte[]{43, 11}));
- return dodgyKey;
- }
-
- 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);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorTests.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorTests.cs
new file mode 100644
index 000000000..e9a778812
--- /dev/null
+++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorTests.cs
@@ -0,0 +1,80 @@
+#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;
+using Octopus.Tentacle.Util;
+
+namespace Octopus.Tentacle.Tests.Configuration.Crypto
+{
+ public class LinuxMachineKeyEncryptorTests
+ {
+ [Test]
+ public void WhenAValueIsEncryptedThenItIsVersionedAndDecrypts()
+ {
+ // Arrange
+ var encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), Array.Empty());
+
+ // Act
+ var encrypted = encryptor.Encrypt("FooBar");
+
+ // Assert
+ 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");
+ }
+
+ [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()
+ {
+ // Arrange
+ 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);
+
+ // Assert
+ decrypt.Should().Throw();
+ }
+
+ [TestCase("AESGCM-V2")]
+ [TestCase("aesgcm-v1")]
+ public void WhenTheSpecifierIsAlteredThenDecryptionFails(string alteredSpecifier)
+ {
+ // Arrange
+ 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);
+
+ // Assert
+ decrypt.Should().Throw().WithMessage("*Unknown encryption specifier*");
+ }
+ }
+}
+#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/Support/TentacleConfigurationBuilder.cs b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs
index c4c93919c..44155ff9b 100644
--- a/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs
+++ b/source/Octopus.Tentacle.Tests/Support/TentacleConfigurationBuilder.cs
@@ -26,10 +26,10 @@ 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));
+ selector.Current.Returns(_ => new ApplicationInstanceConfiguration(null, configFile, store, store, null));
var configuration = new WritableTentacleConfiguration(
selector,
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");
+ }
+ }
+ }
+}
diff --git a/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs b/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs
new file mode 100644
index 000000000..35116c013
--- /dev/null
+++ b/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs
@@ -0,0 +1,60 @@
+using System;
+using System.Security.Cryptography;
+using NSubstitute;
+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
+{
+ // 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(), InMemoryConfigurationEncryptionKey.Create(), 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 static class InMemoryConfigurationEncryptionKey
+ {
+ 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(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;
+ }
+ }
+}
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}");
}
}
}
diff --git a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs
index b990a3b61..ee32afc14 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 configurationEncryptionUpgrade;
string instanceName = null!;
string config = null!;
string home = null!;
- public CreateInstanceCommand(IApplicationInstanceManager instanceManager, ILogFileOnlyLogger logFileOnlyLogger) : base(logFileOnlyLogger)
+ public CreateInstanceCommand(IApplicationInstanceManager instanceManager, ILogFileOnlyLogger logFileOnlyLogger, Lazy configurationEncryptionUpgrade) : base(logFileOnlyLogger)
{
this.instanceManager = instanceManager;
+ 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);
@@ -29,6 +32,9 @@ 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.
+ configurationEncryptionUpgrade.Value.PrepareKey();
}
}
}
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/Commands/RunAgentCommand.cs b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs
index 87e6f895d..325efbadd 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 configurationEncryptionUpgrade;
readonly ISleep sleep;
readonly ISystemLog log;
@@ -53,12 +54,14 @@ public RunAgentCommand(
AppVersion appVersion,
ILogFileOnlyLogger logFileOnlyLogger,
IEnumerable> backgroundTasks,
- IConfigurationFilePermissions configurationFilePermissions) : base(selector, log, logFileOnlyLogger)
+ IConfigurationFilePermissions configurationFilePermissions,
+ Lazy configurationEncryptionUpgrade) : base(selector, log, logFileOnlyLogger)
{
this.halibut = halibut;
this.configuration = configuration;
this.home = home;
this.proxyConfiguration = proxyConfiguration;
+ this.configurationEncryptionUpgrade = configurationEncryptionUpgrade;
this.sleep = sleep;
this.log = log;
this.selector = selector;
@@ -101,6 +104,8 @@ protected override void Start()
return;
}
+ configurationEncryptionUpgrade.Value.TryUpgrade();
+
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..450bb6e32
--- /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 configurationEncryptionUpgrade;
+ readonly IApplicationInstanceSelector instanceSelector;
+ readonly ISystemLog log;
+
+ public UpgradeConfigurationEncryptionCommand(
+ Lazy configurationEncryptionUpgrade,
+ IApplicationInstanceSelector instanceSelector,
+ ISystemLog log,
+ ILogFileOnlyLogger logFileOnlyLogger)
+ : base(instanceSelector, log, logFileOnlyLogger)
+ {
+ this.configurationEncryptionUpgrade = configurationEncryptionUpgrade;
+ 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.");
+ }
+
+ configurationEncryptionUpgrade.Value.Upgrade();
+ log.Info($"The configuration is protected with the encryption key `{instance.KeyFilePath}`.");
+ }
+ }
+}
diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs b/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs
new file mode 100644
index 000000000..88ed501c3
--- /dev/null
+++ b/source/Octopus.Tentacle/Configuration/ConfigurationEncryptionUpgrade.cs
@@ -0,0 +1,121 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+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
+{
+ 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();
+
+ // Prepares the key, then re-encrypts protected settings written with the keys earlier versions used.
+ void Upgrade();
+
+ // 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 Upgrade succeeds, Tentacle keeps working on the keys earlier versions used.
+ public class ConfigurationEncryptionUpgrade : IConfigurationEncryptionUpgrade
+ {
+ public static readonly IReadOnlyList ProtectedSettingNames = new[]
+ {
+ TentacleConfiguration.CertificateSettingName,
+ ProxyConfiguration.ProxyPasswordSettingName,
+ PollingProxyConfiguration.ProxyPasswordSettingName
+ };
+
+ readonly IApplicationInstanceSelector instanceSelector;
+ readonly IOctopusFileSystem fileSystem;
+ readonly ISystemLog log;
+
+ public ConfigurationEncryptionUpgrade(IApplicationInstanceSelector instanceSelector, IOctopusFileSystem fileSystem, ISystemLog log)
+ {
+ this.instanceSelector = instanceSelector;
+ this.fileSystem = fileSystem;
+ this.log = log;
+ }
+
+ public void PrepareKey()
+ => PrepareInstanceKey();
+
+ public void TryPrepareKey()
+ => WarnOnFailure(PrepareKey, "Unable to prepare the configuration encryption key");
+
+ public void TryUpgrade()
+ => WarnOnFailure(Upgrade, "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}, 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 void Upgrade()
+ {
+ var prepared = PrepareInstanceKey();
+ if (prepared == null)
+ {
+ return;
+ }
+
+ 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)
+ {
+ if (store.ReEncryptIfLegacy(name))
+ {
+ log.Info($"Re-encrypted the protected setting '{name}' with the configuration encryption key.");
+ }
+ }
+ }
+
+ // Null when the instance has no key to prepare.
+ (ConfigurationEncryptionKey Key, XmlFileKeyValueStore Store)? PrepareInstanceKey()
+ {
+ if (PlatformDetection.IsRunningOnWindows)
+ {
+ 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 ConfigurationEncryptionKey(log, fileSystem, instance.KeyFilePath);
+ key.CreateIfMissing();
+
+#if NET
+ var configurationOwner = UnixFile.OwnerOf(instance.ConfigurationPath);
+ UnixFile.SetOwnerIfRunningAsRoot(configurationOwner, key.KeyDirectory!);
+ UnixFile.SetOwnerIfRunningAsRoot(configurationOwner, key.KeyFilePath!);
+#endif
+
+ return (key, store);
+ }
+ }
+}
diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs b/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs
index 9f36dd55f..bbf2fd04e 100644
--- a/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs
+++ b/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs
@@ -99,7 +99,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/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs
new file mode 100644
index 000000000..28d1b6d2b
--- /dev/null
+++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs
@@ -0,0 +1,185 @@
+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;
+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 DefaultInstancesDataDirectory = "/var/lib/octopus/tentacle";
+
+ 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
+
+ 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;
+
+ 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(JoinLinuxPath(InstancesDataDirectory, instanceName), "keys"), KeyFileName);
+ }
+
+ public byte[] Load()
+ => 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);
+
+ public byte[]? TryLoad()
+ {
+ if (loaded != null)
+ {
+ return loaded;
+ }
+
+ if (KeyFilePath == null)
+ {
+ return null;
+ }
+
+ 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 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);
+ }
+
+ loaded = Parse(KeyFilePath, contents);
+ 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.");
+ if (fileSystem.FileExists(path))
+ {
+ return;
+ }
+
+ var raw = Convert.ToBase64String(RandomKey());
+
+ CreateKeyDirectory(KeyDirectory!);
+
+ if (!fileSystem.TryAtomicCreateFileWithOnlyUserReadWritePermissions(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.");
+ }
+
+ // 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];
+ using var random = RandomNumberGenerator.Create();
+ random.GetBytes(key);
+ return key;
+ }
+
+ static byte[] Parse(string path, string contents)
+ {
+ try
+ {
+ var key = Convert.FromBase64String(contents.Trim());
+ if (key.Length == KeySizeInBytes)
+ {
+ return key;
+ }
+ }
+ catch (FormatException)
+ {
+ }
+
+ 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);
+ }
+
+ // 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/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/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..46980e01b 100644
--- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs
+++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs
@@ -1,65 +1,50 @@
using System;
using System.IO;
-using System.Security.Cryptography;
-using Octopus.Tentacle.Core.Diagnostics;
using Octopus.Tentacle.Core.Util;
using Octopus.Tentacle.Util;
namespace Octopus.Tentacle.Configuration.Crypto
{
- public class LinuxGeneratedMachineKey: ICryptoKeyNixSource
+ // 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
{
- readonly ISystemLog log;
- readonly IOctopusFileSystem fileSystem;
+ public const string LegacyKeyFileName = "machinekey";
+
+ public const string LegacyKeyFilePath = "/etc/octopus/" + LegacyKeyFileName;
- 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";
+ readonly IOctopusFileSystem fileSystem;
+ readonly string path;
- public LinuxGeneratedMachineKey(ISystemLog log, IOctopusFileSystem fileSystem)
+ public LinuxGeneratedMachineKey(IOctopusFileSystem fileSystem, string path)
{
- this.log = log;
this.fileSystem = fileSystem;
+ this.path = path;
}
- void Generate()
- {
- 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();
- 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.WriteAllText(FileName, raw);
- }
+ public static string LegacyKeyFilePathForThisHost
+ => KubernetesSupportDetection.IsRunningAsKubernetesAgent
+ //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;
- (byte[] Key, byte[] IV) LoadFromFile()
+ public (byte[] Key, byte[] IV) Load()
{
+ if (!fileSystem.FileExists(path))
+ {
+ throw new InvalidOperationException($"There is no machine key file at `{path}`.");
+ }
+
try
{
- var content = fileSystem.ReadAllText(FileName).Split('.');
- var key = Convert.FromBase64String(content[0]);
- var iv = Convert.FromBase64String(content[1]);
- 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)
{
- 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. "
+ + "Restore it from a backup. " + ConfigurationEncryptionKey.RecoveryWithoutBackup);
}
}
-
- public (byte[] Key, byte[] IV) Load()
- {
- if (!fileSystem.FileExists(FileName))
- Generate();
- return LoadFromFile();
- }
}
-}
\ 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..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/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs
index c9d9427d1..12596da2c 100644
--- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs
+++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs
@@ -1,65 +1,221 @@
-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 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 = "AESGCM-V1";
+ // $ 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(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);
+
readonly ISystemLog log;
- readonly IEnumerable keySources;
+ readonly ConfigurationEncryptionKey configurationKey;
+ readonly IReadOnlyList legacyKeySources;
- public LinuxMachineKeyEncryptor(ISystemLog log, IEnumerable keySources)
+ public LinuxMachineKeyEncryptor(ISystemLog log, ConfigurationEncryptionKey configurationKey, IEnumerable legacyKeySources)
{
this.log = log;
- this.keySources = keySources;
+ this.configurationKey = configurationKey;
+ this.legacyKeySources = legacyKeySources.ToArray();
}
+ static bool IsLegacyCiphertext(string encrypted)
+ => encrypted.IndexOf(FieldSeparator) < 0;
+
+ public bool RequiresReEncryption(string encrypted)
+ => IsLegacyCiphertext(encrypted);
+
+ // Until the configuration encryption upgrade has created the key, values are written the way earlier versions wrote them.
public string Encrypt(string raw)
{
- return IterateKeySourcesUntilCryptoSuccess(cipherKeys =>
+ var currentKey = configurationKey.TryLoad();
+ try
{
- 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);
- });
+ 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);
+ }
}
- public string Decrypt(string encrypted)
+ static string EncryptCurrent(byte[] key, string raw)
{
- return IterateKeySourcesUntilCryptoSuccess(cipherKeys =>
+ var nonce = new byte[NonceSizeInBytes];
+ using (var random = RandomNumberGenerator.Create())
+ {
+ random.GetBytes(nonce);
+ }
+
+ 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);
+
+ return string.Join(FieldSeparator.ToString(), Specifier, Convert.ToBase64String(nonce), Convert.ToBase64String(tag), Convert.ToBase64String(ciphertext));
+ }
+
+ string EncryptLegacy(string raw)
+ {
+ var (encrypted, errors) = TryEachLegacyKey(legacy =>
{
- 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);
+ 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 IterateKeySourcesUntilCryptoSuccess(Func<(byte[] Key, byte[] IV), string> cipherOp)
+ (string? Result, List Errors) TryEachLegacyKey(Func<(byte[] Key, byte[] IV), string> use)
{
- var ex = new List();
- foreach (var source in keySources)
+ var errors = new List();
+ foreach (var source in legacyKeySources)
{
try
{
- return cipherOp(source.Load());
+ return (use(source.Load()), errors);
}
catch (Exception e)
{
log.Verbose(e.Message);
- ex.Add(e);
+ errors.Add(e);
}
}
- throw new AggregateException(ex);
+ return (null, errors);
+ }
+
+ public string Decrypt(string encrypted)
+ => IsLegacyCiphertext(encrypted)
+ ? DecryptLegacy(encrypted)
+ : DecryptCurrent(encrypted);
+
+ string DecryptCurrent(string encrypted)
+ {
+ byte[] key;
+ try
+ {
+ key = configurationKey.Load();
+ }
+ catch (Exception e)
+ {
+ throw new CryptographicException(e.Message, e);
+ }
+
+ try
+ {
+ var (nonce, tag, ciphertext) = ParsePayload(encrypted);
+ var plaintext = Gcm.Decrypt(key, nonce, ciphertext, tag, AssociatedData);
+ return StrictUtf8.GetString(plaintext);
+ }
+ catch (Exception e)
+ {
+ // 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[] Nonce, byte[] Tag, byte[] Ciphertext) ParsePayload(string encrypted)
+ {
+ var fields = encrypted.Split(FieldSeparator);
+ if (fields.Length != 4)
+ {
+ throw new FormatException($"Expected 4 '{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 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, tag, Convert.FromBase64String(fields[3]));
+ }
+
+ string DecryptLegacy(string encrypted)
+ {
+ var (decrypted, errors) = TryEachLegacyKey(legacy =>
+ {
+ 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 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));
+ }
+
+ // 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[] 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(nonce, plaintext, ciphertext, tag, associatedData);
+#endif
+ }
+
+ 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 plaintext = new byte[ciphertext.Length];
+ using var aes = new AesGcm(key, TagSizeInBytes);
+ aes.Decrypt(nonce, ciphertext, tag, 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..c20fe9cbc 100644
--- a/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs
+++ b/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs
@@ -1,49 +1,29 @@
-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()
+ : CreateLinuxEncryptor(Log, fileSystem, keyFilePath, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost);
- static IMachineKeyEncryptor LinuxEncryptor()
+ internal static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, string? keyFilePath, string legacyGeneratedKeyFilePath)
{
- 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(fileSystem, legacyGeneratedKeyFilePath)
};
- return new LinuxMachineKeyEncryptor(log, keySources);
+ return new LinuxMachineKeyEncryptor(log, new ConfigurationEncryptionKey(log, fileSystem, keyFilePath), legacyKeySources);
}
-
- MachineKeyEncryptor()
- {
- }
-
- public string Encrypt(string raw)
- => Current.Encrypt(raw);
-
- public string Decrypt(string encrypted)
- => Current.Decrypt(encrypted);
}
-}
\ No newline at end of file
+}
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 a48df445c..f174fbd15 100644
--- a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs
+++ b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs
@@ -8,80 +8,98 @@ 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
{
- 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 = MachineKeyEncryptor.Current.Decrypt(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)
+
+ 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))
+ {
+ return (false, default!);
+ }
+
+ if (protectionLevel == ProtectionLevel.MachineKey)
{
- var data = Read(name);
- if (data == null)
- return (false, default!);
- valueAsString = data as string;
- if (valueAsString == null || string.IsNullOrWhiteSpace(valueAsString))
- return (false, default!);
+ valueAsString = Decrypt(name, valueAsString);
+ }
- if (protectionLevel == ProtectionLevel.MachineKey)
- data = MachineKeyEncryptor.Current.Decrypt(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)
{
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);
}
}
+ string Decrypt(string name, string value)
+ {
+ try
+ {
+ return Encryptor.Decrypt(value);
+ }
+ catch (Exception e)
+ {
+ throw new ProtectedSettingDecryptionException(name, e);
+ }
+ }
+
public override bool Set(string name, TData value, ProtectionLevel protectionLevel = ProtectionLevel.None)
{
if (name == null) throw new ArgumentNullException(nameof(name));
@@ -100,7 +118,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 +127,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 && !Encryptor.RequiresReEncryption(previous))
+ {
+ 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;
+ }
+
protected virtual bool ValueNeedsToBeSerialized(ProtectionLevel protectionLevel, object valueAsObject)
{
//null would end up as "null" rather than empty
diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceConfiguration.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceConfiguration.cs
index fdbfef4d1..b96508266 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)
{
+ 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/ApplicationInstanceManager.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs
index 3b6d00948..c629a62d0 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;
@@ -42,6 +44,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);
@@ -52,6 +55,29 @@ 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);
+ var key = new ConfigurationEncryptionKey(log, fileSystem, keyFilePath);
+ try
+ {
+ 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 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);
+ }
+ }
+
void RegisterInstanceInIndex(string instanceName, string configurationFile)
{
// If completely dynamic (no instance or configFile provided) then dont bother setting anything
diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs
index 262a68279..51e416cf0 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;
@@ -74,12 +75,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 : ConfigurationEncryptionKey.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)
@@ -92,7 +127,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!, MachineKeyEncryptor.ForKeyFile(fileSystem, keyFilePath));
return (ContributeAdditionalConfiguration(writable), writable);
}
diff --git a/source/Octopus.Tentacle/Configuration/LinuxConfigurationFilePermissions.cs b/source/Octopus.Tentacle/Configuration/LinuxConfigurationFilePermissions.cs
index 77f1efd60..9561b6f23 100644
--- a/source/Octopus.Tentacle/Configuration/LinuxConfigurationFilePermissions.cs
+++ b/source/Octopus.Tentacle/Configuration/LinuxConfigurationFilePermissions.cs
@@ -2,10 +2,9 @@
using System;
using System.Diagnostics;
using System.IO;
-using System.Runtime.InteropServices;
using System.Runtime.Versioning;
-using Microsoft.Win32.SafeHandles;
using Octopus.Tentacle.Core.Diagnostics;
+using Octopus.Tentacle.Core.Util;
namespace Octopus.Tentacle.Configuration
{
@@ -14,7 +13,6 @@ namespace Octopus.Tentacle.Configuration
class LinuxConfigurationFilePermissions : IConfigurationFilePermissions
{
public const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
- const uint UnchangedGroup = uint.MaxValue;
readonly ISystemLog log;
@@ -90,9 +88,8 @@ public void RestrictToServiceUser(string configurationPath, string userName)
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)
{
@@ -122,9 +119,6 @@ public void RestrictToServiceUser(string configurationPath, string userName)
return null;
}
}
-
- [DllImport("libc", SetLastError = true)]
- static extern int fchown(SafeFileHandle fd, uint owner, uint group);
}
}
#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..537ae3a08 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
@@ -12,13 +13,41 @@ public class XmlFileKeyValueStore : XmlKeyValueStore
public XmlFileKeyValueStore(IOctopusFileSystem fileSystem,
string configurationFile,
+ IMachineKeyEncryptor encryptor,
bool autoSaveOnSet = true,
- bool isWriteOnly = false) : base(autoSaveOnSet, isWriteOnly)
+ bool isWriteOnly = false) : base(encryptor, autoSaveOnSet, isWriteOnly)
{
this.fileSystem = 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)
+ {
+ 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..1a4ed75fd 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,6 +140,14 @@ public void WriteAllText(string filePath, string contents)
syncRetryPolicy.Execute(() => inner.WriteAllText(filePath, contents));
}
+#if NET
+ [UnsupportedOSPlatform("windows")]
+#endif
+ public bool TryAtomicCreateFileWithOnlyUserReadWritePermissions(string filePath, byte[] contents)
+ {
+ return syncRetryPolicy.Execute(() => inner.TryAtomicCreateFileWithOnlyUserReadWritePermissions(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..00e65eead 100644
--- a/source/Octopus.Tentacle/Program.cs
+++ b/source/Octopus.Tentacle/Program.cs
@@ -94,6 +94,8 @@ 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");
+ 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();
}
diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs
index 2ee89e673..d43c0753c 100644
--- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs
+++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs
@@ -18,6 +18,7 @@ public class ServiceCommand : AbstractCommand
readonly ServiceConfigurationState serviceConfigurationState;
readonly IServiceConfigurator serviceConfigurator;
readonly IConfigurationFilePermissions configurationFilePermissions;
+ readonly Lazy configurationEncryptionUpgrade;
private readonly ISystemLog log;
readonly string ServicePasswordEnvVar = "OCTOPUS_SERVICE_PASSWORD";
readonly string ServiceUsernameEnvVar = "OCTOPUS_SERVICE_USERNAME";
@@ -32,9 +33,11 @@ public ServiceCommand(ApplicationName applicationName,
IServiceConfigurator serviceConfigurator,
ISystemLog log,
ILogFileOnlyLogger logFileOnlyLogger,
- IConfigurationFilePermissions configurationFilePermissions)
+ IConfigurationFilePermissions configurationFilePermissions,
+ Lazy configurationEncryptionUpgrade)
: base(logFileOnlyLogger)
{
+ this.configurationEncryptionUpgrade = configurationEncryptionUpgrade;
this.applicationName = applicationName;
this.instanceLocator = instanceLocator;
this.instanceSelector = instanceSelector;
@@ -116,6 +119,12 @@ protected override void Start()
configurationFilePermissions.RestrictToServiceUser(configurationPath!, userName!);
}
+ // A non-root service cannot create its key under /var/lib/octopus, so it is created here while running as root.
+ if (serviceConfigurationState.Install || serviceConfigurationState.Reconfigure)
+ {
+ configurationEncryptionUpgrade.Value.TryPrepareKey();
+ }
+
if (currentName == null)
{
if (serviceConfigurationState.Install || serviceConfigurationState.Reconfigure)
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