Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
129 commits
Select commit Hold shift + click to select a range
21f349c
Stop deriving Linux Tentacle's config encryption key from /etc/machin…
LukeButters Nov 16, 2026
d8b0dfc
Clean up the Linux config encryption key change (#1352)
LukeButters Nov 17, 2026
da6126c
Tell the user how to recover when the configuration encryption key is…
LukeButters Nov 18, 2026
ba4b996
Tell the user to keep the machine's name when re-registering after lo…
LukeButters Nov 18, 2026
2b4e1ca
Add replace-certificate to recover a Tentacle whose certificate or ke…
LukeButters Nov 18, 2026
cf74368
Create the configuration encryption key before creating the instance
LukeButters Nov 18, 2026
ac98d5f
Fix the net48 build of the unit tests
LukeButters Nov 18, 2026
7abe373
Don't point users at the test-only keys directory override
LukeButters Nov 18, 2026
5f818a8
Point the legacy decrypt failure at replace-certificate
LukeButters Nov 18, 2026
727f7ff
Make shared key directories traversable under a hardened umask
LukeButters Nov 18, 2026
47c0e6d
Refuse to start when only the configuration file is persisted
LukeButters Nov 18, 2026
d69cd1b
Use the nobody user in the hardened umask test so it runs on Alpine
LukeButters Nov 18, 2026
8b14d76
Create a real user in the hardened umask test, with adduser on Alpine
LukeButters Nov 18, 2026
eeeacfb
Store Linux machine-key values as AES256-GCM$nonce$ciphertext
LukeButters Nov 19, 2026
fa7f5cb
Store tag in its own field: AESGCM-V1$nonce$tag$ciphertext
LukeButters Nov 22, 2026
7a9e934
Keep the configuration encryption key under each instance's data dire…
LukeButters Nov 22, 2026
6793c4c
Test that a lost key leaves migrated values untouched; run upgrade fi…
LukeButters Nov 22, 2026
3e06c12
Pass the test encryptor to the configuration builder's store
LukeButters Nov 23, 2026
8f6b238
Mark the user-only atomic file create as unsupported on Windows
LukeButters Nov 23, 2026
804a0f5
Replace the config encryption shell test with Docker integration tests
LukeButters Nov 23, 2026
ce2e851
Mark UnixFile as unsupported on Windows
LukeButters Nov 23, 2026
b58bba2
Inline paths in the config encryption Docker tests
LukeButters Nov 23, 2026
3ed61fe
Start re-created and refusing Tentacles through the container builder
LukeButters Nov 23, 2026
a2e8ffc
Mark arrange, act and assert in the config encryption Docker tests
LukeButters Nov 23, 2026
36d03cc
Test config encryption separately from container re-creation
LukeButters Nov 23, 2026
fe27a9a
Rename WithRunTentacleEnvironmentVariable to WithEnvironmentVariable
LukeButters Nov 23, 2026
2481066
Make key tests self-contained instead of inheriting fixture setup
LukeButters Nov 23, 2026
d982363
Tell the user to run as root when the configuration encryption key ca…
LukeButters Nov 23, 2026
c12e27d
Revert "Tell the user to run as root when the configuration encryptio…
LukeButters Nov 23, 2026
e5509b7
Pass legacy generated key path in rather than reading env var; inline…
LukeButters Nov 23, 2026
c7a1dbe
Remove create-instance test covered by ApplicationInstanceManagerFixture
LukeButters Nov 23, 2026
ca12d6b
Pass key file contents to CreateEncryptor instead of presence flags
LukeButters Nov 23, 2026
f5d302b
Inline encryptor setup in legacy ciphertext tests
LukeButters Nov 23, 2026
2bb4853
Remove LinuxConfigurationFileSecurityFixture
LukeButters Nov 23, 2026
76759de
Rename LinuxMachineKeyEncryptorFixture to Tests and inline setup
LukeButters Nov 23, 2026
e68809d
Convert fixtures added in this PR to Tests classes without shared setup
LukeButters Nov 23, 2026
104afbd
Test on each distro that a non-root create-instance is told the comma…
LukeButters Nov 23, 2026
eaeabd3
Revert "Test on each distro that a non-root create-instance is told t…
LukeButters Nov 23, 2026
f93926c
Test config encryption key failures through agent start and create-in…
LukeButters Nov 23, 2026
9c1a243
Test create-instance key failure through real instance store; drop in…
LukeButters Nov 23, 2026
8c796d9
Restore Linux key file permission, concurrency and umask tests
LukeButters Nov 23, 2026
47a1bda
Cover create-instance key failure with a single real-executable test
LukeButters Nov 23, 2026
c236169
Delete test we don't need
LukeButters Nov 23, 2026
cf0bef7
Test --config key selection through the installed package instead of …
LukeButters Nov 23, 2026
5e39b51
Remove test-linux-package.sh
LukeButters Nov 23, 2026
f238cdb
Restore registered-instance key selection test
LukeButters Nov 23, 2026
a314dc2
Revert "Remove test-linux-package.sh"
LukeButters Nov 23, 2026
72c862d
Remove test asserting unregistered configurations stay on legacy keys
LukeButters Nov 23, 2026
77a2c4e
Remove in-process upgrade tests now covered by old-to-new Tentacle tests
LukeButters Nov 23, 2026
4b62340
Test upgrading a version 14 configuration from the machine-id key to …
LukeButters Nov 23, 2026
accc06f
Name the version 14 Tentacle helper for what it returns
LukeButters Nov 23, 2026
42d657e
Name the certificate helper for the encrypted value it reads
LukeButters Nov 23, 2026
8b1965a
Name the redirected Tentacle directories for what they are
LukeButters Nov 23, 2026
518f25e
Make the version 14 upgrade tests read as a story
LukeButters Nov 23, 2026
13f4e07
Add a builder for a Tentacle instance that is not running, and use it…
LukeButters Nov 23, 2026
9e489b9
Read the stored certificate from the Tentacle instance
LukeButters Nov 23, 2026
31980e6
Let a Tentacle instance own its Tentacle version and switch to the la…
LukeButters Nov 23, 2026
8501b8c
Build the Tentacle instance with its Tentacle and upgrade it to the l…
LukeButters Nov 23, 2026
3c2d66a
Build the Tentacle instance with its Tentacle and switch to the curre…
LukeButters Nov 23, 2026
598b3ca
Test that an unnamed version 14 instance is told to create a named in…
LukeButters Nov 23, 2026
1132beb
Name the configuration encryption upgrade tests When_And_Then
LukeButters Nov 23, 2026
6c6409e
Move the lost key test to the real executable and drop the mocked upg…
LukeButters Nov 23, 2026
f4486d8
Build running Tentacles from a TentacleInstance, and test the upgrade…
LukeButters Nov 23, 2026
d324aba
Test the upgrade by restarting a running version 14 Tentacle as the c…
LukeButters Nov 23, 2026
f082eec
Rename RestartWithCurrentTentacle to StopAndStartWithCurrentVersionOf…
LukeButters Nov 23, 2026
e194806
Assert encryption key failures are about the missing key
LukeButters Nov 23, 2026
4aab95f
Align the Docker test setup with #1363
LukeButters Nov 23, 2026
b993f0f
Retry Tentacle commands that fail while another test registers an ins…
LukeButters Nov 23, 2026
d860c16
Download each old Tentacle into its own temporary directory
LukeButters Nov 23, 2026
78bc03b
Import certificates into unnamed instances through their configuratio…
LukeButters Nov 23, 2026
ed8ba4b
Reject running a caller-built instance as a service
LukeButters Nov 23, 2026
e0946ce
Keep the name and certificate a caller chose when running an instance
LukeButters Nov 23, 2026
88c7f07
Pass cancellation tokens to Tentacle instance commands instead of sto…
LukeButters Nov 23, 2026
34268d3
Keep one multi-block unicode legacy ciphertext case per key
LukeButters Nov 23, 2026
651f473
Test that Tentacle still starts on legacy keys when the new key canno…
LukeButters Nov 23, 2026
3764b2f
Drop show-thumbprint checks from the package test; dotnet tests cover…
LukeButters Nov 23, 2026
e85a52e
Say why the package test exercises the configuration encryption key
LukeButters Nov 23, 2026
cda8340
Run a script on the Tentacle that started on legacy keys
LukeButters Nov 23, 2026
4ee0107
Use TemporaryDirectory in the non-root create-instance test
LukeButters Nov 23, 2026
0d71712
Remove re-encryption typed-read test; re-encryption only moves strings
LukeButters Nov 23, 2026
9a17bcf
Merge origin/main
LukeButters Nov 23, 2026
2871f8c
Move FakeOctopusServer to Tests.Integration.Common and test replace-c…
LukeButters Nov 23, 2026
b5fac5f
Merge remote-tracking branch 'origin/main' into luke/lev-1171-config-…
LukeButters Nov 23, 2026
2bde0c8
Name the replace-certificate test after the Linux encryption upgrade …
LukeButters Nov 24, 2026
bc5b0e6
Inline the single legacy ciphertext case in each test
LukeButters Nov 24, 2026
84def5b
Replace the key file fixture with self-contained tests
LukeButters Nov 24, 2026
42a1a86
Use LinuxOrMacTest rather than an inline platform check
LukeButters Nov 24, 2026
4dc4d54
Write instance index files atomically so concurrent listings never re…
LukeButters Nov 24, 2026
65fecf9
Revert "Write instance index files atomically so concurrent listings …
LukeButters Nov 24, 2026
e139953
Decrypt protected settings outside the parse catch so their recovery …
LukeButters Nov 24, 2026
1bc0bfd
Shorten the hierarchical store's encryption guard comment
LukeButters Nov 24, 2026
bd84f3e
Say the hierarchical store is only for display
LukeButters Nov 24, 2026
6e57e5d
Drop the unused encryption guard from the display-only configuration …
LukeButters Nov 24, 2026
247cd31
Skip encrypted values in show-configuration output
LukeButters Nov 24, 2026
aa20e5f
Merge remote-tracking branch 'origin/main' into luke/lev-1171-config-…
LukeButters Nov 24, 2026
eb5f992
Rename TentacleConfigurationUpgrade to ConfigurationEncryptionUpgrade
LukeButters Nov 24, 2026
564a175
Mark the Linux unit test Docker script as local only
LukeButters Nov 24, 2026
ab5d1c6
Move the local-only Linux unit test script into testing/local
LukeButters Nov 24, 2026
3dc4590
Move the local Linux unit test script to its own PR
LukeButters Nov 24, 2026
a44008e
Rename configurationUpgrade to configurationEncryptionUpgrade
LukeButters Nov 24, 2026
90bb003
Explain why calling the runtime's stat shim is safe
LukeButters Nov 24, 2026
8a05a4d
Note the test that guards the stat shim layout
LukeButters Nov 24, 2026
eb1f0da
Stop telling users to regenerate the legacy machine key
LukeButters Nov 24, 2026
cf582a9
Explain why the upgrade loads the key first
LukeButters Nov 24, 2026
1230ad2
Merge remote-tracking branch 'origin/main' into luke/lev-1171-config-…
LukeButters Nov 24, 2026
c9539be
Throw ControlledFailureException when the configuration key is missin…
LukeButters Nov 24, 2026
54c796b
Make keyFilePath a required ApplicationInstanceConfiguration parameter
LukeButters Nov 24, 2026
0f60588
Fix stale comment wording and add missing braces
LukeButters Nov 24, 2026
d6a31c9
+semver: major
LukeButters Nov 24, 2026
68948fe
Report an unreadable key directory instead of treating the key as mis…
LukeButters Nov 24, 2026
d6cac4d
Test an unreadable key by running Tentacle as another user, and clean…
LukeButters Nov 24, 2026
290283e
Create the configuration encryption key without hard links on filesys…
LukeButters Nov 25, 2026
16d2564
Report configuration encryption key failures as themselves rather tha…
LukeButters Nov 25, 2026
816a763
Add reset-configuration-encryption to recover from a lost key, and st…
LukeButters Nov 25, 2026
3217c5a
Move the configuration encryption key into place with File.Move inste…
LukeButters Nov 25, 2026
4c1332d
Test recovering a Tentacle from a lost key end to end, through to run…
LukeButters Nov 25, 2026
956310a
.
LukeButters Nov 25, 2026
79c6dc1
.
LukeButters Nov 25, 2026
b683c34
Delete the unused LegacySchemeEncryptor test helper
LukeButters Nov 26, 2026
e820790
Delete the concurrent key creation test; each instance has its own key
LukeButters Nov 26, 2026
0ea3061
Test a hardened umask by running the real Tentacle as root, rather th…
LukeButters Nov 26, 2026
458d333
Add known-answer test for AESGCM-V1 format
LukeButters Nov 26, 2026
8cfd0a9
Make the suggested key directory fix work under a hardened umask
LukeButters Nov 26, 2026
abae66c
Revert "Make the suggested key directory fix work under a hardened um…
LukeButters Nov 26, 2026
e2fbe91
Merge remote-tracking branch 'origin/main' into luke/lev-1171-config-…
LukeButters Nov 26, 2026
0ab33cc
Test that installing the service for another user leaves the key read…
LukeButters Nov 26, 2026
76f4d13
Run the service install test as plain root rather than with a umask
LukeButters Nov 26, 2026
7c31c0e
Run Linux integration tests with systemd in the local Docker helper
LukeButters Nov 26, 2026
00cf7c0
.
LukeButters Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docker/linux/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions docker/linux/scripts/configure-and-run.sh
Original file line number Diff line number Diff line change
@@ -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
Expand Down
11 changes: 11 additions & 0 deletions docker/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
38 changes: 38 additions & 0 deletions linux-packages/test-scripts/test-linux-package.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 ""
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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
{
Expand All @@ -112,15 +118,15 @@ 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)
{
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);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -36,6 +37,19 @@ public interface IOctopusFileSystem

void WriteAllBytes(string filePath, byte[] data);
void WriteAllText(string filePath, string contents);

/// <summary>
/// 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 <see cref="PlatformNotSupportedException"/> on Windows.
/// </summary>
/// <returns>True if this call created the file, false if it already existed, in which case the existing file is left untouched.</returns>
#if NET
[UnsupportedOSPlatform("windows")]
#endif
bool TryAtomicCreateFileWithOnlyUserReadWritePermissions(string filePath, byte[] contents);

string ReadAllText(string scriptFile);
string[] ReadAllLines(string scriptFile);
}
Expand Down
60 changes: 60 additions & 0 deletions source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)
{
Expand Down Expand Up @@ -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);

@gb-8 gb-8 Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this change?

This looks like a regression. Were the test failures this was causing not a scenario we care about?

File.Move is not guaranteed to be atomic.
Maybe it is in the cases where we use it in this PR, but this is a more general class, so it could cause confusion.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the added code complexity is worth it for the edge case of race conditions specific to Linux-only tentacles that are running on a non-hard-linking FS.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method name says TryAtomic..... It should be renamed if it is not doing it atomically.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am going to leave it as atomic since its what we want and practically speaking its atomic.

It's not atomic when we have fat/exfat (who is running that?), or samba e.g. for azure shares. Azure shares provide no guarantee for atomic operations of complete files, even if we went back to the complex code we had before.

  • I don't want to remove atomic from the name because it wants to be atomic.
  • it is as atomic as it can be for the file system it runs on.

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))
Expand Down
4 changes: 4 additions & 0 deletions source/Octopus.Tentacle.Core/Util/PlatformDetection.cs
Original file line number Diff line number Diff line change
@@ -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);
}
Expand Down
80 changes: 80 additions & 0 deletions source/Octopus.Tentacle.Core/Util/UnixFile.cs
Original file line number Diff line number Diff line change
@@ -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
Loading