aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2023-07-25 08:14:29 -0500
committerGitHub <noreply@github.com>2023-07-25 08:14:29 -0500
commit76ea31e3556c25df85a9708e3cbbe6062b0abb44 (patch)
tree627b720e05e26aab7b4a3ee86445f01ee6984528
parent50bf39a16261ac4a0ba9f70501c183867d382712 (diff)
parentf3b4f3fc6328c5b56820b93a92d83680e0498833 (diff)
downloadslskd-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
-rw-r--r--src/slskd/Application.cs2
-rw-r--r--src/slskd/Common/Exceptions/UnauthorizedException.cs (renamed from src/slskd/Common/Exceptions/ForbiddenException.cs)22
-rw-r--r--src/slskd/Files/API/FilesController.cs304
-rw-r--r--src/slskd/Files/FileService.cs143
-rw-r--r--src/slskd/Files/IFileService.cs26
-rw-r--r--src/slskd/Files/Types/FilesystemDirectory.cs36
-rw-r--r--src/slskd/Files/Types/FilesystemFile.cs31
-rw-r--r--src/slskd/Program.cs3
-rw-r--r--src/web/package-lock.json133
-rw-r--r--src/web/package.json1
-rw-r--r--src/web/src/components/App.css4
-rw-r--r--src/web/src/components/System/Files/Explorer.js154
-rw-r--r--src/web/src/components/System/Files/Files.css19
-rw-r--r--src/web/src/components/System/Files/index.js30
-rw-r--r--src/web/src/components/System/System.css4
-rw-r--r--src/web/src/components/System/System.js12
-rw-r--r--src/web/src/lib/files.js22
-rw-r--r--src/web/src/lib/util.js4
-rw-r--r--tests/slskd.Tests.Unit/Files/FileServiceTests.cs137
19 files changed, 809 insertions, 278 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 48406931..32eb6cb7 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -280,6 +280,8 @@ namespace slskd
async Task IHostedService.StartAsync(CancellationToken cancellationToken)
{
+ Log.Information("Application started");
+
// if the application shut down "uncleanly", transfers may need to be cleaned up. we deliberately don't allow these
// records to be updated if the application has started to shut down so that we can do this cleanup and properly
// disposition them as having failed due to an application shutdown, instead of some random exception thrown while
diff --git a/src/slskd/Common/Exceptions/ForbiddenException.cs b/src/slskd/Common/Exceptions/UnauthorizedException.cs
index 814b8cfc..a7179c80 100644
--- a/src/slskd/Common/Exceptions/ForbiddenException.cs
+++ b/src/slskd/Common/Exceptions/UnauthorizedException.cs
@@ -1,4 +1,4 @@
-// <copyright file="ForbiddenException.cs" company="slskd Team">
+// <copyright file="UnauthorizedException.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
@@ -22,31 +22,31 @@ namespace slskd
using System.Runtime.Serialization;
/// <summary>
- /// Represents errors that originate when an attempt is made to access a restricted resource.
+ /// Represents errors that originate when a restricted resources is accessed without authorization.
/// </summary>
[ExcludeFromCodeCoverage]
[Serializable]
- public class ForbiddenException : SlskdException
+ public class UnauthorizedException : SlskdException
{
/// <summary>
- /// Initializes a new instance of the <see cref="ForbiddenException"/> class.
+ /// Initializes a new instance of the <see cref="UnauthorizedException"/> class.
/// </summary>
- public ForbiddenException()
+ public UnauthorizedException()
: base()
{
}
/// <summary>
- /// Initializes a new instance of the <see cref="ForbiddenException"/> class with a specified error message.
+ /// Initializes a new instance of the <see cref="UnauthorizedException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
- public ForbiddenException(string message)
+ public UnauthorizedException(string message)
: base(message)
{
}
/// <summary>
- /// Initializes a new instance of the <see cref="ForbiddenException"/> class with a specified error message and a
+ /// Initializes a new instance of the <see cref="UnauthorizedException"/> class with a specified error message and a
/// reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The message that describes the error.</param>
@@ -54,17 +54,17 @@ namespace slskd
/// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no
/// inner exception is specified.
/// </param>
- public ForbiddenException(string message, Exception innerException)
+ public UnauthorizedException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
- /// Initializes a new instance of the <see cref="ForbiddenException"/> class with serialized data.
+ /// Initializes a new instance of the <see cref="UnauthorizedException"/> class with serialized data.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
- protected ForbiddenException(SerializationInfo info, StreamingContext context)
+ protected UnauthorizedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
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
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 060284d8..418a29c2 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -397,6 +397,8 @@ namespace slskd
Log.Information("Invocation ID: {InvocationId}", InvocationId);
Log.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName);
+ Log.Information("Configuring application...");
+
// SQLite must have specific capabilities to function properly. this shouldn't be a concern for shrinkwrapped
// binaries or in Docker, but if someone builds from source weird things can happen.
InitSQLiteOrFailFast();
@@ -465,6 +467,7 @@ namespace slskd
return;
}
+ Log.Information("Configuration complete. Starting application...");
app.Run();
}
catch (Exception ex)
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index b7a8397c..bfe7f2cd 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -27,6 +27,7 @@
"yaml": "^1.10.2"
},
"devDependencies": {
+ "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"@craco/craco": "^7.0.0",
"@semantic-ui-react/craco-less": "^3.0.0",
"@semantic-ui-react/css-patch": "^1.0.0",
@@ -111,9 +112,9 @@
}
},
"node_modules/@babel/core/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -147,9 +148,9 @@
}
},
"node_modules/@babel/eslint-parser/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -214,9 +215,9 @@
}
},
"node_modules/@babel/helper-compilation-targets/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -246,9 +247,9 @@
}
},
"node_modules/@babel/helper-create-class-features-plugin/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -272,9 +273,9 @@
}
},
"node_modules/@babel/helper-create-regexp-features-plugin/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -298,9 +299,9 @@
}
},
"node_modules/@babel/helper-define-polyfill-provider/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -761,10 +762,16 @@
}
},
"node_modules/@babel/plugin-proposal-private-property-in-object": {
- "version": "7.21.0-placeholder-for-preset-env.2",
- "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz",
- "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==",
+ "version": "7.21.11",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.11.tgz",
+ "integrity": "sha512-0QZ8qP/3RLDVBwBFoWAwCtgcDZJVwA5LUJRZU8x2YFfKNuFq161wK3cuGrALu5yiPu+vzwTAg/sMWVNeWeNyaw==",
"dev": true,
+ "dependencies": {
+ "@babel/helper-annotate-as-pure": "^7.18.6",
+ "@babel/helper-create-class-features-plugin": "^7.21.0",
+ "@babel/helper-plugin-utils": "^7.20.2",
+ "@babel/plugin-syntax-private-property-in-object": "^7.14.5"
+ },
"engines": {
"node": ">=6.9.0"
},
@@ -1854,9 +1861,9 @@
}
},
"node_modules/@babel/plugin-transform-runtime/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -2113,10 +2120,22 @@
"@babel/core": "^7.0.0-0"
}
},
+ "node_modules/@babel/preset-env/node_modules/@babel/plugin-proposal-private-property-in-object": {
+ "version": "7.21.0-placeholder-for-preset-env.2",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz",
+ "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
"node_modules/@babel/preset-env/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -5274,9 +5293,9 @@
}
},
"node_modules/babel-loader/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -5352,9 +5371,9 @@
}
},
"node_modules/babel-plugin-polyfill-corejs2/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -7693,9 +7712,9 @@
}
},
"node_modules/eslint-plugin-import/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -7756,9 +7775,9 @@
}
},
"node_modules/eslint-plugin-jsx-a11y/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -7835,9 +7854,9 @@
}
},
"node_modules/eslint-plugin-react/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -8482,9 +8501,9 @@
}
},
"node_modules/find-cache-dir/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -10056,9 +10075,9 @@
}
},
"node_modules/istanbul-lib-instrument/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -10094,9 +10113,9 @@
}
},
"node_modules/istanbul-lib-report/node_modules/semver": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
- "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
@@ -11865,9 +11884,9 @@
}
},
"node_modules/make-dir/node_modules/semver": {
- "version": "5.7.1",
- "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
- "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==",
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
"dev": true,
"optional": true,
"bin": {
@@ -15360,9 +15379,9 @@
}
},
"node_modules/semver": {
- "version": "7.5.1",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz",
- "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==",
+ "version": "7.5.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz",
+ "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==",
"dev": true,
"dependencies": {
"lru-cache": "^6.0.0"
diff --git a/src/web/package.json b/src/web/package.json
index 278123bb..c0fd7657 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -32,6 +32,7 @@
"yaml": "^1.10.2"
},
"devDependencies": {
+ "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"@craco/craco": "^7.0.0",
"@semantic-ui-react/craco-less": "^3.0.0",
"@semantic-ui-react/css-patch": "^1.0.0",
diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css
index ceb60536..1de44557 100644
--- a/src/web/src/components/App.css
+++ b/src/web/src/components/App.css
@@ -259,4 +259,8 @@ body {
.search-list-wrapper {
overflow-x: auto;
+}
+
+.message {
+ padding: 8px 12px 8px 12px !important;
} \ No newline at end of file
diff --git a/src/web/src/components/System/Files/Explorer.js b/src/web/src/components/System/Files/Explorer.js
new file mode 100644
index 00000000..093192bf
--- /dev/null
+++ b/src/web/src/components/System/Files/Explorer.js
@@ -0,0 +1,154 @@
+import React, { useState, useEffect } from 'react';
+
+import {
+ Table,
+ Icon,
+ Modal,
+ Header,
+} from 'semantic-ui-react';
+
+import { list, deleteDirectory, deleteFile } from '../../../lib/files';
+import { formatBytes, formatDate } from '../../../lib/util';
+import { LoaderSegment } from '../../Shared';
+
+const Explorer = ({ root }) => {
+ const [directory, setDirectory] = useState({ files: [], directories: [] });
+ const [subdirectory, setSubdirectory] = useState([]);
+ const [loading, setLoading] = useState(false);
+
+ useEffect(() => {
+ fetch();
+ }, [subdirectory]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ useEffect(() => {
+ setSubdirectory([]);
+ }, [root]);
+
+ const fetch = async () => {
+ setLoading(true);
+ const dir = await list({ root, subdirectory: subdirectory.join('/') });
+ setDirectory(dir);
+ setLoading(false);
+ };
+
+ const select = ({ path }) => {
+ setSubdirectory([...subdirectory, path]);
+ };
+
+ const upOneSubdirectory = () => {
+ const copy = [...subdirectory];
+ copy.pop();
+ setSubdirectory(copy);
+ };
+
+ const FileRow = ({ name, fullName, modifiedAt, length }) => <Table.Row key={fullName}>
+ <Table.Cell><Icon name='file outline'/>{name}</Table.Cell>
+ <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell>
+ <Table.Cell>{length ? formatBytes(length) : ''}</Table.Cell>
+ <Table.Cell>
+ <Modal
+ trigger={
+ <Icon name="trash alternate" color="red" style={{ cursor: 'pointer' }}/>
+ }
+ centered
+ size='small'
+ header={<Header icon='trash alternate' content='Confirm File Delete' />}
+ content={`Are you sure you want to delete file '${fullName}'?`}
+ actions={[
+ 'Cancel',
+ {
+ key: 'done',
+ content: 'Delete',
+ negative: true,
+ onClick: async () => {
+ await deleteFile({ root, path: `${subdirectory.join('/')}/${fullName}`});
+ fetch();
+ },
+ },
+ ]}
+ />
+ </Table.Cell>
+ </Table.Row>;
+
+ const DirectoryRow = ({
+ name,
+ fullName,
+ modifiedAt,
+ onClick = () => {},
+ deletable = true,
+ }) => <Table.Row key={name}>
+ <Table.Cell
+ style={{ cursor: 'pointer' }}
+ onClick={onClick}
+ ><Icon name='folder'/>{name}</Table.Cell>
+ <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell>
+ <Table.Cell></Table.Cell>
+ <Table.Cell>
+ {deletable
+ ? <Modal
+ trigger={
+ <Icon name="trash alternate" color="red" style={{ cursor: 'pointer' }}/>
+ }
+ centered
+ size='small'
+ header={<Header icon='trash alternate' content='Confirm Directory Delete' />}
+ content={`Are you sure you want to delete directory '${fullName}'?`}
+ actions={[
+ 'Cancel',
+ {
+ key: 'done',
+ content: 'Delete',
+ negative: true,
+ onClick: async () => {
+ await deleteDirectory({ root, path: `${subdirectory.join('/')}/${fullName}`});
+ fetch();
+ },
+ },
+ ]}
+ />
+ : ''}
+ </Table.Cell>
+ </Table.Row>;
+
+ if (loading) {
+ return <LoaderSegment/>;
+ }
+
+ const total = directory?.directories?.length + directory?.files?.length ?? 0;
+
+ return (
+ <>
+ <Header size='small' className='explorer-working-directory'>
+ <Icon name='folder open'/>{'/' + root + '/' + subdirectory.join('/')}
+ </Header>
+ <Table size='large' className='unstackable'>
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell className="explorer-list-name">Name</Table.HeaderCell>
+ <Table.HeaderCell className="explorer-list-date">Date Modified</Table.HeaderCell>
+ <Table.HeaderCell className="explorer-list-size">Size</Table.HeaderCell>
+ <Table.HeaderCell className="explorer-list-action"></Table.HeaderCell>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {total === 0
+ ? <Table.Row>
+ <Table.Cell colSpan={99} style={{ opacity: .5, padding: '10px !important', textAlign: 'center' }}>
+ No files or directories
+ </Table.Cell>
+ </Table.Row>
+ : <>
+ {subdirectory.length > 0
+ && <DirectoryRow name=".." fullName=".." onClick={upOneSubdirectory} deletable={false}/>}
+ {directory?.directories?.map(d => <DirectoryRow
+ key={d.name} onClick={() => select({ path: d.name })} {...d}/>)}
+ {directory?.files?.map(f => <FileRow {...f}/>)}
+ </>
+ }
+ </Table.Body>
+ </Table>
+ </>
+ );
+};
+
+export default Explorer; \ No newline at end of file
diff --git a/src/web/src/components/System/Files/Files.css b/src/web/src/components/System/Files/Files.css
new file mode 100644
index 00000000..535809dd
--- /dev/null
+++ b/src/web/src/components/System/Files/Files.css
@@ -0,0 +1,19 @@
+.explorer-working-directory {
+ margin-top: 7px !important;
+}
+
+.explorer-list-name {
+ word-wrap: break-word !important;
+}
+
+.explorer-list-size {
+ width: 100px;
+}
+
+.explorer-list-date {
+ width: 210px;
+}
+
+.explorer-list-action {
+ width: 5px !important;
+} \ No newline at end of file
diff --git a/src/web/src/components/System/Files/index.js b/src/web/src/components/System/Files/index.js
new file mode 100644
index 00000000..cf3dc869
--- /dev/null
+++ b/src/web/src/components/System/Files/index.js
@@ -0,0 +1,30 @@
+import React from 'react';
+import { Tab } from 'semantic-ui-react';
+
+import './Files.css';
+import Explorer from './Explorer';
+
+const Files = () => {
+ const panes = [
+ {
+ route: 'downloads',
+ menuItem: 'Downloads',
+ render: () => <Tab.Pane><Explorer root={'downloads'}/></Tab.Pane>,
+ },
+ {
+ route: 'incomplete',
+ menuItem: 'Incomplete',
+ render: () => <Tab.Pane><Explorer root={'incomplete'}/></Tab.Pane>,
+ },
+ ];
+
+ return (
+ <div>
+ <Tab
+ panes={panes}
+ />
+ </div>
+ );
+};
+
+export default Files; \ No newline at end of file
diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css
index dc32d583..80642687 100644
--- a/src/web/src/components/System/System.css
+++ b/src/web/src/components/System/System.css
@@ -71,4 +71,8 @@
.transfer-header {
margin-bottom: -15px !important;
+}
+
+.file-management-header {
+ margin-bottom: -15px !important;
} \ No newline at end of file
diff --git a/src/web/src/components/System/System.js b/src/web/src/components/System/System.js
index df77ded2..3629082e 100644
--- a/src/web/src/components/System/System.js
+++ b/src/web/src/components/System/System.js
@@ -5,11 +5,12 @@ import { Segment, Tab, Menu, Icon } from 'semantic-ui-react';
import './System.css';
+import { Switch } from '../Shared';
import Info from './Info';
import Logs from './Logs';
import Options from './Options';
import Shares from './Shares';
-import { Switch } from '../Shared';
+import Files from './Files';
import Data from './Data';
const System = ({ state = {}, theme, options = {} }) => {
@@ -52,6 +53,15 @@ const System = ({ state = {}, theme, options = {} }) => {
render: () => <Tab.Pane><Shares state={state.shares} theme={theme}/></Tab.Pane>,
},
{
+ route: 'files',
+ menuItem: {
+ key: 'files',
+ icon: 'folder open',
+ content: 'Files',
+ },
+ render: () => <Tab.Pane className='full-height'><Files theme={theme}/></Tab.Pane>,
+ },
+ {
route: 'data',
menuItem: {
key: 'data',
diff --git a/src/web/src/lib/files.js b/src/web/src/lib/files.js
new file mode 100644
index 00000000..9284fb1b
--- /dev/null
+++ b/src/web/src/lib/files.js
@@ -0,0 +1,22 @@
+import api from './api';
+
+export const list = async ({ root, subdirectory = '' }) => {
+ subdirectory = btoa(subdirectory);
+ const response = (await api.get(`/files/${root}/directories/${subdirectory}`)).data;
+
+ return response;
+};
+
+export const deleteDirectory = async ({ root, path }) => {
+ path = btoa(path);
+ const response = (await api.delete(`/files/${root}/directories/${path}`));
+
+ return response;
+};
+
+export const deleteFile = async ({ root, path }) => {
+ path = btoa(path);
+ const response = (await api.delete(`/files/${root}/files/${path}`));
+
+ return response;
+}; \ No newline at end of file
diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js
index 20653737..974915ed 100644
--- a/src/web/src/lib/util.js
+++ b/src/web/src/lib/util.js
@@ -21,6 +21,10 @@ export const formatBytes = (bytes, decimals = 2) => {
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
+export const formatDate = (date) => {
+ return new Date(date).toLocaleString();
+};
+
export const getFileName = (fullPath) => {
return fullPath.split('\\').pop().split('/').pop();
};
diff --git a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs
new file mode 100644
index 00000000..7c9931ab
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs
@@ -0,0 +1,137 @@
+using Microsoft.Extensions.Options;
+
+namespace slskd.Tests.Unit.Files
+{
+ using System;
+ using System.IO;
+ using System.Threading.Tasks;
+ using Moq;
+ using slskd.Files;
+ using Xunit;
+
+ public class FileServiceTests : IDisposable
+ {
+ public FileServiceTests()
+ {
+ OptionsSnapshotMock = new Mock<IOptionsSnapshot<Options>>();
+
+ Temp = Path.Combine(Path.GetTempPath(), $"slskd.test.{Guid.NewGuid()}");
+ Directory.CreateDirectory(Temp);
+
+ FileService = new FileService(
+ optionsSnapshot: OptionsSnapshotMock.Object);
+ }
+
+ public void Dispose()
+ {
+ Directory.Delete(Temp, recursive: true);
+ }
+
+ private Mock<IOptionsSnapshot<Options>> OptionsSnapshotMock { get; init; }
+ private string Temp { get; init; }
+ private IFileService FileService { get; init; }
+
+ [Fact]
+ public async Task ListContentsAsync_Throws_ArgumentException_Given_Relative_Path()
+ {
+ var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: "../"));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentException>(ex);
+ Assert.Equal("directory", ((ArgumentException)ex).ParamName);
+ }
+
+ [Fact]
+ public async Task ListContentsAsync_Throws_UnauthorizedException_Given_Disallowed_Directory()
+ {
+ OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options
+ {
+ Directories = new Options.DirectoriesOptions
+ {
+ Downloads = Path.Combine(Temp, "downloads"),
+ Incomplete = Path.Combine(Temp, "incomplete"),
+ }
+ });
+
+ var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: Path.Combine(Temp, "foo")));
+
+ Assert.NotNull(ex);
+ Assert.IsType<UnauthorizedException>(ex);
+ }
+
+ [Fact]
+ public async Task ListContentsAsync_Throws_NotFoundException_Given_NonExistent_Directory()
+ {
+ OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options
+ {
+ Directories = new Options.DirectoriesOptions
+ {
+ Downloads = Path.Combine(Temp, "downloads"),
+ Incomplete = Path.Combine(Temp, "incomplete"),
+ }
+ });
+
+ var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: Path.Combine(Temp, "downloads", "foo")));
+
+ Assert.NotNull(ex);
+ Assert.IsType<NotFoundException>(ex);
+ }
+
+ [Fact]
+ public async Task DeleteDirectoriesAsync_Throws_ArgumentException_Given_Relative_Path()
+ {
+ var ex = await Record.ExceptionAsync(() => FileService.DeleteDirectoriesAsync("../foo"));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentException>(ex);
+ Assert.Equal("directories", ((ArgumentException)ex).ParamName);
+ }
+
+ [Fact]
+ public async Task DeleteDirectoriesAsync_Throws_ArgumentException_Given_Disallowed_Path()
+ {
+ OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options
+ {
+ Directories = new Options.DirectoriesOptions
+ {
+ Downloads = Path.Combine(Temp, "downloads"),
+ Incomplete = Path.Combine(Temp, "incomplete"),
+ }
+ });
+
+ var ex = await Record.ExceptionAsync(() => FileService.DeleteDirectoriesAsync(Path.Combine(Temp, "foo")));
+
+ Assert.NotNull(ex);
+ Assert.IsType<UnauthorizedException>(ex);
+ }
+
+ [Fact]
+ public async Task DeleteFilesAsync_Throws_ArgumentException_Given_Relative_Path()
+ {
+ var ex = await Record.ExceptionAsync(() => FileService.DeleteFilesAsync("../foo.bar"));
+
+ Assert.NotNull(ex);
+ Assert.IsType<ArgumentException>(ex);
+ Assert.Equal("files", ((ArgumentException)ex).ParamName);
+ }
+
+ [Fact]
+ public async Task DeleteFilesAsync_Throws_ArgumentException_Given_Disallowed_Path()
+ {
+ OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options
+ {
+ Directories = new Options.DirectoriesOptions
+ {
+ Downloads = Path.Combine(Temp, "downloads"),
+ Incomplete = Path.Combine(Temp, "incomplete"),
+ }
+ });
+
+ var ex = await Record.ExceptionAsync(() => FileService.DeleteFilesAsync(Path.Combine(Temp, "foo")));
+
+ Assert.NotNull(ex);
+ Assert.IsType<UnauthorizedException>(ex);
+ }
+ }
+}
+