From 7316f144c2fca00fbcfe54b65846a4102ea536ab Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 1 Jul 2023 15:12:12 -0500 Subject: refactor, simplify, document --- src/slskd/Files/API/FilesController.cs | 288 ++++++++++++++++----------------- 1 file changed, 143 insertions(+), 145 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index f4b3ce87..12c642c0 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -22,10 +22,12 @@ 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; /// /// Files. @@ -47,163 +49,145 @@ namespace slskd.Files.API private IFileService Files { get; } private IOptionsSnapshot OptionsSnapshot { get; } + private ILogger Log { get; set; } = Serilog.Log.ForContext(); + /// + /// Lists the contents of the downloads directory. + /// + /// An optional value indicating whether to recursively list subdirectories and files. + /// + /// The request completed successfully. + /// Authentication failed. [HttpGet("downloads/directories")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(FilesystemDirectory), 200)] - public async Task 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(401)] + public Task GetDownloadContentsAsync([FromQuery] bool recursive = false) + => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64SubdirectoryName: null, recursive); + /// + /// Lists the contents of the specified subdirectory within the downloads directory. + /// + /// The relative, base 64 encoded, name of the subdirectory to list. + /// An optional value indicating whether to recursively list subdirectories and files. + /// + /// The request completed successfully. + /// Authentication failed. + /// Access to the specified subdirectory was denied. + /// The specified subdirectory does not exist. [HttpGet("downloads/directories/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(FilesystemDirectory), 200)] - public async Task 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(401)] + [ProducesResponseType(403)] + [ProducesResponseType(404)] + public Task GetDownloadSubdirectoryContentsAsync([FromRoute] string base64SubdirectoryName, [FromQuery] bool recursive = false) + => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64SubdirectoryName, recursive); + /// + /// Deletes the specified subdirectory within the downloads directory. + /// + /// The relative, base 64 encoded, name of the subdirectory to delete. + /// + /// The request completed successfully. + /// Authentication failed. + /// Access to the specified subdirectory was denied. + /// The specified subdirectory does not exist. [HttpDelete("downloads/directories/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Dictionary>), 204)] - public async Task 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(); - } - } + public Task DeleteDownloadSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + => DeleteSubdirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64SubdirectoryName); + /// + /// Deletes the specified file within the downloads directory. + /// + /// The relative, base 64 encoded, name of the file to delete. + /// + /// The request completed successfully. + /// Authentication failed. + /// Access to the specified subdirectory was denied. + /// The specified subdirectory does not exist. [HttpDelete("downloads/files/{base64Filename}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Dictionary>), 204)] - public async Task DeleteDownloadFileAsync([FromRoute] string base64filename) - { - if (!OptionsSnapshot.Value.RemoteFileManagement) - { - return Forbid(); - } - - var decodedFilename = base64filename.FromBase64(); - - try - { - var results = await Files.DeleteFilesAsync(OptionsSnapshot.Value.Directories.Downloads, base64filename); - - return results[decodedFilename].Match( - success => NoContent(), - failure => throw failure); - } - catch (ForbiddenException) - { - return Forbid(); - } - catch (NotFoundException) - { - return NotFound(); - } - } + public Task DeleteDownloadFileAsync([FromRoute] string base64filename) + => DeleteFileAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64filename); + /// + /// Lists the contents of the downloads directory. + /// + /// An optional value indicating whether to recursively list subdirectories and files. + /// + /// The request completed successfully. + /// Authentication failed. [HttpGet("incomplete/directories")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(FilesystemDirectory), 200)] - public async Task GetIncompleteContentsAsync([FromQuery] bool recursive = false) - { - try - { - var response = await Files.ListContentsAsync( - rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, - enumerationOptions: new EnumerationOptions - { - AttributesToSkip = FileAttributes.System, - RecurseSubdirectories = recursive, - }); - - return Ok(response); - } - catch (ForbiddenException) - { - return Forbid(); - } - catch (NotFoundException) - { - return NotFound(); - } - } + public Task GetIncompleteContentsAsync([FromQuery] bool recursive = false) + => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64SubdirectoryName: null, recursive); + /// + /// Lists the contents of the specified subdirectory within the incomplete directory. + /// + /// The relative, base 64 encoded, name of the subdirectory to list. + /// An optional value indicating whether to recursively list subdirectories and files. + /// + /// The request completed successfully. + /// Authentication failed. + /// Access to the specified subdirectory was denied. + /// The specified subdirectory does not exist. [HttpGet("incomplete/directories/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(FilesystemDirectory), 200)] - public async Task GetIncompleteSubdirectoryContentsAsync([FromRoute, Required] string base64SubdirectoryName, [FromQuery] bool recursive = false) + public Task GetIncompleteSubdirectoryContentsAsync([FromRoute, Required] string base64SubdirectoryName, [FromQuery] bool recursive = false) + => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64SubdirectoryName, recursive); + + /// + /// Deletes the specified subdirectory within the downloads directory. + /// + /// The relative, base 64 encoded, name of the subdirectory to delete. + /// + /// The request completed successfully. + /// Authentication failed. + /// Access to the specified subdirectory was denied. + /// The specified subdirectory does not exist. + [HttpDelete("incomplete/directories/{base64SubdirectoryName}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary>), 204)] + public Task DeleteIncompleteSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + => DeleteSubdirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64SubdirectoryName); + + /// + /// Deletes the specified file within the downloads directory. + /// + /// The relative, base 64 encoded, name of the file to delete. + /// + /// The request completed successfully. + /// Authentication failed. + /// Access to the specified subdirectory was denied. + /// The specified subdirectory does not exist. + [HttpDelete("incomplete/files/{base64Filename}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(204)] + public Task DeleteIncompleteFileAsync([FromRoute] string base64filename) + => DeleteFileAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64filename); + + private async Task ListDirectoryAsync(string rootDirectory, string base64SubdirectoryName = null, bool recursive = false) { - var decodedDir = base64SubdirectoryName.FromBase64(); + var requestedDir = (base64SubdirectoryName ?? string.Empty) + .FromBase64() + .Replace('\\', Path.DirectorySeparatorChar) + .Replace('/', Path.DirectorySeparatorChar); + + requestedDir = Path.GetFullPath(Path.Combine(rootDirectory, requestedDir)); + + 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 +196,86 @@ 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>), 204)] - public async Task DeleteIncompleteSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + private async Task 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); + + 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>), 204)] - public async Task DeleteIncompleteFileAsync([FromRoute] string base64filename) + private async Task 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); + + 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(); } } -- cgit v1.2.3