diff options
| -rwxr-xr-x[-rw-r--r--] | bin/test | 0 | ||||
| -rw-r--r-- | config/slskd.example.yml | 4 | ||||
| -rw-r--r-- | docs/config.md | 25 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 85 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 36 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Core/Options/WebOptions.CorsOptionsTests.cs | 261 |
6 files changed, 404 insertions, 7 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 1edcb919..1f7e1a46 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -171,6 +171,10 @@ # key: <some example string between 16 and 255 characters> # role: readonly # readonly, readwrite, administrator # cidr: 0.0.0.0/0,::/0 +# cors: +# allowed_origins: +# - https://app.example.com +# allow_credentials: false # retention: # search: 10080 # 7 days, in minutes # transfers: diff --git a/docs/config.md b/docs/config.md index d864458b..9a8ae564 100644 --- a/docs/config.md +++ b/docs/config.md @@ -992,6 +992,31 @@ web: cidr: 0.0.0.0/0,::/0 ``` +## Cross-Origin Resource Sharing (CORS) + +[CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) controls whether a web page served from one origin (scheme, host, and port) is allowed by the browser to make requests to the API from another origin. This only applies to requests made by a browser; scripts, command-line tools, and other applications that call the API directly are not affected. + +Most users don't need to change these options. The web UI is served by the application itself, so requests it makes are not cross-origin. A common reason to configure CORS is to call the API from a custom web page or dashboard hosted somewhere else, such as `https://dashboard.example.com`. + +By default, the list of allowed origins is empty, which allows requests from any origin. A list containing a single wildcard (`*`) entry has the same effect. To restrict access, supply a list of the specific origins that should be allowed. + +Credentials (cookies and HTTP authentication) are not allowed in CORS requests by default. Credentials can only be allowed if a list of specific origins is supplied; attempting to allow credentials while all origins are allowed (an empty list or a wildcard) will cause a validation error. Note that JWTs and API keys are sent in headers and don't require this option. + +| Command-Line | Environment Variable | Description | +| --------------------------- | ------------------------------ | --------------------------------------------------- | +| `--cors-allowed-origins` | `SLSKD_CORS_ALLOWED_ORIGINS` | The list of allowed CORS origins | +| `--cors-allow-credentials` | `SLSKD_CORS_ALLOW_CREDENTIALS` | Determines whether CORS requests may include credentials | + +#### **YAML** +```yaml +web: + cors: + allowed_origins: + - https://dashboard.example.com + - http://localhost:3000 + allow_credentials: false +``` + # Filters A number of filters can be configured to control various aspects of how the application interacts with the Soulseek network. diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 1f6ceac2..8c22eab7 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2093,6 +2093,12 @@ namespace slskd public WebAuthenticationOptions Authentication { get; init; } = new WebAuthenticationOptions(); /// <summary> + /// Gets CORS options. + /// </summary> + [Validate] + public CorsOptions Cors { get; init; } = new CorsOptions(); + + /// <summary> /// Authentication options. /// </summary> public class WebAuthenticationOptions : IValidatableObject @@ -2385,6 +2391,85 @@ namespace slskd public string Password { get; init; } } } + + /// <summary> + /// CORS options. + /// </summary> + public class CorsOptions : IValidatableObject + { + /// <summary> + /// Gets the list of CORS allowed origins. + /// </summary> + [Argument(default, "cors-allowed-origins")] + [EnvironmentVariable("CORS_ALLOWED_ORIGINS")] + [Description("list of allowed CORS origins")] + [RequiresRestart] + public string[] AllowedOrigins { get; init; } = null; + + /// <summary> + /// Gets a value indicating whether CORS requests may include credentials. + /// </summary> + [Argument(default, "cors-allow-credentials")] + [EnvironmentVariable("CORS_ALLOW_CREDENTIALS")] + [Description("allow CORS credentials for allowed origins")] + [RequiresRestart] + public bool AllowCredentials { get; init; } = false; + + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + if (AllowedOrigins?.Contains("*") ?? false) + { + if (AllowedOrigins.Count(x => x == "*") > 1) + { + yield return new ValidationResult("Specify only one wildcard origin (\"*\")"); + } + + if (AllowedOrigins.Any(x => x != "*")) + { + yield return new ValidationResult("Specifying wildcard origin (\"*\") with other origins has no effect; remove either the wildcard or all non-wildcard origins"); + } + } + + foreach (var origin in (AllowedOrigins ?? []).Where(o => o != "*")) + { + if (origin.Contains('*')) + { + yield return new ValidationResult($"Origin {origin} must not contain a wildcard"); + } + + if (!Uri.TryCreate(origin, default(UriCreationOptions), out var o)) + { + yield return new ValidationResult($"Origin {origin} is not a valid URI"); + continue; + } + + if (!o.IsAbsoluteUri) + { + yield return new ValidationResult($"Origin {origin} must be an absolute URI"); + } + + string[] validSchemes = ["http", "https"]; + + if (!validSchemes.Contains(o.Scheme, StringComparer.OrdinalIgnoreCase)) + { + yield return new ValidationResult($"Origin {origin} must use the HTTP or HTTPS scheme"); + } + + var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicyBuilder().WithOrigins(origin).Build(); + var browserOrigin = $"{o.Scheme}://{o.IdnHost}{(o.IsDefaultPort ? string.Empty : $":{o.Port}")}"; + + if (!policy.IsOriginAllowed(browserOrigin)) + { + yield return new ValidationResult($"Origin {origin} is malformed and will never match a browser request; rewrite it as {browserOrigin}"); + } + } + + if ((AllowedOrigins is null || AllowedOrigins.Length == 0 || AllowedOrigins.Contains("*")) && AllowCredentials) + { + yield return new ValidationResult("Credentials can not be allowed while allowing all origins"); + } + } + } } /// <summary> diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 794a33eb..4b985061 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -842,12 +842,34 @@ namespace slskd private static IServiceCollection ConfigureAspDotNetServices(this IServiceCollection services) { - services.AddCors(options => options.AddPolicy("AllowAll", builder => builder - .SetIsOriginAllowed((host) => true) - .AllowAnyHeader() - .AllowAnyMethod() - .AllowCredentials() - .WithExposedHeaders("X-URL-Base", "X-Total-Count"))); + services.AddCors(options => options.AddPolicy(nameof(OptionsAtStartup.Web.Cors), builder => + { + var cors = OptionsAtStartup.Web.Cors; + var origins = (cors.AllowedOrigins ?? []) + .Where(origin => !string.IsNullOrWhiteSpace(origin)) + .Select(origin => origin.Trim().TrimEnd('/')) + .ToArray(); + + builder + .AllowAnyHeader() + .AllowAnyMethod() + .DisallowCredentials() + .WithExposedHeaders("X-URL-Base", "X-Total-Count"); + + if (origins.Length > 0 && !origins.Contains("*")) + { + builder.WithOrigins(origins); + + if (cors.AllowCredentials) + { + builder.AllowCredentials(); + } + } + else + { + builder.SetIsOriginAllowed((origin) => true); // allow any origin + } + })); services.ConfigureTelemetry(); @@ -1076,7 +1098,7 @@ namespace slskd await context.Response.WriteAsJsonAsync(context.Features.Get<IExceptionHandlerPathFeature>().Error.Message); })); - app.UseCors("AllowAll"); + app.UseCors(nameof(OptionsAtStartup.Web.Cors)); if (OptionsAtStartup.Web.Https.Force) { diff --git a/tests/slskd.Tests.Unit/Core/Options/WebOptions.CorsOptionsTests.cs b/tests/slskd.Tests.Unit/Core/Options/WebOptions.CorsOptionsTests.cs new file mode 100644 index 00000000..782af616 --- /dev/null +++ b/tests/slskd.Tests.Unit/Core/Options/WebOptions.CorsOptionsTests.cs @@ -0,0 +1,261 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using Xunit; +using static slskd.Options; + +namespace slskd.Tests.Unit.Core.Options; + +using CorsOptions = WebOptions.CorsOptions; + +public class CorsOptionsTests +{ + private static List<ValidationResult> Validate(CorsOptions options) + { + var context = new ValidationContext(options); + var results = new List<ValidationResult>(); + Validator.TryValidateObject(options, context, results, validateAllProperties: true); + return results; + } + + public class AllowedOrigins + { + [Fact] + public void Null_origins_produces_no_errors() + { + var options = new CorsOptions { AllowedOrigins = null }; + Assert.Empty(Validate(options)); + } + + [Fact] + public void Empty_origins_produces_no_errors() + { + var options = new CorsOptions { AllowedOrigins = [] }; + Assert.Empty(Validate(options)); + } + + [Fact] + public void Single_wildcard_produces_no_errors() + { + var options = new CorsOptions { AllowedOrigins = ["*"] }; + Assert.Empty(Validate(options)); + } + + [Fact] + public void Multiple_wildcards_produces_error() + { + var options = new CorsOptions { AllowedOrigins = ["*", "*"] }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains("only one wildcard", results[0].ErrorMessage); + } + + [Theory] + [InlineData("http://localhost:3000")] + [InlineData("https://example.com")] + [InlineData("https://sub.example.com")] + [InlineData("https://example.com:8443")] + [InlineData("http://192.168.1.10:5030")] + [InlineData("HTTPS://EXAMPLE.COM")] + public void Valid_origin_produces_no_errors(string origin) + { + var options = new CorsOptions { AllowedOrigins = [origin] }; + Assert.Empty(Validate(options)); + } + + [Fact] + public void Wildcard_and_valid_origin_produces_error() + { + var options = new CorsOptions { AllowedOrigins = ["*", "https://example.com"] }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains("other origins", results[0].ErrorMessage); + } + + [Fact] + public void Valid_origin_and_wildcard_produces_error() + { + var options = new CorsOptions { AllowedOrigins = ["https://example.com", "*"] }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains("other origins", results[0].ErrorMessage); + } + + [Fact] + public void Multiple_wildcards_and_valid_origin_produces_both_errors() + { + var options = new CorsOptions { AllowedOrigins = ["*", "https://example.com", "*"] }; + var results = Validate(options); + Assert.Equal(2, results.Count); + Assert.Contains(results, r => r.ErrorMessage.Contains("only one wildcard")); + Assert.Contains(results, r => r.ErrorMessage.Contains("other origins")); + } + + [Fact] + public void Wildcard_and_invalid_origin_produces_errors_for_both() + { + var options = new CorsOptions { AllowedOrigins = ["*", "ftp://example.com"] }; + var results = Validate(options); + Assert.Equal(2, results.Count); + Assert.Contains(results, r => r.ErrorMessage.Contains("other origins")); + Assert.Contains(results, r => r.ErrorMessage.Contains("HTTP or HTTPS")); + } + + [Theory] + [InlineData("https://*.example.com")] + [InlineData("https://example.*")] + public void Origin_containing_wildcard_produces_error(string origin) + { + var options = new CorsOptions { AllowedOrigins = [origin] }; + var results = Validate(options); + Assert.NotEmpty(results); + Assert.Contains(results, r => r.ErrorMessage.Contains(origin) && r.ErrorMessage.Contains("wildcard")); + } + + [Theory] + [InlineData("foo")] + [InlineData("example.com")] + [InlineData("null")] + [InlineData("")] + [InlineData(" ")] + public void Invalid_uri_produces_error(string origin) + { + var options = new CorsOptions { AllowedOrigins = [origin] }; + Assert.NotEmpty(Validate(options)); + } + + [Theory] + [InlineData("ftp://example.com")] + [InlineData("ws://example.com")] + [InlineData("file:///c:/foo")] + public void Non_http_scheme_produces_error(string origin) + { + var options = new CorsOptions { AllowedOrigins = [origin] }; + var results = Validate(options); + Assert.Contains(results, r => r.ErrorMessage.Contains("HTTP or HTTPS")); + } + + [Theory] + [InlineData("https://example.com/")] + [InlineData("https://example.com/app")] + [InlineData("https://example.com?foo=bar")] + [InlineData("https://example.com#foo")] + [InlineData("https://example.com:443")] + [InlineData("http://example.com:80")] + [InlineData("https://alice@example.com")] + [InlineData("https://alice:secret@example.com")] + [InlineData("https://example.com@evil.com")] + public void Origin_that_never_matches_a_browser_request_produces_error(string origin) + { + var options = new CorsOptions { AllowedOrigins = [origin] }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains(origin, results[0].ErrorMessage); + } + + [Fact] + public void Malformed_origin_error_suggests_browser_origin() + { + var options = new CorsOptions { AllowedOrigins = ["https://example.com/"] }; + var results = Validate(options); + Assert.Single(results); + Assert.EndsWith("https://example.com", results[0].ErrorMessage); + } + + [Fact] + public void Internationalized_origin_produces_no_errors() + { + var options = new CorsOptions { AllowedOrigins = ["https://münchen.de"] }; + Assert.Empty(Validate(options)); + } + + [Fact] + public void Multiple_invalid_origins_each_produce_an_error() + { + var options = new CorsOptions { AllowedOrigins = ["https://example.com/", "ftp://example.com"] }; + Assert.Equal(2, Validate(options).Count); + } + + [Fact] + public void Mixed_valid_and_invalid_origins_only_errors_on_invalid() + { + var options = new CorsOptions { AllowedOrigins = ["https://example.com", "https://other.com/"] }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains("https://other.com/", results[0].ErrorMessage); + } + } + + public class AllowCredentials + { + [Fact] + public void Credentials_with_null_origins_produces_error() + { + var options = new CorsOptions { AllowedOrigins = null, AllowCredentials = true }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains("Credentials", results[0].ErrorMessage); + } + + [Fact] + public void Credentials_with_empty_origins_produces_error() + { + var options = new CorsOptions { AllowedOrigins = [], AllowCredentials = true }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains("Credentials", results[0].ErrorMessage); + } + + [Fact] + public void Credentials_with_wildcard_origin_produces_error() + { + var options = new CorsOptions { AllowedOrigins = ["*"], AllowCredentials = true }; + var results = Validate(options); + Assert.Single(results); + Assert.Contains("Credentials", results[0].ErrorMessage); + } + + [Fact] + public void Credentials_with_wildcard_and_specific_origin_produces_error() + { + var options = new CorsOptions { AllowedOrigins = ["*", "https://example.com"], AllowCredentials = true }; + var results = Validate(options); + Assert.Contains(results, r => r.ErrorMessage.Contains("Credentials")); + } + + [Fact] + public void Credentials_with_multiple_wildcards_produces_error() + { + var options = new CorsOptions { AllowedOrigins = ["*", "*"], AllowCredentials = true }; + var results = Validate(options); + Assert.Contains(results, r => r.ErrorMessage.Contains("Credentials")); + } + + [Fact] + public void Credentials_with_specific_origins_produces_no_errors() + { + var options = new CorsOptions { AllowedOrigins = ["https://example.com", "http://localhost:3000"], AllowCredentials = true }; + Assert.Empty(Validate(options)); + } + + [Fact] + public void No_credentials_with_null_origins_produces_no_errors() + { + var options = new CorsOptions { AllowedOrigins = null, AllowCredentials = false }; + Assert.Empty(Validate(options)); + } + + [Fact] + public void No_credentials_with_empty_origins_produces_no_errors() + { + var options = new CorsOptions { AllowedOrigins = [], AllowCredentials = false }; + Assert.Empty(Validate(options)); + } + + [Fact] + public void No_credentials_with_wildcard_origin_produces_no_errors() + { + var options = new CorsOptions { AllowedOrigins = ["*"], AllowCredentials = false }; + Assert.Empty(Validate(options)); + } + } +} |
