diff options
| author | JP Dillingham <jp@dillingham.me> | 2023-07-25 08:14:29 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-07-25 08:14:29 -0500 |
| commit | 76ea31e3556c25df85a9708e3cbbe6062b0abb44 (patch) | |
| tree | 627b720e05e26aab7b4a3ee86445f01ee6984528 /src/slskd/Files | |
| parent | 50bf39a16261ac4a0ba9f70501c183867d382712 (diff) | |
| parent | f3b4f3fc6328c5b56820b93a92d83680e0498833 (diff) | |
| download | slskd-76ea31e3556c25df85a9708e3cbbe6062b0abb44.tar.gz | |
Merge pull request #941 from slskd/view-files
Add the ability to view and delete downloaded and incomplete files to the UI
Diffstat (limited to 'src/slskd/Files')
| -rw-r--r-- | src/slskd/Files/API/FilesController.cs | 304 | ||||
| -rw-r--r-- | src/slskd/Files/FileService.cs | 143 | ||||
| -rw-r--r-- | src/slskd/Files/IFileService.cs | 26 | ||||
| -rw-r--r-- | src/slskd/Files/Types/FilesystemDirectory.cs | 36 | ||||
| -rw-r--r-- | src/slskd/Files/Types/FilesystemFile.cs | 31 |
5 files changed, 331 insertions, 209 deletions
diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index 08895639..372e5f5e 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -19,13 +19,13 @@ using Microsoft.Extensions.Options; namespace slskd.Files.API { - using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; + using System.Security; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; - using OneOf; + using Serilog; /// <summary> /// Files. @@ -47,163 +47,145 @@ namespace slskd.Files.API private IFileService Files { get; } private IOptionsSnapshot<Options> OptionsSnapshot { get; } + private ILogger Log { get; set; } = Serilog.Log.ForContext<FilesController>(); + /// <summary> + /// Lists the contents of the downloads directory. + /// </summary> + /// <param name="recursive">An optional value indicating whether to recursively list subdirectories and files.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="401">Authentication failed.</response> [HttpGet("downloads/directories")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(IEnumerable<FilesystemDirectory>), 200)] - public async Task<IActionResult> GetDownloadContentsAsync([FromQuery] bool recursive = false) - { - try - { - var response = await Files.ListContentsAsync( - rootDirectory: OptionsSnapshot.Value.Directories.Downloads, - enumerationOptions: new EnumerationOptions - { - AttributesToSkip = FileAttributes.System, - RecurseSubdirectories = recursive, - }); - - return Ok(response); - } - catch (ForbiddenException) - { - return Forbid(); - } - catch (NotFoundException) - { - return NotFound(); - } - } + [ProducesResponseType(typeof(FilesystemDirectory), 200)] + [ProducesResponseType(401)] + public Task<IActionResult> GetDownloadContentsAsync([FromQuery] bool recursive = false) + => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64SubdirectoryName: null, recursive); + /// <summary> + /// Lists the contents of the specified subdirectory within the downloads directory. + /// </summary> + /// <param name="base64SubdirectoryName">The relative, base 64 encoded, name of the subdirectory to list.</param> + /// <param name="recursive">An optional value indicating whether to recursively list subdirectories and files.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="401">Authentication failed.</response> + /// <response code="403">Access to the specified subdirectory was denied.</response> + /// <response code="404">The specified subdirectory does not exist.</response> [HttpGet("downloads/directories/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(IEnumerable<FilesystemDirectory>), 200)] - public async Task<IActionResult> GetDownloadSubdirectoryContentsAsync([FromRoute] string base64SubdirectoryName, [FromQuery] bool recursive = false) - { - var decodedDir = base64SubdirectoryName.FromBase64(); - - try - { - var response = await Files.ListContentsAsync( - rootDirectory: OptionsSnapshot.Value.Directories.Downloads, - parentDirectory: decodedDir, - enumerationOptions: new EnumerationOptions - { - AttributesToSkip = FileAttributes.System, - RecurseSubdirectories = recursive, - }); - - return Ok(response); - } - catch (ForbiddenException) - { - return Forbid(); - } - catch (NotFoundException) - { - return NotFound(); - } - } + [ProducesResponseType(typeof(FilesystemDirectory), 200)] + [ProducesResponseType(401)] + [ProducesResponseType(403)] + [ProducesResponseType(404)] + public Task<IActionResult> GetDownloadSubdirectoryContentsAsync([FromRoute] string base64SubdirectoryName, [FromQuery] bool recursive = false) + => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64SubdirectoryName, recursive); + /// <summary> + /// Deletes the specified subdirectory within the downloads directory. + /// </summary> + /// <param name="base64SubdirectoryName">The relative, base 64 encoded, name of the subdirectory to delete.</param> + /// <returns></returns> + /// <response code="204">The request completed successfully.</response> + /// <response code="401">Authentication failed.</response> + /// <response code="403">Access to the specified subdirectory was denied.</response> + /// <response code="404">The specified subdirectory does not exist.</response> [HttpDelete("downloads/directories/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary<string, OneOf<bool, string>>), 204)] - public async Task<IActionResult> DeleteDownloadSubdirectoryAsync([FromRoute] string base64SubdirectoryName) - { - if (!OptionsSnapshot.Value.RemoteFileManagement) - { - return Forbid(); - } - - var decodedDir = base64SubdirectoryName.FromBase64(); - - try - { - var results = await Files.DeleteDirectoriesAsync(OptionsSnapshot.Value.Directories.Downloads, decodedDir); - - return results[decodedDir].Match( - success => NoContent(), - failure => throw failure); - } - catch (ForbiddenException) - { - return Forbid(); - } - catch (NotFoundException) - { - return NotFound(); - } - } + [ProducesResponseType(204)] + public Task<IActionResult> DeleteDownloadSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + => DeleteSubdirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64SubdirectoryName); - [HttpDelete("downloads/files/{base64Filename}")] + /// <summary> + /// Deletes the specified file within the downloads directory. + /// </summary> + /// <param name="base64FileName">The relative, base 64 encoded, name of the file to delete.</param> + /// <returns></returns> + /// <response code="204">The request completed successfully.</response> + /// <response code="401">Authentication failed.</response> + /// <response code="403">Access to the specified subdirectory was denied.</response> + /// <response code="404">The specified subdirectory does not exist.</response> + [HttpDelete("downloads/files/{base64FileName}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary<string, OneOf<bool, string>>), 204)] - public async Task<IActionResult> DeleteDownloadFileAsync([FromRoute] string base64filename) - { - if (!OptionsSnapshot.Value.RemoteFileManagement) - { - return Forbid(); - } + [ProducesResponseType(204)] + public Task<IActionResult> DeleteDownloadFileAsync([FromRoute] string base64FileName) + => DeleteFileAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64FileName); - var decodedFilename = base64filename.FromBase64(); + /// <summary> + /// Lists the contents of the downloads directory. + /// </summary> + /// <param name="recursive">An optional value indicating whether to recursively list subdirectories and files.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="401">Authentication failed.</response> + [HttpGet("incomplete/directories")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(FilesystemDirectory), 200)] + public Task<IActionResult> GetIncompleteContentsAsync([FromQuery] bool recursive = false) + => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64SubdirectoryName: null, recursive); - try - { - var results = await Files.DeleteFilesAsync(OptionsSnapshot.Value.Directories.Downloads, base64filename); + /// <summary> + /// Lists the contents of the specified subdirectory within the incomplete directory. + /// </summary> + /// <param name="base64SubdirectoryName">The relative, base 64 encoded, name of the subdirectory to list.</param> + /// <param name="recursive">An optional value indicating whether to recursively list subdirectories and files.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="401">Authentication failed.</response> + /// <response code="403">Access to the specified subdirectory was denied.</response> + /// <response code="404">The specified subdirectory does not exist.</response> + [HttpGet("incomplete/directories/{base64SubdirectoryName}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(FilesystemDirectory), 200)] + public Task<IActionResult> GetIncompleteSubdirectoryContentsAsync([FromRoute, Required] string base64SubdirectoryName, [FromQuery] bool recursive = false) + => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64SubdirectoryName, recursive); - return results[decodedFilename].Match( - success => NoContent(), - failure => throw failure); - } - catch (ForbiddenException) - { - return Forbid(); - } - catch (NotFoundException) - { - return NotFound(); - } - } + /// <summary> + /// Deletes the specified subdirectory within the downloads directory. + /// </summary> + /// <param name="base64SubdirectoryName">The relative, base 64 encoded, name of the subdirectory to delete.</param> + /// <returns></returns> + /// <response code="204">The request completed successfully.</response> + /// <response code="401">Authentication failed.</response> + /// <response code="403">Access to the specified subdirectory was denied.</response> + /// <response code="404">The specified subdirectory does not exist.</response> + [HttpDelete("incomplete/directories/{base64SubdirectoryName}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(204)] + public Task<IActionResult> DeleteIncompleteSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + => DeleteSubdirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64SubdirectoryName); - [HttpGet("incomplete/directories")] + /// <summary> + /// Deletes the specified file within the downloads directory. + /// </summary> + /// <param name="base64FileName">The relative, base 64 encoded, name of the file to delete.</param> + /// <returns></returns> + /// <response code="204">The request completed successfully.</response> + /// <response code="401">Authentication failed.</response> + /// <response code="403">Access to the specified subdirectory was denied.</response> + /// <response code="404">The specified subdirectory does not exist.</response> + [HttpDelete("incomplete/files/{base64FileName}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(IEnumerable<FilesystemDirectory>), 200)] - public async Task<IActionResult> GetIncompleteContentsAsync([FromQuery] bool recursive = false) + [ProducesResponseType(204)] + public Task<IActionResult> DeleteIncompleteFileAsync([FromRoute] string base64FileName) + => DeleteFileAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64FileName); + + private async Task<IActionResult> ListDirectoryAsync(string rootDirectory, string base64SubdirectoryName = null, bool recursive = false) { - try - { - var response = await Files.ListContentsAsync( - rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, - enumerationOptions: new EnumerationOptions - { - AttributesToSkip = FileAttributes.System, - RecurseSubdirectories = recursive, - }); + var requestedDir = (base64SubdirectoryName ?? string.Empty) + .FromBase64() + .Replace('\\', Path.DirectorySeparatorChar) + .Replace('/', Path.DirectorySeparatorChar); - return Ok(response); - } - catch (ForbiddenException) - { - return Forbid(); - } - catch (NotFoundException) - { - return NotFound(); - } - } + requestedDir = Path.GetFullPath(Path.Combine(rootDirectory, requestedDir)); - [HttpGet("incomplete/directories/{base64SubdirectoryName}")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(IEnumerable<FilesystemDirectory>), 200)] - public async Task<IActionResult> GetIncompleteSubdirectoryContentsAsync([FromRoute, Required] string base64SubdirectoryName, [FromQuery] bool recursive = false) - { - var decodedDir = base64SubdirectoryName.FromBase64(); + Log.Debug("Listing directory '{Directory}'", requestedDir); try { var response = await Files.ListContentsAsync( - rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, - parentDirectory: decodedDir, + directory: requestedDir, enumerationOptions: new EnumerationOptions { AttributesToSkip = FileAttributes.System, @@ -212,72 +194,88 @@ namespace slskd.Files.API return Ok(response); } - catch (ForbiddenException) + catch (SecurityException) { + Log.Warning("Directory listing of '{Directory}' forbidden", requestedDir); return Forbid(); } catch (NotFoundException) { + Log.Debug("Directory '{Directory}' not found", requestedDir); return NotFound(); } } - [HttpDelete("incomplete/directories/{base64SubdirectoryName}")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary<string, OneOf<bool, string>>), 204)] - public async Task<IActionResult> DeleteIncompleteSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + private async Task<IActionResult> DeleteSubdirectoryAsync(string rootDirectory, string base64SubdirectoryName) { if (!OptionsSnapshot.Value.RemoteFileManagement) { return Forbid(); } - var decodedDir = base64SubdirectoryName.FromBase64(); + var requestedDir = base64SubdirectoryName + .FromBase64() + .Replace('\\', Path.DirectorySeparatorChar) + .Replace('/', Path.DirectorySeparatorChar) + .TrimStart(Path.DirectorySeparatorChar); + + requestedDir = Path.GetFullPath(Path.Combine(rootDirectory, requestedDir)); + + Log.Information("Deleting directory '{Directory}'", requestedDir); try { - var results = await Files.DeleteDirectoriesAsync(OptionsSnapshot.Value.Directories.Incomplete, decodedDir); + var results = await Files.DeleteDirectoriesAsync(requestedDir); - return results[decodedDir].Match( + return results[requestedDir].Match( success => NoContent(), failure => throw failure); } - catch (ForbiddenException) + catch (SecurityException) { + Log.Warning("Directory deletion of '{Directory}' forbidden", requestedDir); return Forbid(); } catch (NotFoundException) { + Log.Information("Directory '{Directory}' not found", requestedDir); return NotFound(); } } - [HttpDelete("incomplete/files/{base64Filename}")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary<string, OneOf<bool, string>>), 204)] - public async Task<IActionResult> DeleteIncompleteFileAsync([FromRoute] string base64filename) + private async Task<IActionResult> DeleteFileAsync(string rootDirectory, string base64FileName) { if (!OptionsSnapshot.Value.RemoteFileManagement) { return Forbid(); } - var decodedFilename = base64filename.FromBase64(); + var requestedFilename = base64FileName + .FromBase64() + .Replace('\\', Path.DirectorySeparatorChar) + .Replace('/', Path.DirectorySeparatorChar) + .TrimStart(Path.DirectorySeparatorChar); + + requestedFilename = Path.GetFullPath(Path.Combine(rootDirectory, requestedFilename)); + + Log.Information("Deleting file '{File}'", requestedFilename); try { - var results = await Files.DeleteFilesAsync(OptionsSnapshot.Value.Directories.Incomplete, base64filename); + var results = await Files.DeleteFilesAsync(requestedFilename); - return results[decodedFilename].Match( + return results[requestedFilename].Match( success => NoContent(), failure => throw failure); } - catch (ForbiddenException) + catch (SecurityException) { + Log.Warning("File deletion of '{File}' forbidden", requestedFilename); return Forbid(); } catch (NotFoundException) { + Log.Information("File '{File}' not found", requestedFilename); return NotFound(); } } diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index f37c861b..c820220f 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -23,8 +23,10 @@ namespace slskd.Files using System.Collections.Generic; using System.IO; using System.Linq; + using System.Security; using System.Threading.Tasks; using OneOf; + using Serilog; /// <summary> /// Manages files on disk. @@ -40,7 +42,13 @@ namespace slskd.Files OptionsSnapshot = optionsSnapshot; } - private IEnumerable<string> AllowedDirectories => new[] { OptionsSnapshot.Value.Directories.Downloads, OptionsSnapshot.Value.Directories.Incomplete }; + private IEnumerable<string> AllowedDirectories => new[] + { + Path.GetFullPath(OptionsSnapshot.Value.Directories.Downloads), + Path.GetFullPath(OptionsSnapshot.Value.Directories.Incomplete), + }; + + private ILogger Log { get; } = Serilog.Log.ForContext<FileService>(); private IOptionsSnapshot<Options> OptionsSnapshot { get; } /// <summary> @@ -50,16 +58,33 @@ namespace slskd.Files /// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are /// contained in the result, and are not thrown. /// </remarks> - /// <param name="rootDirectory">The root directory.</param> /// <param name="directories">The directories to delete.</param> /// <returns>The operation context.</returns> + /// <exception cref="ArgumentException">Thrown if any of the specified directories have a relative path.</exception> + /// <exception cref="ArgumentException"> + /// Thrown if any of the directories is an exact match for an application-controlled directory. + /// </exception> /// <exception cref="NotFoundException">Thrown if a specified directory does not exist.</exception> - /// <exception cref="ForbiddenException">Thrown if a specified directory is restricted.</exception> - public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(string rootDirectory, params string[] directories) + /// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception> + public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories) { - if (!AllowedDirectories.Any(d => rootDirectory == d)) + if (directories.Any(directory => Path.GetFullPath(directory) != directory)) + { + throw new ArgumentException("Only absolute paths may be specified", nameof(directories)); + } + + if (directories.Any(directory => AllowedDirectories.Contains(directory))) + { + throw new ArgumentException("Deletion of application-controlled directory roots is not supported"); + } + + // important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..' + bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed)); + + // if any of the resolved directory paths aren't rooted in one of the allowed directories, forbid the entire request + if (!directories.All(directory => IsAllowed(directory))) { - throw new ForbiddenException($"For security reasons, only application-controlled directories can be deleted"); + throw new UnauthorizedException("Only application-controlled directories can be deleted"); } await Task.Yield(); @@ -70,16 +95,18 @@ namespace slskd.Files { try { - Directory.Delete(Path.Combine(rootDirectory, directory), recursive: true); + Directory.Delete(directory, recursive: true); results.Add(directory, true); + + Log.Information("Deleted directory '{Directory}'", directory); } - catch (FileNotFoundException) + catch (DirectoryNotFoundException) { results.Add(directory, new NotFoundException($"The directory '{directory}' does not exist")); } - catch (UnauthorizedAccessException) + catch (UnauthorizedAccessException ex) { - results.Add(directory, new ForbiddenException()); + results.Add(directory, new UnauthorizedException($"Deletion of the directory '{directory}' was denied: {ex.Message}", ex)); } catch (Exception ex) { @@ -97,16 +124,25 @@ namespace slskd.Files /// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are /// contained in the result, and are not thrown. /// </remarks> - /// <param name="rootDirectory">The root directory.</param> /// <param name="files">The list of files to delete.</param> /// <returns>The operation context.</returns> + /// <exception cref="ArgumentException">Thrown if any of the specified files have a relative path.</exception> /// <exception cref="NotFoundException">Thrown if a specified file does not exist.</exception> - /// <exception cref="ForbiddenException">Thrown if a specified file is restricted.</exception> - public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(string rootDirectory, params string[] files) + /// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception> + public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files) { - if (!AllowedDirectories.Any(d => rootDirectory == d)) + if (files.Any(file => Path.GetFullPath(file) != file)) + { + throw new ArgumentException("Only absolute paths may be specified", nameof(files)); + } + + // important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..' + bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed)); + + // if any of the resolved file paths aren't rooted in one of the allowed directories, forbid the entire request + if (!files.All(file => IsAllowed(file))) { - throw new ForbiddenException($"For security reasons, only application-controlled directories can be deleted"); + throw new UnauthorizedException("Only files in application-controlled directories can be deleted"); } await Task.Yield(); @@ -117,16 +153,16 @@ namespace slskd.Files { try { - File.Delete(Path.Combine(rootDirectory, file)); + File.Delete(file); results.Add(file, true); } catch (FileNotFoundException) { results.Add(file, new NotFoundException($"The file '{file}' does not exist")); } - catch (UnauthorizedAccessException) + catch (UnauthorizedAccessException ex) { - results.Add(file, new ForbiddenException()); + results.Add(file, new UnauthorizedException($"Deletion of the file '{file}' was denied: {ex.Message}", ex)); } catch (Exception ex) { @@ -138,50 +174,67 @@ namespace slskd.Files } /// <summary> - /// Lists the contents in the specified <paramref name="parentDirectory"/>, optionally applying the specified <paramref name="enumerationOptions"/>. + /// Lists the contents in the specified <paramref name="directory"/>, optionally applying the specified <paramref name="enumerationOptions"/>. /// </summary> - /// <param name="rootDirectory">The root directory.</param> - /// <param name="parentDirectory">An optional subdirectory from which to start the listing.</param> + /// <param name="directory">The directory from which to start the listing.</param> /// <param name="enumerationOptions">Optional enumeration options to apply.</param> /// <returns>The list of found contents.</returns> + /// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception> /// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception> - /// <exception cref="ForbiddenException">Thrown if the specified directory is restricted.</exception> - public async Task<IEnumerable<FilesystemDirectory>> ListContentsAsync(string rootDirectory, string parentDirectory = null, EnumerationOptions enumerationOptions = null) + /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception> + public async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { - if (!AllowedDirectories.Any(d => rootDirectory == d)) + if (Path.GetFullPath(directory) != directory) { - throw new ForbiddenException($"For security reasons, only application-controlled directories can be deleted"); + throw new ArgumentException("Only absolute paths may be specified", nameof(directory)); } - var fullDirectory = parentDirectory is not null ? Path.Combine(rootDirectory, parentDirectory) : rootDirectory; + // important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..' + if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed))) + { + throw new UnauthorizedException($"Only application-controlled directories can be deleted"); + } - if (!Directory.Exists(fullDirectory)) + if (!Directory.Exists(directory)) { - throw new NotFoundException($"The directory '{fullDirectory}' does not exist"); + throw new NotFoundException($"The directory '{directory}' does not exist"); } return await Task.Run(() => { - var dir = new DirectoryInfo(fullDirectory); - - var contents = dir.GetFileSystemInfos("*", enumerationOptions); + var dir = new DirectoryInfo(directory); - var files = contents - .OfType<FileInfo>() - .Select(f => FilesystemFile.FromFileInfo(f)); - - var dirs = contents - .OfType<DirectoryInfo>() - .Prepend(dir) - .Select(d => FilesystemDirectory.FromDirectoryInfo(d) with + try + { + var contents = dir.GetFileSystemInfos("*", enumerationOptions); + + var files = contents + .OfType<FileInfo>() + .Select(f => FilesystemFile.FromFileInfo(f) with + { + FullName = f.FullName.ReplaceFirst(directory, string.Empty).TrimStart('\\', '/'), + }); + + var dirs = contents + .OfType<DirectoryInfo>() + .Select(d => FilesystemDirectory.FromDirectoryInfo(d) with + { + FullName = d.FullName.ReplaceFirst(directory, string.Empty).TrimStart('\\', '/'), + }); + + var response = FilesystemDirectory.FromDirectoryInfo(dir) with { - FullName = d.FullName.ReplaceFirst(rootDirectory, string.Empty).TrimStart('\\', '/'), - Files = files - .Where(f => Path.GetDirectoryName(f.FullName) == d.FullName) - .Select(f => f with { FullName = f.FullName.ReplaceFirst(rootDirectory, string.Empty).TrimStart('\\', '/') }), - }); + FullName = dir.FullName.ReplaceFirst(directory, string.Empty).TrimStart('\\', '/'), + Files = files, + Directories = dirs, + }; - return dirs; + return response; + } + catch (UnauthorizedAccessException ex) + { + throw new UnauthorizedException($"Access to directory '{directory}' was denied: {ex.Message}", ex); + } }); } } diff --git a/src/slskd/Files/IFileService.cs b/src/slskd/Files/IFileService.cs index 8e3ddcb7..89d4ce76 100644 --- a/src/slskd/Files/IFileService.cs +++ b/src/slskd/Files/IFileService.cs @@ -20,6 +20,7 @@ namespace slskd.Files using System; using System.Collections.Generic; using System.IO; + using System.Security; using System.Threading.Tasks; using OneOf; @@ -35,12 +36,15 @@ namespace slskd.Files /// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are /// contained in the result, and are not thrown. /// </remarks> - /// <param name="rootDirectory">The root directory.</param> /// <param name="directories">The directories to delete.</param> /// <returns>The operation context.</returns> + /// <exception cref="ArgumentException">Thrown if any of the specified directories have a relative path.</exception> + /// <exception cref="ArgumentException"> + /// Thrown if any of the directories is an exact match for an application-controlled directory. + /// </exception> /// <exception cref="NotFoundException">Thrown if a specified directory does not exist.</exception> - /// <exception cref="ForbiddenException">Thrown if a specified directory is restricted.</exception> - Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(string rootDirectory, params string[] directories); + /// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception> + Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories); /// <summary> /// Deletes the specified <paramref name="files"/>. @@ -49,22 +53,22 @@ namespace slskd.Files /// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are /// contained in the result, and are not thrown. /// </remarks> - /// <param name="rootDirectory">The root directory.</param> /// <param name="files">The list of files to delete.</param> /// <returns>The operation context.</returns> + /// <exception cref="ArgumentException">Thrown if any of the specified files have a relative path.</exception> /// <exception cref="NotFoundException">Thrown if a specified file does not exist.</exception> - /// <exception cref="ForbiddenException">Thrown if a specified file is restricted.</exception> - Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(string rootDirectory, params string[] files); + /// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception> + Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files); /// <summary> - /// Lists the contents in the specified <paramref name="parentDirectory"/>, optionally applying the specified <paramref name="enumerationOptions"/>. + /// Lists the contents in the specified <paramref name="directory"/>, optionally applying the specified <paramref name="enumerationOptions"/>. /// </summary> - /// <param name="rootDirectory">The root directory.</param> - /// <param name="parentDirectory">An optional subdirectory from which to start the listing.</param> + /// <param name="directory">The directory from which to start the listing.</param> /// <param name="enumerationOptions">Optional enumeration options to apply.</param> /// <returns>The list of found contents.</returns> + /// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception> /// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception> - /// <exception cref="ForbiddenException">Thrown if the specified root directory is restricted.</exception> - Task<IEnumerable<FilesystemDirectory>> ListContentsAsync(string rootDirectory, string parentDirectory = null, EnumerationOptions enumerationOptions = null); + /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception> + Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null); } }
\ No newline at end of file diff --git a/src/slskd/Files/Types/FilesystemDirectory.cs b/src/slskd/Files/Types/FilesystemDirectory.cs index 4183c724..6628ce15 100644 --- a/src/slskd/Files/Types/FilesystemDirectory.cs +++ b/src/slskd/Files/Types/FilesystemDirectory.cs @@ -21,15 +21,51 @@ namespace slskd.Files using System.Collections.Generic; using System.IO; + /// <summary> + /// A file directory on the host filesystem. + /// </summary> public record FilesystemDirectory { + /// <summary> + /// The name of the directory. + /// </summary> public string Name { get; init; } + + /// <summary> + /// The fully qualified name of the directory. + /// </summary> public string FullName { get; init; } + + /// <summary> + /// The directories' attributes. + /// </summary> public FileAttributes Attributes { get; init; } + + /// <summary> + /// The timestamp at which the directory was created. + /// </summary> public DateTime CreatedAt { get; init; } + + /// <summary> + /// The timestamp at which the directory was last modified. + /// </summary> public DateTime ModifiedAt { get; init; } + + /// <summary> + /// The files within the directory. + /// </summary> public IEnumerable<FilesystemFile> Files { get; init; } + /// <summary> + /// The directories within the directory. + /// </summary> + public IEnumerable<FilesystemDirectory> Directories { get; init; } + + /// <summary> + /// Maps a <see cref="FilesystemDirectory"/> from the specified <see cref="DirectoryInfo"/>. + /// </summary> + /// <param name="i">The DirectoryInfo instance from which to map.</param> + /// <returns>A new instance of FilesystemDirectory.</returns> public static FilesystemDirectory FromDirectoryInfo(DirectoryInfo i) { return new FilesystemDirectory diff --git a/src/slskd/Files/Types/FilesystemFile.cs b/src/slskd/Files/Types/FilesystemFile.cs index fc36fff0..0b6feeb5 100644 --- a/src/slskd/Files/Types/FilesystemFile.cs +++ b/src/slskd/Files/Types/FilesystemFile.cs @@ -20,15 +20,46 @@ namespace slskd.Files using System; using System.IO; + /// <summary> + /// A file on the host filesystem. + /// </summary> public record FilesystemFile { + /// <summary> + /// The name of the file. + /// </summary> public string Name { get; init; } + + /// <summary> + /// The fully qualified name of the file. + /// </summary> public string FullName { get; init; } + + /// <summary> + /// The size of the file, in bytes. + /// </summary> public long Length { get; init; } + + /// <summary> + /// The file's attributes. + /// </summary> public FileAttributes Attributes { get; init; } + + /// <summary> + /// The timestamp at which the file was created. + /// </summary> public DateTime CreatedAt { get; init; } + + /// <summary> + /// The timestamp at which the file was last modified. + /// </summary> public DateTime ModifiedAt { get; init; } + /// <summary> + /// Maps a <see cref="FilesystemFile"/> from the specified <see cref="FileInfo"/>. + /// </summary> + /// <param name="i">The FileInfo instance from which to map.</param> + /// <returns>A new instance of FilesystemFile.</returns> public static FilesystemFile FromFileInfo(FileInfo i) { return new FilesystemFile |
