Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
113 changes: 113 additions & 0 deletions AppDataStorage.Test/UnixFileModeTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// Copyright (c) 2023-2026 ktsu-dev contributors

namespace ktsu.AppDataStorage.Test;

using System.IO.Abstractions;
using System.Runtime.Versioning;

using ktsu.Semantics.Paths;

/// <summary>
/// A save replaces the settings file with a newly written one, so on Unix it must carry the settings
/// file's permissions across: a file restricted to 0600 because it holds a token must not come back
/// 0644 (ktsu-dev/AppDataStorage#380). These run against the real file system, since permissions are
/// what the OS does with them.
/// </summary>
[TestClass]
[OSCondition(OperatingSystems.Linux | OperatingSystems.OSX)]
[SupportedOSPlatform("linux")]
[SupportedOSPlatform("macos")]
public sealed class UnixFileModeTests
{
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;

private string directory = string.Empty;

public sealed class TokenSettings : AppData<TokenSettings>
{
public string Token { get; set; } = string.Empty;
}

[TestInitialize]
public void SetupTest()
{
directory = Path.Combine(Path.GetTempPath(), $"appdatastorage_mode_{Guid.NewGuid():N}");
Directory.CreateDirectory(directory);
AppData.UseFileSystemOnThisThread(new FileSystem());
}

[TestCleanup]
public void CleanupTest()
{
AppData.ClearCachedFileSystem();
Directory.Delete(directory, recursive: true);
}

private AbsoluteDirectoryPath Root => AbsoluteDirectoryPath.Create(directory);

[TestMethod]
[DataRow(OwnerOnly)]
[DataRow(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead)]
[DataRow(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.OtherRead | UnixFileMode.OtherWrite)]
public void SaveKeepsTheSettingsFilePermissions(UnixFileMode mode)
{
using TokenSettings settings = TokenSettings.LoadOrCreateIn(Root);
string filePath = settings.FilePath.ToString();
File.SetUnixFileMode(filePath, mode);

settings.Token = "s3cr3t";
settings.Save();

Assert.AreEqual(mode, File.GetUnixFileMode(filePath), "A save must keep the settings file's permissions.");
using TokenSettings reloaded = TokenSettings.LoadOrCreateIn(Root);
Assert.AreEqual("s3cr3t", reloaded.Token, "The save must still have written the new content.");
}

[TestMethod]
public void SavingTwiceKeepsOwnerOnly()
{
using TokenSettings settings = TokenSettings.LoadOrCreateIn(Root);
string filePath = settings.FilePath.ToString();
File.SetUnixFileMode(filePath, OwnerOnly);

settings.Token = "one";
settings.Save();
settings.Token = "two";
settings.Save();

Assert.AreEqual(OwnerOnly, File.GetUnixFileMode(filePath));
}

[TestMethod]
public void AReaderHoldingAStaleTempFileNeverSeesTheNewContent()
{
using TokenSettings settings = TokenSettings.LoadOrCreateIn(Root);
string filePath = settings.FilePath.ToString();
File.SetUnixFileMode(filePath, OwnerOnly);

// A .tmp left by an interrupted save, world-readable, which another account has already opened.
string tempPath = filePath + ".tmp";
File.WriteAllText(tempPath, string.Empty);
File.SetUnixFileMode(tempPath, OwnerOnly | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
using FileStream reader = new(tempPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);

settings.Token = "s3cr3t";
settings.Save();

using StreamReader text = new(reader);
Assert.DoesNotContain("s3cr3t", text.ReadToEnd(), "The save must write to a newly created file, not through a descriptor someone else already holds.");
Assert.AreEqual(OwnerOnly, File.GetUnixFileMode(filePath));
}

[TestMethod]
public void ANewSettingsFileKeepsTheDefaultMode()
{
string probe = Path.Combine(directory, "probe");
File.WriteAllText(probe, string.Empty);
UnixFileMode defaultMode = File.GetUnixFileMode(probe);

using TokenSettings settings = TokenSettings.LoadOrCreateIn(Root);

Assert.AreEqual(defaultMode, File.GetUnixFileMode(settings.FilePath.ToString()), "A new file is created as before, with the process's default mode.");
}
}
80 changes: 77 additions & 3 deletions AppDataStorage/AppData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@
EnsureDirectoryExists(appData.FilePath);
AbsoluteFilePath tempFilePath = MakeTempFilePath(appData.FilePath);
AbsoluteFilePath bkFilePath = MakeBackupFilePath(appData.FilePath);
WriteDurably(tempFilePath, text);
WriteDurably(tempFilePath, text, modeSource: appData.FilePath);

// With no main file, a backup is not a copy of anything about to be replaced: it is left over
// from an interrupted write, and may be the only copy of the user's last good data. Deleting
Expand Down Expand Up @@ -326,9 +326,14 @@
/// </remarks>
/// <param name="filePath">The file to write.</param>
/// <param name="text">The text to write.</param>
private static void WriteDurably(AbsoluteFilePath filePath, string text)
/// <param name="modeSource">The file whose Unix permissions <paramref name="filePath"/> takes, if it exists.</param>
private static void WriteDurably(AbsoluteFilePath filePath, string text, AbsoluteFilePath modeSource)
{
using FileSystemStream stream = FileSystem.FileStream.New(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
using FileSystemStream stream = CreateForWriting(filePath, modeSource);

// The umask can only narrow the create mode, so the exact mode is set once the file exists. This never
// makes it wider than the settings file, and the disposal above covers a failure here.
CopyUnixFileMode(modeSource, filePath);
using (StreamWriter writer = new(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), bufferSize: 4096, leaveOpen: true))
{
writer.Write(text);
Expand All @@ -337,6 +342,75 @@
stream.Flush(flushToDisk: true);
}

/// <summary>
/// Creates <paramref name="filePath"/> for writing, with the Unix permissions of
/// <paramref name="modeSource"/> from the moment it exists, when <paramref name="modeSource"/> exists and
/// the platform has them.
/// </summary>
/// <remarks>
/// A save writes a new file and renames it over the settings file, so the settings file would otherwise
/// take the new file's default mode (0666 less the umask, usually 0644). A file the user restricted to
/// 0600 because it holds a token would become readable by every account after the next save
/// (ktsu-dev/AppDataStorage#380).
/// <para>
/// The mode is given at creation, not applied afterwards: Unix checks permissions when a file is opened,
/// so another account that opened a more permissive file in the meantime could read everything later
/// written through it. For the same reason a stale <c>.tmp</c> from an interrupted save is deleted rather
/// than truncated, and the new one is created with <see cref="FileMode.CreateNew"/>, so a file someone
/// else put there in between is refused rather than written to.
/// </para>
/// <para>
/// Windows needs nothing here: <c>File.Replace</c> keeps the replaced file's attributes and ACLs. The file
/// system abstraction has the Unix mode APIs from .NET 8 on, so the .NET 7 and netstandard builds keep
/// the default mode.
/// </para>
/// </remarks>
/// <param name="filePath">The file to create.</param>
/// <param name="modeSource">The file whose permissions <paramref name="filePath"/> takes.</param>
/// <returns>A stream that writes to the new file.</returns>
private static FileSystemStream CreateForWriting(AbsoluteFilePath filePath, AbsoluteFilePath modeSource)
{
#if NET8_0_OR_GREATER
if (!OperatingSystem.IsWindows() && FileSystem.File.Exists(modeSource))
{
UnixFileMode mode = FileSystem.File.GetUnixFileMode(modeSource);
FileSystem.File.Delete(filePath);
return FileSystem.FileStream.New(filePath, new FileStreamOptions
{
Mode = FileMode.CreateNew,
Access = FileAccess.Write,
Share = FileShare.None,
UnixCreateMode = mode,
});
}
#else
_ = modeSource;
#endif

return FileSystem.FileStream.New(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
}

/// <summary>
/// Gives <paramref name="destination"/> exactly the Unix permissions of <paramref name="source"/>, when
/// <paramref name="source"/> exists and the platform has them.
/// </summary>
/// <param name="source">The file whose permissions are copied.</param>
/// <param name="destination">The file that receives them.</param>
private static void CopyUnixFileMode(AbsoluteFilePath source, AbsoluteFilePath destination)
{
#if NET8_0_OR_GREATER
if (OperatingSystem.IsWindows() || !FileSystem.File.Exists(source))
{
return;
}

FileSystem.File.SetUnixFileMode(destination, FileSystem.File.GetUnixFileMode(source));
#else
_ = source;
_ = destination;
#endif
}

/// <summary>
/// Reads the text content from the app data file.
/// </summary>
Expand Down Expand Up @@ -688,10 +762,10 @@
/// </summary>
#if NET9_0_OR_GREATER
[JsonIgnore]
public static Lock Lock { get; } = new();

Check warning on line 765 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 765 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 765 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 765 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.
#else
[JsonIgnore]
public static object Lock { get; } = new();

Check warning on line 768 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 768 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 768 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 768 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 768 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.

Check warning on line 768 in AppDataStorage/AppData.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

A static field in a generic type is not shared among instances of different close constructed types.
#endif

internal bool IsSaveQueued()
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ copy.Save();
- Debounced saves via `QueueSave()` / `SaveIfRequired()` (3-second debounce, timed with `Stopwatch.GetTimestamp()` so a wall-clock step back cannot hold a save back)
- Whether a save is outstanding is the `HasQueuedSave` flag, set by `QueueSave()` and cleared by a successful `Save()`. It is not `SaveQueuedTime > LastSaveTime`: `DateTime.UtcNow` advances in whole microseconds on macOS, so a queue straight after a save can read the same instant and would be dropped
- Automatic backup files (`.bk` suffix) with timestamped collision handling
- Safe write pattern: write `.tmp` and flush it to disk, then `File.Replace` it over the final file (keeping `.bk` until done), or move it into place when there is no final file yet
- Safe write pattern: write `.tmp` and flush it to disk, then `File.Replace` it over the final file (keeping `.bk` until done), or move it into place when there is no final file yet. On Unix (.NET 8+ builds) a stale `.tmp` is deleted and the new one is created (`CreateNew`) with the existing file's permissions as its `UnixCreateMode`, then set to exactly that mode (which only undoes the umask), so a 0600 file stays 0600 and no other account can open the `.tmp` while it is wider (ktsu-dev/AppDataStorage#380)
- Each settings file belongs to the first `AppData<T>` type that loads or saves it, per file system. A different type that resolves to the same path (two `Settings` classes in different namespaces, or `Gen<int>` and `Gen<string>`) throws `InvalidOperationException` naming both, instead of silently sharing the file (ktsu-dev/AppDataStorage#336)
- Lazy singleton access via `Get()` backed by `Lazy<T>`
- `LoadOrCreate()` reads the file into a new instance on every call and never returns the `Get()` singleton, so the two do not see each other's edits. The static `QueueSave()` / `SaveIfRequired()` act on `Get()` only
Expand Down
Loading