Files
Chronos/tests/Chronos.Server.Tests/Hosting/DataFolderAccessTests.cs
T
Alby96andClaude Opus 5.5 5f27a86406
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s
refactor!: rename Titano to Chronos and move CI and releases to Gitea
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout. The release cross-compiles the Windows programs, checks their
  icon, version and DPI manifest, packs installers and zips, publishes the
  Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only
  tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow) and
  pe-check.

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 11:34:48 +02:00

285 lines
13 KiB
C#

using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Principal;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
/// <summary>
/// The data folder and its secrets are private (BRIEF §14.2): mode 0600 off Windows; on Windows a protected ACL that no
/// ordinary user appears in, where %ProgramData% would otherwise let every local user read the folder, with owners the
/// server trusts and no links. On Windows a new archive folder lets other users only read it.
/// </summary>
[Category("server")]
public sealed class DataFolderAccessTests(TestContext context)
{
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
[Test]
public async Task TheTlsKeyAndTheFirstAdminPasswordAreReadableOnlyByTheServer()
{
await using var server = await TestServer.StartAsync(context, o => o.AdminPassword = null);
foreach (var file in new[] { Path.Combine(server.Options.TlsPath, "server.pfx"), Path.Combine(server.Options.DataPath, "initial-admin-password.txt") })
{
Assert.FileExists(file);
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new FileInfo(file).GetAccessControl()), file);
else Assert.Equal(OwnerOnly, File.GetUnixFileMode(file));
}
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(server.Options.DataPath).GetAccessControl()));
}
[Test]
public void ARewrittenSecretLosesTheAccessItHad()
{
var file = Path.Combine(context.CreateTempDirectory("secret"), "server.pfx");
File.WriteAllBytes(file, [1]);
if (OperatingSystem.IsWindows()) GrantUsersRead(new FileInfo(file));
else File.SetUnixFileMode(file, OwnerOnly | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
DataFolderAccess.WritePrivateFile(file, [1, 2, 3]);
Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(file));
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new FileInfo(file).GetAccessControl()));
else Assert.Equal(OwnerOnly, File.GetUnixFileMode(file));
}
[Test]
[WindowsOnly]
public void AFolderEveryUserCouldReadBecomesPrivateWithItsFiles()
{
if (!OperatingSystem.IsWindows()) return;
var folder = new DirectoryInfo(context.CreateTempDirectory("programdata"));
// What %ProgramData% hands down to a new folder: every local user may read it and create files in it.
var open = folder.GetAccessControl();
open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.ReadAndExecute | FileSystemRights.CreateFiles,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
folder.SetAccessControl(open);
var database = new FileInfo(Path.Combine(folder.FullName, "chronos.db"));
File.WriteAllText(database.FullName, "rows");
Assert.True(NamesUsers(database.GetAccessControl()), "the file inherited the users' entry");
DataFolderAccess.Restrict(folder.FullName);
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
Assert.False(NamesUsers(folder.GetAccessControl()));
Assert.False(NamesUsers(database.GetAccessControl()), "the file still lets every user read it");
Assert.Equal("rows", File.ReadAllText(database.FullName));
// Once private, a later start leaves it as it is.
DataFolderAccess.Restrict(folder.FullName);
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
}
[Test]
[WindowsOnly]
public void ANewDataFolderIsCreatedPrivate()
{
if (!OperatingSystem.IsWindows()) return;
var folder = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("new"), "Chronos Server"));
DataFolderAccess.Restrict(folder.FullName);
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
var settings = new FileInfo(Path.Combine(folder.FullName, "server.json"));
File.WriteAllText(settings.FullName, "{}");
Assert.False(NamesUsers(settings.GetAccessControl()));
}
[Test]
[WindowsOnly]
public void ASecretAnotherAccountOwnedIsReplacedByOneTheServerOwns()
{
if (!OperatingSystem.IsWindows()) return;
var folder = context.CreateTempDirectory("planted");
var own = OwnerOf(NewFile(Path.Combine(folder, "probe.txt")));
// Planted before the first start: whoever owns it keeps the right to change its ACL, whatever the server sets.
var secret = NewFile(Path.Combine(folder, "initial-admin-password.txt"));
if (!TrySetOwner(secret, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
GrantUsersRead(secret);
DataFolderAccess.WritePrivateFile(secret.FullName, [1, 2, 3]);
secret.Refresh();
Assert.Equal(own, OwnerOf(secret));
Assert.True(DataFolderAccess.IsPrivate(secret.GetAccessControl()));
Assert.False(NamesUsers(secret.GetAccessControl()));
Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(secret.FullName));
}
[Test]
[WindowsOnly]
public void AnythingAnotherAccountOwnsIsFound()
{
if (!OperatingSystem.IsWindows()) return;
var folder = new DirectoryInfo(context.CreateTempDirectory("squatted"));
var key = NewFile(Path.Combine(folder.CreateSubdirectory("tls").FullName, "server.pfx"));
var own = OwnerOf(key);
Assert.Null(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own }));
// A folder someone else created before the first start is reported before anything inside it.
Assert.Contains(folder.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { LocalSystem })));
if (!TrySetOwner(key, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
Assert.Contains(key.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own })));
}
[Test]
[WindowsOnly]
public void ALinkInTheDataFolderStopsTheServerBeforeTheAclChanges()
{
if (!OperatingSystem.IsWindows()) return;
var folder = new DirectoryInfo(context.CreateTempDirectory("linked"));
var link = Path.Combine(folder.FullName, "logs");
try
{
Directory.CreateSymbolicLink(link, context.CreateTempDirectory("elsewhere"));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Assert.Inconclusive("creating a symbolic link needs an elevated administrator or developer mode");
}
var refused = Assert.Throws<InvalidOperationException>(() => DataFolderAccess.Restrict(folder.FullName));
Assert.Contains(link, refused.Message);
// The ACL change would have followed the link; it never started.
Assert.False(folder.GetAccessControl().AreAccessRulesProtected);
}
[Test]
[WindowsOnly]
public void SettingsAnotherAccountOwnsAreNotRead()
{
if (!OperatingSystem.IsWindows()) return;
var settings = NewFile(Path.Combine(context.CreateTempDirectory("settings"), "server.json"), """{ "ArchivePath": "D:\\Elsewhere" }""");
Assert.Contains("Elsewhere", DataFolderAccess.ReadTrustedText(settings.FullName));
// As if another account had planted it: the owner is not among those the server trusts.
InvalidOperationException? refused = null;
try
{
DataFolderAccess.ReadTrustedText(settings.FullName, new HashSet<SecurityIdentifier> { LocalSystem });
}
catch (InvalidOperationException ex)
{
refused = ex;
}
Assert.Contains(settings.FullName, Assert.NotNull(refused).Message);
}
[Test]
public void AMissingArchiveFolderIsCreated()
{
var root = Path.Combine(context.CreateTempDirectory("archive"), "ChronosArchive");
Assert.False(DataFolderAccess.PrepareArchive(root));
Assert.True(Directory.Exists(root));
// An existing folder is left as it is.
Assert.False(DataFolderAccess.PrepareArchive(root));
}
[Test]
[WindowsOnly]
public void ANewArchiveIsReadableByUsersButOnlyTheServerChangesIt()
{
if (!OperatingSystem.IsWindows()) return;
// Under C:\ a new folder would inherit "Authenticated Users: modify" and every local user could plant links
// where the service moves uploads.
var root = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("archive"), "ChronosArchive"));
Assert.False(DataFolderAccess.PrepareArchive(root.FullName));
var security = root.GetAccessControl();
Assert.True(security.AreAccessRulesProtected);
Assert.Equal(FileSystemRights.ReadAndExecute, RightsOf(security, Users) & FileSystemRights.ReadAndExecute);
Assert.Equal((FileSystemRights)0, RightsOf(security, Users) & (FileSystemRights.Write | FileSystemRights.Delete | FileSystemRights.ChangePermissions));
// Staging and trash are the server's alone.
var meta = new DirectoryInfo(Path.Combine(root.FullName, ".chronos"));
Assert.True(DataFolderAccess.IsPrivate(meta.GetAccessControl()));
Assert.False(NamesUsers(meta.CreateSubdirectory("staging").GetAccessControl()));
}
[Test]
[WindowsOnly]
public void AnArchiveOtherUsersCanChangeIsReportedButLeftAsItIs()
{
if (!OperatingSystem.IsWindows()) return;
var root = new DirectoryInfo(context.CreateTempDirectory("shared"));
DataFolderAccess.PrepareArchive(root.FullName);
var open = root.GetAccessControl();
open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Modify,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
root.SetAccessControl(open);
Assert.True(DataFolderAccess.PrepareArchive(root.FullName));
Assert.Equal(FileSystemRights.Modify, RightsOf(root.GetAccessControl(), Users) & FileSystemRights.Modify);
// The .chronos folder the server added at the first start stays its own.
Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(Path.Combine(root.FullName, ".chronos")).GetAccessControl()));
}
[SupportedOSPlatform("windows")]
private static SecurityIdentifier Users => new(WellKnownSidType.BuiltinUsersSid, null);
[SupportedOSPlatform("windows")]
private static SecurityIdentifier LocalSystem => new(WellKnownSidType.LocalSystemSid, null);
[SupportedOSPlatform("windows")]
private static SecurityIdentifier Administrators => new(WellKnownSidType.BuiltinAdministratorsSid, null);
private static FileInfo NewFile(string path, string contents = "x")
{
File.WriteAllText(path, contents);
return new FileInfo(path);
}
[SupportedOSPlatform("windows")]
private static SecurityIdentifier OwnerOf(FileInfo file) => (SecurityIdentifier)file.GetAccessControl().GetOwner(typeof(SecurityIdentifier))!;
/// <summary>An owner this process may give a file that its new files do not get: its own account or Administrators.</summary>
[SupportedOSPlatform("windows")]
private static SecurityIdentifier OtherOwner(SecurityIdentifier own)
{
using var identity = WindowsIdentity.GetCurrent();
return own == Administrators ? identity.User! : Administrators;
}
[SupportedOSPlatform("windows")]
private static bool TrySetOwner(FileInfo file, SecurityIdentifier owner)
{
var security = new FileSecurity();
security.SetOwner(owner);
try
{
file.SetAccessControl(security);
return true;
}
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException)
{
return false;
}
}
/// <summary>The rights allow entries give <paramref name="account"/>.</summary>
[SupportedOSPlatform("windows")]
private static FileSystemRights RightsOf(FileSystemSecurity security, SecurityIdentifier account)
{
FileSystemRights rights = 0;
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
if (rule.AccessControlType == AccessControlType.Allow && rule.IdentityReference.Equals(account)) rights |= rule.FileSystemRights;
}
return rights;
}
/// <summary>True when Users, Authenticated Users or Everyone have any allow entry.</summary>
[SupportedOSPlatform("windows")]
private static bool NamesUsers(FileSystemSecurity security)
{
SecurityIdentifier[] ordinary = [Users, new(WellKnownSidType.AuthenticatedUserSid, null), new(WellKnownSidType.WorldSid, null)];
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
if (rule.AccessControlType == AccessControlType.Allow && ordinary.Contains((SecurityIdentifier)rule.IdentityReference)) return true;
}
return false;
}
[SupportedOSPlatform("windows")]
private static void GrantUsersRead(FileInfo file)
{
var security = file.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Read, AccessControlType.Allow));
file.SetAccessControl(security);
}
}