diff options
| author | JP Dillingham <jp@dillingham.me> | 2024-05-26 20:59:00 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-05-26 20:59:00 -0500 |
| commit | e2e8fb86f74fdbd1c39820a7ac3adc91d4a5c2a8 (patch) | |
| tree | a6d1ec0e9c8bcef57951924073a905329392ebdd | |
| parent | ff841bc6411be74e99b0b71754d23614a59c7187 (diff) | |
| parent | f7fefd065aec5ba3a9b4e679e36a5997924ec591 (diff) | |
| download | slskd-e2e8fb86f74fdbd1c39820a7ac3adc91d4a5c2a8.tar.gz | |
Merge pull request #1128 from slskd/file-perms
Add the ability to configure Unix file permissions to be applied to newly downloaded files
| -rw-r--r-- | Dockerfile | 6 | ||||
| -rw-r--r-- | config/slskd.example.yml | 3 | ||||
| -rw-r--r-- | docs/config.md | 24 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 57 | ||||
| -rw-r--r-- | src/slskd/Files/FileExtensions.cs | 62 | ||||
| -rw-r--r-- | src/slskd/Files/FileService.cs | 143 | ||||
| -rw-r--r-- | src/slskd/Files/Types/CreateFileOptions.cs | 31 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 71 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs | 71 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Files/FileServiceTests.cs | 14 |
11 files changed, 420 insertions, 64 deletions
@@ -63,6 +63,7 @@ ENV DOTNET_BUNDLE_EXTRACT_BASE_DIR=/.net \ DOTNET_gcConcurrent=1 \ DOTNET_GCHeapHardLimit=1F400000 \ DOTNET_GCConserveMemory=9 \ + SLSKD_UMASK=0022 \ SLSKD_HTTP_PORT=5030 \ SLSKD_HTTPS_PORT=5031 \ SLSKD_SLSK_LISTEN_PORT=50300 \ @@ -87,4 +88,7 @@ LABEL org.opencontainers.image.title=slskd \ WORKDIR /slskd COPY --from=publish /slskd/dist/${TARGETPLATFORM} . -ENTRYPOINT ["/usr/bin/tini", "--", "./slskd"] +RUN echo "umask \$SLSKD_UMASK && ./slskd" > start.sh \ + && chmod +x start.sh + +ENTRYPOINT ["/usr/bin/tini", "--", "./start.sh"] diff --git a/config/slskd.example.yml b/config/slskd.example.yml index f4839e6d..f1e1b4ab 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -32,6 +32,9 @@ # instance_name: my_agent # make sure the top-level instance_name of the agent matches! # secret: <a 16-255 character string unique to this agent> # cidr: 0.0.0.0/0,::/0 +# permissions: +# file: +# mode: ~ # not for Windows, chmod syntax, e.g. 644, 777. can't escalate beyond umask # directories: # incomplete: ~ # downloads: ~ diff --git a/docs/config.md b/docs/config.md index f81fe8c0..5c4eb2bb 100644 --- a/docs/config.md +++ b/docs/config.md @@ -73,6 +73,30 @@ If an attacker were to gain access to the application and retrieve the YAML file remote_configuration: false ``` +# Permissions + +On [Unix-like](https://en.wikipedia.org/wiki/Unix-like) operating systems, slskd creates downloaded files with permissions dictated by the [umask](https://en.wikipedia.org/wiki/Umask) of the process, usually 022, which translates to a file mode of 644; read/write for the owner and read for the group and all others. + +Users wishing to create files with different permissions can change the umask value before launching the application (e.g. `umask 000 & ./slskd`), and the file mode will be changed accordingly. + +When running within a docker container the environment variable `SLSKD_UMASK` can be used to change the umask for the process within the container, and this will in turn change the resulting file mode on a mounted volume. + +Users can optionally configure alternative permissions for files by setting the file permission mode option. It's not possible to supersede the configured umask value; setting a mode of 777, for example, will have no effect with a umask of 022. + +These options have no effect on Windows. + +| Command-Line | Environment Variable | Description | +| ------------------------ | -----------------------------| -------------------------------------------------------------------------------- | +| n/a | `SLSKD_UMASK` | When running within the slskd Docker container, the umask for the process | +| `--file-permission-mode` | `SLSKD_FILE_PERMISSION_MODE` | The permissions to apply to newly created files (chmod syntax, non-Windows only) | + +#### **YAML** +```yaml +permissions: + file: + mode: 644 # not for Windows, chmod syntax, e.g. 644, 777. can't escalate beyond umask +``` + # Application Directory Configuration The application directory configuration option determines the location of the YAML file, the default locations of the download and incomplete directories, and the location of application working data, such as logs and SQLite databases. diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 81dc09f6..f2419c83 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -210,6 +210,12 @@ namespace slskd public RelayOptions Relay { get; init; } = new RelayOptions(); /// <summary> + /// Gets permission options. + /// </summary> + [Validate] + public PermissionsOptions Permissions { get; init; } = new PermissionsOptions(); + + /// <summary> /// Gets directory options. /// </summary> [Validate] @@ -603,6 +609,57 @@ namespace slskd } /// <summary> + /// Permission options. + /// </summary> + public class PermissionsOptions + { + /// <summary> + /// Gets file permission options. + /// </summary> + [Validate] + public FileOptions File { get; init; } = new FileOptions(); + + /// <summary> + /// File permission options. + /// </summary> + public class FileOptions : IValidatableObject + { + /// <summary> + /// Gets the permissions to apply to newly created files. + /// </summary> + /// <remarks> + /// Applicable to non-Windows operating systems, only. + /// </remarks> + [Argument(default, "file-permission-mode")] + [EnvironmentVariable("FILE_PERMISSION_MODE")] + [Description("the permissions to apply to newly created files (chmod syntax, non-Windows only)")] + public string Mode { get; init; } + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (!string.IsNullOrEmpty(Mode)) + { + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + + if (!regEx.IsMatch(Mode)) + { + results.Add(new ValidationResult($"Field {nameof(Mode)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); + } + } + + return results; + } + } + } + + /// <summary> /// Directory options. /// </summary> public class DirectoriesOptions diff --git a/src/slskd/Files/FileExtensions.cs b/src/slskd/Files/FileExtensions.cs new file mode 100644 index 00000000..4aa7a648 --- /dev/null +++ b/src/slskd/Files/FileExtensions.cs @@ -0,0 +1,62 @@ +// <copyright file="FileExtensions.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Files; + +using System; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; + +/// <summary> +/// Extension methods related to <see cref="Files"/>. +/// </summary> +public static class FileExtensions +{ + /// <summary> + /// Converts the specified <paramref name="permissions"/> string into an instance of <see cref="UnixFileMode"/>. + /// </summary> + /// <param name="permissions">A 3 or 4 character string consisting of only 0-7, matching a Unix file permission (e.g. one used with 'chmod').</param> + /// <returns>The converted UnixFileMode.</returns> + /// <exception cref="ArgumentException">Thrown if the specified <paramref name="permissions"/> string is null or consists of only whitespace.</exception> + /// <exception cref="ArgumentOutOfRangeException">Thrown if the specified <paramref name="permissions"/> are not a 3 or 4 character string consisting of only 0-7.</exception> + public static UnixFileMode ToUnixFileMode(this string permissions) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(permissions, nameof(permissions)); + + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + + if (!regEx.IsMatch(permissions)) + { + throw new ArgumentOutOfRangeException($"The provided permissions are not a valid, expected 0-7 repeated 3 or 4 times (provided: {permissions})"); + } + + var opts = permissions + .Select(x => int.Parse(x.ToString())) + .Reverse() + .ToArray(); + + int mode = 0; + + for (var i = 0; i < opts.Length; i++) + { + mode |= opts[i] << (i * 3); + } + + return (UnixFileMode)mode; + } +}
\ No newline at end of file diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index ee8271b1..0d193d73 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -36,19 +36,19 @@ namespace slskd.Files /// Initializes a new instance of the <see cref="FileService"/> class. /// </summary> public FileService( - IOptionsSnapshot<Options> optionsSnapshot) + IOptionsMonitor<Options> optionsMonitor) { - OptionsSnapshot = optionsSnapshot; + OptionsMonitor = optionsMonitor; } private IEnumerable<string> AllowedDirectories => new[] { - Path.GetFullPath(OptionsSnapshot.Value.Directories.Downloads), - Path.GetFullPath(OptionsSnapshot.Value.Directories.Incomplete), + Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), + Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), }; private ILogger Log { get; } = Serilog.Log.ForContext<FileService>(); - private IOptionsSnapshot<Options> OptionsSnapshot { get; } + private IOptionsMonitor<Options> OptionsMonitor { get; } /// <summary> /// Deletes the specified <paramref name="directories"/>. @@ -236,5 +236,138 @@ namespace slskd.Files } }); } + + /// <summary> + /// Creates a new file with the specified fully qualified <paramref name="filename"/> and the optional <paramref name="options"/>, + /// returning a <see cref="Stream"/> with which the contents of the file can be written. + /// </summary> + /// <remarks> + /// Reasonable defaults, including the Unix permissions from app configuration, have been applied. Be sure to review the defaults + /// for each new use case and ensure they are appropriate. + /// </remarks> + /// <param name="filename">The fully qualified filename.</param> + /// <param name="options">An optional patch for the underlying <see cref="FileStreamOptions"/>.</param> + /// <returns>A Stream with which the contents of the file can be written.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified filename is null or contains only whitespace.</exception> + /// <exception cref="IOException">Thrown if the underlying file or Stream can't be created for some reason.</exception> + public virtual Stream CreateFile(string filename, CreateFileOptions options = null) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + + var path = Path.GetDirectoryName(filename); + + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + + var streamOptions = new FileStreamOptions + { + Access = options?.Access ?? FileAccess.Write, + BufferSize = options?.BufferSize ?? 4096, // framework default + Mode = options?.Mode ?? FileMode.Create, // overwrite + Options = options?.Options ?? FileOptions.None, // synchronous I/O + PreallocationSize = options?.PreallocationSize ?? 0, + Share = options?.Share ?? FileShare.None, // exclusive access + }; + + // attempting to use UnixCreateMode on Windows raises an Exception + // we *MUST* check the OS and skip this on Windows + if (!OperatingSystem.IsWindows()) + { + var appOption = OptionsMonitor.CurrentValue.Permissions.File.Mode; + + // if options haven't been passed in and none have been set in app config, omit this + // so that the application's umask will be applied, saving users the hassle of setting it twice. + if (options?.UnixCreateMode != null || !string.IsNullOrWhiteSpace(appOption)) + { + streamOptions.UnixCreateMode = options?.UnixCreateMode ?? appOption?.ToUnixFileMode(); + Log.Debug("Setting Unix file mode to {Mode}", streamOptions.UnixCreateMode); + } + } + + try + { + return new FileStream(filename, streamOptions); + } + catch (Exception ex) + { + // the operation above can throw quite a few exceptions, all granular variations of + // IOException. to make handling downstream easier, wrap them all up and re-throw. + throw new IOException($"Failed to create file {Path.GetFileName(filename)}: {ex.Message}", ex); + } + } + + /// <summary> + /// Moves the specified fully qualified, localized, <paramref name="sourceFilename"/> to the specified fully qualified, localized, + /// <paramref name="destinationDirectory"/>. + /// </summary> + /// <remarks> + /// If the destination file already exists and the <paramref name="overwrite"/> option is not set, the destination filename will + /// be modified to include the current time to avoid the collision while preserving both files. + /// </remarks> + /// <param name="sourceFilename">The fully qualified filename of the file to move.</param> + /// <param name="destinationDirectory">The fully qualified directory to which to move the source file.</param> + /// <param name="overwrite">An optional value indicating whether the destination file should be overwritten if it already exists.</param> + /// <param name="deleteSourceDirectoryIfEmptyAfterMove"> + /// An optional value indicating whether the parent directory of the source file should be deleted if it is empty after the move. + /// </param> + /// <returns>The fully qualified filename of the resulting file.</returns> + /// <exception cref="ArgumentNullException">Thrown if either of the specified file or directories are null or contain only whitespace.</exception> + /// <exception cref="FileNotFoundException">Thrown if the specified <paramref name="sourceFilename"/> does not exist.</exception> + /// <exception cref="IOException">Thrown if the file can't be moved, or the <paramref name="deleteSourceDirectoryIfEmptyAfterMove"/> option is set and the operation fails.</exception> + public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); + ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); + + if (!File.Exists(sourceFilename)) + { + throw new FileNotFoundException($"The specified source file does not exist", fileName: sourceFilename); + } + + if (!Directory.Exists(destinationDirectory)) + { + Directory.CreateDirectory(destinationDirectory); + } + + var destinationFilename = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilename)); + + Log.Debug("Attempting to move {Source} to {Destination}", sourceFilename, destinationFilename); + + if (!overwrite && File.Exists(destinationFilename)) + { + Log.Debug("Destination file {Destination} exists, and overwite option is not set; attempting to generate new filename", destinationFilename); + + string extensionlessFilename = Path.Combine(Path.GetDirectoryName(destinationFilename), Path.GetFileNameWithoutExtension(sourceFilename)); + string extension = Path.GetExtension(sourceFilename); + + while (File.Exists(destinationFilename)) + { + destinationFilename = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; + } + } + + try + { + File.Move(sourceFilename, destinationFilename, overwrite: overwrite); + + Log.Debug("Successfully moved {Source} to {Destination}", sourceFilename, destinationFilename); + + // if the parent directory is empty after the move, delete it + if (deleteSourceDirectoryIfEmptyAfterMove && !Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) + { + Directory.Delete(Path.GetDirectoryName(sourceFilename)); + } + + return destinationFilename; + } + catch (Exception ex) + { + // the operation above can throw quite a few exceptions, all granular variations of + // IOException. to make handling downstream easier, wrap them all up and re-throw. + throw new IOException($"Failed to move file {Path.GetFileName(sourceFilename)}: {ex.Message}", ex); + } + } } }
\ No newline at end of file diff --git a/src/slskd/Files/Types/CreateFileOptions.cs b/src/slskd/Files/Types/CreateFileOptions.cs new file mode 100644 index 00000000..26d6e7d4 --- /dev/null +++ b/src/slskd/Files/Types/CreateFileOptions.cs @@ -0,0 +1,31 @@ +// <copyright file="CreateFileOptions.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Files; + +using System.IO; + +public record CreateFileOptions +{ + public FileAccess? Access { get; init; } + public int? BufferSize { get; init; } + public FileMode? Mode { get; init; } + public FileOptions? Options { get; init; } + public long? PreallocationSize { get; init; } + public FileShare? Share { get; init; } + public UnixFileMode? UnixCreateMode { get; init; } +}
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 545a80ab..27cbfc6f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -590,7 +590,7 @@ namespace slskd services.AddSingleton<ITransferService, TransferService>(); services.AddSingleton<IDownloadService, DownloadService>(); services.AddSingleton<IUploadService, UploadService>(); - services.AddTransient<FileService>(); + services.AddSingleton<FileService>(); services.AddSingleton<IRelayService, RelayService>(); diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 57a78a1f..32903bf9 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -23,13 +23,13 @@ namespace slskd.Transfers.Downloads using System; using System.Collections.Concurrent; using System.Collections.Generic; - using System.IO; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; + using slskd.Files; using slskd.Integrations.FTP; using slskd.Relay; @@ -120,12 +120,14 @@ namespace slskd.Transfers.Downloads IOptionsMonitor<Options> optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory<TransfersDbContext> contextFactory, + FileService fileService, IRelayService relayService, IFTPService ftpClient) { Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; + Files = fileService; FTP = ftpClient; Relay = relayService; } @@ -134,6 +136,7 @@ namespace slskd.Transfers.Downloads private ISoulseekClient Client { get; } private IDbContextFactory<TransfersDbContext> ContextFactory { get; } private IFTPService FTP { get; } + private FileService Files { get; } private IRelayService Relay { get; } private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } @@ -285,7 +288,18 @@ namespace slskd.Transfers.Downloads var completedTransfer = await Client.DownloadAsync( username: username, remoteFilename: file.Filename, - outputStreamFactory: () => Task.FromResult(GetLocalFileStream(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete)), + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + options: new CreateFileOptions + { + Access = System.IO.FileAccess.Write, + Mode = System.IO.FileMode.Create, // overwrites file if it exists + Share = System.IO.FileShare.None, // exclusive access for the duration of the download + UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() + : null, + })), size: file.Size, startOffset: 0, token: null, @@ -304,7 +318,11 @@ namespace slskd.Transfers.Downloads // this would be the ideal place to hook in a generic post-download task processor for now, we'll // just carry out hard coded behavior. these carry the risk of failing the transfer, and i could // argue both ways for that being the correct behavior. revisit this later. - var finalFilename = MoveFile(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete, OptionsMonitor.CurrentValue.Directories.Downloads); + var finalFilename = Files.MoveFile( + sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + destinationDirectory: System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)), + overwrite: false, + deleteSourceDirectoryIfEmptyAfterMove: true); Log.Debug("Moved file to {Destination}", finalFilename); @@ -587,52 +605,5 @@ namespace slskd.Transfers.Downloads context.Update(transfer); context.SaveChanges(); } - - private static Stream GetLocalFileStream(string remoteFilename, string saveDirectory) - { - var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); - var path = Path.GetDirectoryName(localFilename); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - return new FileStream(localFilename, FileMode.Create); - } - - private static string MoveFile(string filename, string sourceDirectory, string destinationDirectory) - { - var sourceFilename = filename.ToLocalFilename(sourceDirectory); - var destinationFilename = filename.ToLocalFilename(destinationDirectory); - - var destinationPath = Path.GetDirectoryName(destinationFilename); - - if (!Directory.Exists(destinationPath)) - { - Directory.CreateDirectory(destinationPath); - } - - if (File.Exists(destinationFilename)) - { - string extensionlessFilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename)); - string extension = Path.GetExtension(filename); - - while (File.Exists(destinationFilename)) - { - string filenameUTC = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; - destinationFilename = filenameUTC.ToLocalFilename(destinationDirectory); - } - } - - File.Move(sourceFilename, destinationFilename, overwrite: true); - - if (!Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) - { - Directory.Delete(Path.GetDirectoryName(sourceFilename)); - } - - return destinationFilename; - } } }
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs b/tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs new file mode 100644 index 00000000..c270bb31 --- /dev/null +++ b/tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using slskd.Files; +using Xunit; + +namespace slskd.Tests.Unit.Files; + +public class FileExtensionsTests +{ + [Theory] + [InlineData("0000", UnixFileMode.None)] + [InlineData("0100", UnixFileMode.UserExecute)] + [InlineData("0200", UnixFileMode.UserWrite)] + [InlineData("0300", UnixFileMode.UserWrite | UnixFileMode.UserExecute)] + [InlineData("0400", UnixFileMode.UserRead)] + [InlineData("0500", UnixFileMode.UserRead | UnixFileMode.UserExecute)] + [InlineData("0600", UnixFileMode.UserRead | UnixFileMode.UserWrite)] + [InlineData("0700", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute)] + [InlineData("0010", UnixFileMode.GroupExecute)] + [InlineData("0020", UnixFileMode.GroupWrite)] + [InlineData("0030", UnixFileMode.GroupWrite | UnixFileMode.GroupExecute)] + [InlineData("0040", UnixFileMode.GroupRead)] + [InlineData("0050", UnixFileMode.GroupRead | UnixFileMode.GroupExecute)] + [InlineData("0060", UnixFileMode.GroupRead | UnixFileMode.GroupWrite)] + [InlineData("0070", UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute)] + [InlineData("0001", UnixFileMode.OtherExecute)] + [InlineData("0002", UnixFileMode.OtherWrite)] + [InlineData("0003", UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)] + [InlineData("0004", UnixFileMode.OtherRead)] + [InlineData("0005", UnixFileMode.OtherRead | UnixFileMode.OtherExecute)] + [InlineData("0006", UnixFileMode.OtherRead | UnixFileMode.OtherWrite)] + [InlineData("0007", UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)] + [InlineData("0644", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead)] + [InlineData("0777", UnixFileMode.UserExecute | UnixFileMode.UserWrite | UnixFileMode.UserRead | UnixFileMode.GroupExecute | UnixFileMode.GroupWrite | UnixFileMode.GroupRead | UnixFileMode.OtherExecute | UnixFileMode.OtherWrite | UnixFileMode.OtherRead)] + [InlineData("1000", UnixFileMode.StickyBit)] + [InlineData("2000", UnixFileMode.SetGroup)] + [InlineData("3000", UnixFileMode.SetGroup | UnixFileMode.StickyBit)] + [InlineData("4000", UnixFileMode.SetUser)] + [InlineData("5000", UnixFileMode.SetUser | UnixFileMode.StickyBit)] + [InlineData("6000", UnixFileMode.SetUser | UnixFileMode.SetGroup)] + [InlineData("7000", UnixFileMode.SetUser | UnixFileMode.SetGroup | UnixFileMode.StickyBit)] + [InlineData("7777", UnixFileMode.SetUser | UnixFileMode.SetGroup | UnixFileMode.StickyBit | UnixFileMode.UserExecute | UnixFileMode.UserWrite | UnixFileMode.UserRead | UnixFileMode.GroupExecute | UnixFileMode.GroupWrite | UnixFileMode.GroupRead | UnixFileMode.OtherExecute | UnixFileMode.OtherWrite | UnixFileMode.OtherRead)] + public void ToUnixFileMode_Works_As_Expected(string permissions, UnixFileMode expected) + { + var result = permissions.ToUnixFileMode(); + + Assert.Equal(expected, result); + } + + [Fact] + public void ToUinixFileMode_Throws_ArgumentException_Given_Empty() + { + var ex = Record.Exception(() => "".ToUnixFileMode()); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("0")] + [InlineData("00")] + [InlineData("00000")] + [InlineData("foo bar baz")] + public void ToUinixFileMode_Throws_ArgumentOutOfRangeException_Given_Bad_String(string str) + { + var ex = Record.Exception(() => str.ToUnixFileMode()); + + Assert.NotNull(ex); + Assert.IsType<ArgumentOutOfRangeException>(ex); + } +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs index 917d1a43..6c3d1d73 100644 --- a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs +++ b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs @@ -13,13 +13,13 @@ namespace slskd.Tests.Unit.Files { public FileServiceTests() { - OptionsSnapshotMock = new Mock<IOptionsSnapshot<Options>>(); + OptionsMonitorMock = new Mock<IOptionsMonitor<Options>>(); Temp = Path.Combine(Path.GetTempPath(), $"slskd.test.{Guid.NewGuid()}"); Directory.CreateDirectory(Temp); FileService = new FileService( - optionsSnapshot: OptionsSnapshotMock.Object); + optionsMonitor: OptionsMonitorMock.Object); } public void Dispose() @@ -27,7 +27,7 @@ namespace slskd.Tests.Unit.Files Directory.Delete(Temp, recursive: true); } - private Mock<IOptionsSnapshot<Options>> OptionsSnapshotMock { get; init; } + private Mock<IOptionsMonitor<Options>> OptionsMonitorMock { get; init; } private string Temp { get; init; } private FileService FileService { get; init; } @@ -44,7 +44,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task ListContentsAsync_Throws_UnauthorizedException_Given_Disallowed_Directory() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { @@ -62,7 +62,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task ListContentsAsync_Throws_NotFoundException_Given_NonExistent_Directory() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { @@ -90,7 +90,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task DeleteDirectoriesAsync_Throws_ArgumentException_Given_Disallowed_Path() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { @@ -118,7 +118,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task DeleteFilesAsync_Throws_ArgumentException_Given_Disallowed_Path() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { |
