aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/slskd/Common/Exceptions/UnauthorizedException.cs72
-rw-r--r--src/slskd/Files/FileService.cs22
-rw-r--r--src/slskd/Files/IFileService.cs6
-rw-r--r--tests/slskd.Tests.Unit/Files/FileServiceTests.cs137
4 files changed, 223 insertions, 14 deletions
diff --git a/src/slskd/Common/Exceptions/UnauthorizedException.cs b/src/slskd/Common/Exceptions/UnauthorizedException.cs
new file mode 100644
index 00000000..a7179c80
--- /dev/null
+++ b/src/slskd/Common/Exceptions/UnauthorizedException.cs
@@ -0,0 +1,72 @@
+// <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
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Runtime.Serialization;
+
+ /// <summary>
+ /// Represents errors that originate when a restricted resources is accessed without authorization.
+ /// </summary>
+ [ExcludeFromCodeCoverage]
+ [Serializable]
+ public class UnauthorizedException : SlskdException
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UnauthorizedException"/> class.
+ /// </summary>
+ public UnauthorizedException()
+ : base()
+ {
+ }
+
+ /// <summary>
+ /// 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 UnauthorizedException(string message)
+ : base(message)
+ {
+ }
+
+ /// <summary>
+ /// 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>
+ /// <param name="innerException">
+ /// 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 UnauthorizedException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+
+ /// <summary>
+ /// 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 UnauthorizedException(SerializationInfo info, StreamingContext context)
+ : base(info, context)
+ {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs
index 2324a492..c820220f 100644
--- a/src/slskd/Files/FileService.cs
+++ b/src/slskd/Files/FileService.cs
@@ -65,7 +65,7 @@ namespace slskd.Files
/// 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="SecurityException">Thrown if a specified directory is restricted.</exception>
+ /// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception>
public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories)
{
if (directories.Any(directory => Path.GetFullPath(directory) != directory))
@@ -84,7 +84,7 @@ namespace slskd.Files
// 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 SecurityException("Only application-controlled directories can be deleted");
+ throw new UnauthorizedException("Only application-controlled directories can be deleted");
}
await Task.Yield();
@@ -104,9 +104,9 @@ namespace slskd.Files
{
results.Add(directory, new NotFoundException($"The directory '{directory}' does not exist"));
}
- catch (UnauthorizedAccessException)
+ catch (UnauthorizedAccessException ex)
{
- results.Add(directory, new SecurityException());
+ results.Add(directory, new UnauthorizedException($"Deletion of the directory '{directory}' was denied: {ex.Message}", ex));
}
catch (Exception ex)
{
@@ -128,7 +128,7 @@ namespace slskd.Files
/// <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="SecurityException">Thrown if a specified file is restricted.</exception>
+ /// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception>
public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files)
{
if (files.Any(file => Path.GetFullPath(file) != file))
@@ -142,7 +142,7 @@ namespace slskd.Files
// 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 SecurityException("Only files in application-controlled directories can be deleted");
+ throw new UnauthorizedException("Only files in application-controlled directories can be deleted");
}
await Task.Yield();
@@ -160,9 +160,9 @@ namespace slskd.Files
{
results.Add(file, new NotFoundException($"The file '{file}' does not exist"));
}
- catch (UnauthorizedAccessException)
+ catch (UnauthorizedAccessException ex)
{
- results.Add(file, new SecurityException());
+ results.Add(file, new UnauthorizedException($"Deletion of the file '{file}' was denied: {ex.Message}", ex));
}
catch (Exception ex)
{
@@ -181,7 +181,7 @@ namespace slskd.Files
/// <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="SecurityException">Thrown if the specified root directory is restricted.</exception>
+ /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception>
public async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null)
{
if (Path.GetFullPath(directory) != directory)
@@ -192,7 +192,7 @@ namespace slskd.Files
// 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 SecurityException($"For security reasons, only application-controlled directories can be deleted");
+ throw new UnauthorizedException($"Only application-controlled directories can be deleted");
}
if (!Directory.Exists(directory))
@@ -233,7 +233,7 @@ namespace slskd.Files
}
catch (UnauthorizedAccessException ex)
{
- throw new SecurityException($"Access to '{directory}' was denied", 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 63b5f1a3..89d4ce76 100644
--- a/src/slskd/Files/IFileService.cs
+++ b/src/slskd/Files/IFileService.cs
@@ -43,7 +43,7 @@ namespace slskd.Files
/// 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="SecurityException">Thrown if a specified directory is restricted.</exception>
+ /// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception>
Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories);
/// <summary>
@@ -57,7 +57,7 @@ namespace slskd.Files
/// <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="SecurityException">Thrown if a specified file is restricted.</exception>
+ /// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception>
Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files);
/// <summary>
@@ -68,7 +68,7 @@ namespace slskd.Files
/// <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="SecurityException">Thrown if the specified root directory is restricted.</exception>
+ /// <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/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);
+ }
+ }
+}
+