diff --git a/ErsatzTV.Core/FileSystemLayout.cs b/ErsatzTV.Core/FileSystemLayout.cs index 13e9f42ee..898c8d32b 100644 --- a/ErsatzTV.Core/FileSystemLayout.cs +++ b/ErsatzTV.Core/FileSystemLayout.cs @@ -25,6 +25,8 @@ public static class FileSystemLayout public static readonly string JellyfinSecretsPath; public static readonly string EmbySecretsPath; + public static readonly string ApiKeyPath; + public static readonly string FFmpegReportsFolder; public static readonly string SearchIndexFolder; public static readonly string TempFilePoolFolder; @@ -150,6 +152,8 @@ public static class FileSystemLayout JellyfinSecretsPath = Path.Combine(AppDataFolder, "jellyfin-secrets.json"); EmbySecretsPath = Path.Combine(AppDataFolder, "emby-secrets.json"); + ApiKeyPath = Path.Combine(AppDataFolder, "api.key"); + FFmpegReportsFolder = Path.Combine(AppDataFolder, "ffmpeg-reports"); SearchIndexFolder = Path.Combine(AppDataFolder, "search-index"); TempFilePoolFolder = Path.Combine(AppDataFolder, "temp-pool"); diff --git a/ErsatzTV.Tests/Controllers/ApiControllerSecurityTests.cs b/ErsatzTV.Tests/Controllers/ApiControllerSecurityTests.cs index fcfc085a7..8b335b2b7 100644 --- a/ErsatzTV.Tests/Controllers/ApiControllerSecurityTests.cs +++ b/ErsatzTV.Tests/Controllers/ApiControllerSecurityTests.cs @@ -93,6 +93,38 @@ public class ApiControllerSecurityTests ApiKeyAuthorizationFilterIsGlobal.ShouldBeTrue(); } + [Test] + public void Sensitive_Read_Controllers_Should_Require_Api_Key() + { + // These GET surfaces disclose secrets/paths or trigger work; they must stay gated even if an + // operator disables Api:RequireKeyForReads (issue #282). Asserted reflectively so the tier + // can't silently drop the attribute. + Type[] sensitiveControllers = + [ + typeof(TroubleshootController), + typeof(LogsController), + typeof(SettingsController), + typeof(MaintenanceController) + ]; + + foreach (Type controllerType in sensitiveControllers) + { + controllerType.GetCustomAttributes(inherit: true).Any() + .ShouldBeTrue($"{controllerType.Name} must carry [RequiresApiKey]"); + } + } + + [Test] + public void ScannerController_Should_Be_Localhost_Only() + { + // The scanner callback is exempt from the API key (guessable scan-id GUID); a loopback check + // replaces the GUID as the real gate (issue #285). + typeof(ScannerController) + .GetCustomAttributes(inherit: true) + .Any() + .ShouldBeTrue(); + } + private static bool IsGloballyProtected() => ApiKeyAuthorizationFilterIsGlobal; private static bool IsApiKeyAuthorizationFilterRegisteredGlobally() diff --git a/ErsatzTV.Tests/Filters/ApiKeyAuthorizationFilterTests.cs b/ErsatzTV.Tests/Filters/ApiKeyAuthorizationFilterTests.cs index 3e04cd1fe..61d0cb1b5 100644 --- a/ErsatzTV.Tests/Filters/ApiKeyAuthorizationFilterTests.cs +++ b/ErsatzTV.Tests/Filters/ApiKeyAuthorizationFilterTests.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using ErsatzTV.Filters; +using ErsatzTV.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.Configuration; using NUnit.Framework; using Shouldly; @@ -14,11 +14,20 @@ namespace ErsatzTV.Tests.Filters; [TestFixture] public class ApiKeyAuthorizationFilterTests { + private const string Key = "secret"; + + private sealed class FakeApiKeyProvider(string apiKey, bool requireKeyForReads) : IApiKeyProvider + { + public string ApiKey { get; } = apiKey; + public bool RequireKeyForReads { get; } = requireKeyForReads; + } + private static AuthorizationFilterContext MakeContext( string method, string? apiKeyHeader, string path = "/api/channels", - bool skipApiKeyAuthorization = false) + bool skipApiKeyAuthorization = false, + bool requiresApiKey = false) { var httpContext = new DefaultHttpContext(); httpContext.Request.Method = method; @@ -28,92 +37,123 @@ public class ApiKeyAuthorizationFilterTests httpContext.Request.Headers[ApiKeyAuthorizationFilter.HeaderName] = apiKeyHeader; } - var actionDescriptor = new ActionDescriptor(); + var metadata = new List(); if (skipApiKeyAuthorization) { - actionDescriptor.EndpointMetadata = [new SkipApiKeyAuthorizationAttribute()]; + metadata.Add(new SkipApiKeyAuthorizationAttribute()); } + if (requiresApiKey) + { + metadata.Add(new RequiresApiKeyAttribute()); + } + + var actionDescriptor = new ActionDescriptor { EndpointMetadata = metadata }; var actionContext = new ActionContext(httpContext, new RouteData(), actionDescriptor); return new AuthorizationFilterContext(actionContext, new List()); } - private static ApiKeyAuthorizationFilter MakeFilter(string? configuredKey) - { - var settings = new Dictionary(); - if (configuredKey is not null) - { - settings[ApiKeyAuthorizationFilter.ConfigurationKey] = configuredKey; - } + private static ApiKeyAuthorizationFilter MakeFilter(bool requireKeyForReads = true) => + new(new FakeApiKeyProvider(Key, requireKeyForReads)); - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - return new ApiKeyAuthorizationFilter(configuration); - } - - [Test] - public void Should_Allow_When_Key_Not_Configured() + private static void ShouldBeUnauthorized(AuthorizationFilterContext context) { - AuthorizationFilterContext context = MakeContext("POST", apiKeyHeader: null); - MakeFilter(configuredKey: null).OnAuthorization(context); - context.Result.ShouldBeNull(); - } - - [Test] - public void Should_Allow_When_Key_Configured_Empty() - { - AuthorizationFilterContext context = MakeContext("POST", apiKeyHeader: null); - MakeFilter(configuredKey: string.Empty).OnAuthorization(context); - context.Result.ShouldBeNull(); - } - - [Test] - public void Should_Reject_Mutating_Request_When_Key_Configured_And_Header_Missing() - { - AuthorizationFilterContext context = MakeContext("POST", apiKeyHeader: null); - MakeFilter(configuredKey: "secret").OnAuthorization(context); var result = context.Result.ShouldBeOfType(); var problemDetails = result.Value.ShouldBeOfType(); problemDetails.Status.ShouldBe(StatusCodes.Status401Unauthorized); problemDetails.Title.ShouldBe("Unauthorized"); } + // ---- writes are always fail-closed (issue #280) ---- + + [Test] + public void Should_Reject_Mutating_Request_When_Header_Missing() + { + AuthorizationFilterContext context = MakeContext("POST", apiKeyHeader: null); + MakeFilter().OnAuthorization(context); + ShouldBeUnauthorized(context); + } + [Test] public void Should_Reject_Mutating_Request_When_Key_Wrong() { AuthorizationFilterContext context = MakeContext("DELETE", apiKeyHeader: "wrong"); - MakeFilter(configuredKey: "secret").OnAuthorization(context); - var result = context.Result.ShouldBeOfType(); - var problemDetails = result.Value.ShouldBeOfType(); - problemDetails.Status.ShouldBe(StatusCodes.Status401Unauthorized); - problemDetails.Title.ShouldBe("Unauthorized"); + MakeFilter().OnAuthorization(context); + ShouldBeUnauthorized(context); } [Test] public void Should_Allow_Mutating_Request_When_Key_Correct() { - AuthorizationFilterContext context = MakeContext("PUT", apiKeyHeader: "secret"); - MakeFilter(configuredKey: "secret").OnAuthorization(context); + AuthorizationFilterContext context = MakeContext("PUT", apiKeyHeader: Key); + MakeFilter().OnAuthorization(context); context.Result.ShouldBeNull(); } [Test] - public void Should_Allow_Get_Request_Even_When_Key_Configured() + public void Should_Reject_Mutating_Request_Even_When_Reads_Not_Required() + { + AuthorizationFilterContext context = MakeContext("POST", apiKeyHeader: null); + MakeFilter(requireKeyForReads: false).OnAuthorization(context); + ShouldBeUnauthorized(context); + } + + // ---- reads gated by Api:RequireKeyForReads (default true, issue #282) ---- + + [Test] + public void Should_Reject_Read_When_Reads_Required_And_Header_Missing() { AuthorizationFilterContext context = MakeContext("GET", apiKeyHeader: null); - MakeFilter(configuredKey: "secret").OnAuthorization(context); + MakeFilter(requireKeyForReads: true).OnAuthorization(context); + ShouldBeUnauthorized(context); + } + + [Test] + public void Should_Allow_Read_When_Reads_Required_And_Key_Correct() + { + AuthorizationFilterContext context = MakeContext("GET", apiKeyHeader: Key); + MakeFilter(requireKeyForReads: true).OnAuthorization(context); context.Result.ShouldBeNull(); } [Test] - public void Should_Allow_Non_Api_Mutating_Request_Even_When_Key_Configured() + public void Should_Allow_Read_When_Reads_Not_Required() + { + AuthorizationFilterContext context = MakeContext("GET", apiKeyHeader: null); + MakeFilter(requireKeyForReads: false).OnAuthorization(context); + context.Result.ShouldBeNull(); + } + + // ---- the sensitive-read tier stays gated even with reads open ([RequiresApiKey]) ---- + + [Test] + public void Should_Reject_Read_On_RequiresApiKey_Endpoint_Even_When_Reads_Not_Required() + { + AuthorizationFilterContext context = MakeContext("GET", apiKeyHeader: null, requiresApiKey: true); + MakeFilter(requireKeyForReads: false).OnAuthorization(context); + ShouldBeUnauthorized(context); + } + + [Test] + public void Should_Allow_Read_On_RequiresApiKey_Endpoint_When_Key_Correct() + { + AuthorizationFilterContext context = MakeContext("GET", apiKeyHeader: Key, requiresApiKey: true); + MakeFilter(requireKeyForReads: false).OnAuthorization(context); + context.Result.ShouldBeNull(); + } + + // ---- scope / bypass rules ---- + + [Test] + public void Should_Allow_Non_Api_Mutating_Request() { AuthorizationFilterContext context = MakeContext("POST", apiKeyHeader: null, path: "/iptv/channels.m3u"); - MakeFilter(configuredKey: "secret").OnAuthorization(context); + MakeFilter().OnAuthorization(context); context.Result.ShouldBeNull(); } [Test] - public void Should_Allow_Api_Mutating_Request_When_Endpoint_Skips_Api_Key_Authorization() + public void Should_Allow_When_Endpoint_Skips_Api_Key_Authorization() { AuthorizationFilterContext context = MakeContext( "POST", @@ -121,7 +161,15 @@ public class ApiKeyAuthorizationFilterTests path: "/api/scan/0f8fad5b-d9cb-469f-a165-70867728950e/progress", skipApiKeyAuthorization: true); - MakeFilter(configuredKey: "secret").OnAuthorization(context); + MakeFilter().OnAuthorization(context); + context.Result.ShouldBeNull(); + } + + [Test] + public void Should_Allow_Cors_Preflight_Options_Without_Key() + { + AuthorizationFilterContext context = MakeContext("OPTIONS", apiKeyHeader: null); + MakeFilter(requireKeyForReads: true).OnAuthorization(context); context.Result.ShouldBeNull(); } } diff --git a/ErsatzTV.Tests/Services/ApiKeyProviderTests.cs b/ErsatzTV.Tests/Services/ApiKeyProviderTests.cs new file mode 100644 index 000000000..a78a906f7 --- /dev/null +++ b/ErsatzTV.Tests/Services/ApiKeyProviderTests.cs @@ -0,0 +1,144 @@ +using System.Collections.Generic; +using System.IO; +using ErsatzTV.Services; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging.Abstractions; +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Tests.Services; + +[TestFixture] +public class ApiKeyProviderTests +{ + private DirectoryInfo _tempDir = null!; + private string _keyPath = null!; + + [SetUp] + public void SetUp() + { + _tempDir = Directory.CreateTempSubdirectory("etv-apikey-tests"); + _keyPath = Path.Combine(_tempDir.FullName, "api.key"); + } + + [TearDown] + public void TearDown() + { + try + { + _tempDir.Delete(recursive: true); + } + catch + { + // best-effort cleanup + } + } + + private static IConfiguration Config(params (string Key, string Value)[] settings) + { + var dict = new Dictionary(); + foreach ((string key, string value) in settings) + { + dict[key] = value; + } + + return new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); + } + + [Test] + public void Configured_WriteKey_Takes_Precedence_And_Does_Not_Write_A_File() + { + IConfiguration config = Config((ApiKeyProvider.WriteKeyConfigurationKey, " from-config ")); + + string key = ApiKeyProvider.ResolveKey(config, _keyPath, NullLogger.Instance); + + key.ShouldBe("from-config"); // trimmed + File.Exists(_keyPath).ShouldBeFalse(); + } + + [Test] + public void Existing_Key_File_Is_Loaded() + { + File.WriteAllText(_keyPath, " persisted-key \n"); + + string key = ApiKeyProvider.ResolveKey(Config(), _keyPath, NullLogger.Instance); + + key.ShouldBe("persisted-key"); + } + + [Test] + public void Empty_Key_File_Is_Regenerated() + { + File.WriteAllText(_keyPath, " \n"); + + string key = ApiKeyProvider.ResolveKey(Config(), _keyPath, NullLogger.Instance); + + key.ShouldMatch("^[0-9a-f]{64}$"); + File.ReadAllText(_keyPath).Trim().ShouldBe(key); // the empty file was overwritten + } + + [Test] + public void Generates_And_Persists_A_256_Bit_Key_When_None_Exists() + { + string key = ApiKeyProvider.ResolveKey(Config(), _keyPath, NullLogger.Instance); + + key.ShouldMatch("^[0-9a-f]{64}$"); // 32 bytes hex + File.Exists(_keyPath).ShouldBeTrue(); + File.ReadAllText(_keyPath).Trim().ShouldBe(key); + } + + [Test] + [Platform(Exclude = "Win", Reason = "Unix file mode is not applicable on Windows")] + public void Persisted_Key_File_Is_Owner_Read_Write_Only() + { + ApiKeyProvider.ResolveKey(Config(), _keyPath, NullLogger.Instance); + + UnixFileMode mode = File.GetUnixFileMode(_keyPath); + mode.ShouldBe(UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + + [Test] + public void Unreadable_Existing_Key_File_Throws_Rather_Than_Overwriting() + { + // The headline #285/L3 behavior: a present-but-unreadable key file must NOT be silently + // regenerated (that would invalidate every client's key). Inject a reader that throws to + // simulate a permission error portably (a real chmod-000 no-ops under root in CI). + File.WriteAllText(_keyPath, "good-key"); + + Should.Throw(() => + ApiKeyProvider.ResolveKey(Config(), _keyPath, NullLogger.Instance, _ => throw new IOException("boom"))); + + File.ReadAllText(_keyPath).ShouldBe("good-key"); // untouched + } + + [Test] + public void Key_File_Deleted_During_Read_Falls_Back_To_Generate() + { + // Raced delete between File.Exists and the read → treat as absent (don't fail boot). + File.WriteAllText(_keyPath, "whatever"); + + string key = ApiKeyProvider.ResolveKey( + Config(), + _keyPath, + NullLogger.Instance, + _ => throw new FileNotFoundException()); + + key.ShouldMatch("^[0-9a-f]{64}$"); + } + + [Test] + public void Returns_A_Usable_Key_Even_When_Persist_Fails() + { + // Make persistence fail by giving the key a parent path that is a FILE, not a directory: + // Directory.CreateDirectory / file creation then throws, Persist swallows it, and the + // resolver must still return the in-memory generated key (the never-empty invariant, #280). + string fileAsParent = Path.Combine(_tempDir.FullName, "not-a-dir"); + File.WriteAllText(fileAsParent, "x"); + string unwritable = Path.Combine(fileAsParent, "api.key"); + + string key = ApiKeyProvider.ResolveKey(Config(), unwritable, NullLogger.Instance); + + key.ShouldMatch("^[0-9a-f]{64}$"); + File.Exists(unwritable).ShouldBeFalse(); + } +} diff --git a/ErsatzTV/Controllers/AccountController.cs b/ErsatzTV/Controllers/AccountController.cs deleted file mode 100644 index 6594cd54d..000000000 --- a/ErsatzTV/Controllers/AccountController.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Microsoft.AspNetCore.Mvc; - -namespace ErsatzTV.Controllers; - -[ApiController] -public class AccountController : ControllerBase -{ - private static readonly string[] AuthenticationSchemes = { "oidc", "cookie" }; - - [HttpPost("account/logout")] - public IActionResult Logout() => new SignOutResult(AuthenticationSchemes); -} diff --git a/ErsatzTV/Controllers/Api/LogsController.cs b/ErsatzTV/Controllers/Api/LogsController.cs index 19e4aadf9..301e4b65b 100644 --- a/ErsatzTV/Controllers/Api/LogsController.cs +++ b/ErsatzTV/Controllers/Api/LogsController.cs @@ -1,6 +1,7 @@ using System.Linq.Expressions; using ErsatzTV.Application.Logs; using ErsatzTV.Core.Api.Logs; +using ErsatzTV.Filters; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -8,6 +9,7 @@ using Microsoft.AspNetCore.Mvc; namespace ErsatzTV.Controllers.Api; [ApiController] +[RequiresApiKey] public class LogsController(IMediator mediator) : ControllerBase { private const int MaxPageSize = 100; diff --git a/ErsatzTV/Controllers/Api/MaintenanceController.cs b/ErsatzTV/Controllers/Api/MaintenanceController.cs index 2093207b7..8330a43d1 100644 --- a/ErsatzTV/Controllers/Api/MaintenanceController.cs +++ b/ErsatzTV/Controllers/Api/MaintenanceController.cs @@ -3,6 +3,7 @@ using ErsatzTV.Application; using ErsatzTV.Application.Maintenance; using ErsatzTV.Core; using ErsatzTV.Extensions; +using ErsatzTV.Filters; using MediatR; using Microsoft.AspNetCore.Mvc; @@ -10,9 +11,10 @@ namespace ErsatzTV.Controllers.Api; [ApiController] [EndpointGroupName("general")] +[RequiresApiKey] public class MaintenanceController(IMediator mediator, ChannelWriter workerChannel) { - [HttpGet("/api/maintenance/gc")] + [HttpPost("/api/maintenance/gc")] [Tags("Maintenance")] [EndpointSummary("Garbage collect")] public async Task GarbageCollection([FromQuery] bool force = false) diff --git a/ErsatzTV/Controllers/Api/ScannerController.cs b/ErsatzTV/Controllers/Api/ScannerController.cs index fb337cc21..a466cf58d 100644 --- a/ErsatzTV/Controllers/Api/ScannerController.cs +++ b/ErsatzTV/Controllers/Api/ScannerController.cs @@ -10,6 +10,7 @@ namespace ErsatzTV.Controllers.Api; [ApiController] [ApiExplorerSettings(IgnoreApi = true)] [SkipApiKeyAuthorization] +[LocalhostOnly] [Route("api/scan/{scanId:guid}")] public class ScannerController( IScannerProxyService scannerProxyService, diff --git a/ErsatzTV/Controllers/Api/SettingsController.cs b/ErsatzTV/Controllers/Api/SettingsController.cs index 7a1d2ec57..a29063b3d 100644 --- a/ErsatzTV/Controllers/Api/SettingsController.cs +++ b/ErsatzTV/Controllers/Api/SettingsController.cs @@ -6,6 +6,7 @@ using ErsatzTV.Controllers.Api.Requests; using ErsatzTV.Core; using ErsatzTV.Core.Api.Settings; using ErsatzTV.Extensions; +using ErsatzTV.Filters; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -18,6 +19,7 @@ namespace ErsatzTV.Controllers.Api; [ApiController] [EndpointGroupName("general")] +[RequiresApiKey] public class SettingsController(IMediator mediator) : ControllerBase { // FFmpeg settings diff --git a/ErsatzTV/Controllers/Api/TroubleshootController.cs b/ErsatzTV/Controllers/Api/TroubleshootController.cs index 7a523f3f7..ca313de74 100644 --- a/ErsatzTV/Controllers/Api/TroubleshootController.cs +++ b/ErsatzTV/Controllers/Api/TroubleshootController.cs @@ -18,6 +18,7 @@ using ErsatzTV.Core.Interfaces.Repositories; using ErsatzTV.Core.Interfaces.Troubleshooting; using ErsatzTV.Core.Troubleshooting; using ErsatzTV.Extensions; +using ErsatzTV.Filters; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -26,6 +27,7 @@ using Serilog.Context; namespace ErsatzTV.Controllers.Api; [ApiController] +[RequiresApiKey] public class TroubleshootController( ChannelWriter channelWriter, IFileSystem fileSystem, diff --git a/ErsatzTV/Controllers/SortController.cs b/ErsatzTV/Controllers/SortController.cs deleted file mode 100644 index 4ca55e6f8..000000000 --- a/ErsatzTV/Controllers/SortController.cs +++ /dev/null @@ -1,31 +0,0 @@ -using ErsatzTV.Application.MediaCollections; -using MediatR; -using Microsoft.AspNetCore.Mvc; - -namespace ErsatzTV.Controllers; - -[ApiController] -[ApiExplorerSettings(IgnoreApi = true)] -public class SortController : ControllerBase -{ - private readonly IMediator _mediator; - - public SortController(IMediator mediator) => _mediator = mediator; - - [HttpPost("media/collections/{collectionId}/items")] - public Task SortCollectionItems( - int collectionId, - [FromForm] - SortedMediaItemIds sortedMediaItemIds) - { - var ids = sortedMediaItemIds.Item.Map(int.Parse).ToList(); - - var request = new UpdateCollectionCustomOrder( - collectionId, - ids.Map(i => new MediaItemCustomOrder(i, ids.IndexOf(i))).ToList()); - - return _mediator.Send(request); - } -} - -public record SortedMediaItemIds(List Item); diff --git a/ErsatzTV/Filters/ApiKeyAuthorizationFilter.cs b/ErsatzTV/Filters/ApiKeyAuthorizationFilter.cs index 821a4fe08..b30771de6 100644 --- a/ErsatzTV/Filters/ApiKeyAuthorizationFilter.cs +++ b/ErsatzTV/Filters/ApiKeyAuthorizationFilter.cs @@ -1,5 +1,6 @@ using System.Security.Cryptography; using System.Text; +using ErsatzTV.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; @@ -8,56 +9,72 @@ using Microsoft.Extensions.Primitives; namespace ErsatzTV.Filters; /// -/// Optional API-key authorization for mutating JSON API endpoints. -/// Reads the configured key from Api:WriteKey. When that key is empty the filter is -/// a no-op (preserving the current open LAN behavior); when it is set, mutating requests -/// under /api/* (POST/PUT/PATCH/DELETE) must present a matching X-Api-Key -/// header or receive 401. This is fully independent of and never -/// affects /iptv/* or any read endpoint. +/// API-key authorization for the JSON API. The effective key (from ) +/// is never empty, so this is fail-closed by construction (issue #280): every mutating request +/// under /api/* must present a matching X-Api-Key header. Read (GET/HEAD) requests +/// under /api/* are also gated when Api:RequireKeyForReads is enabled (the default) +/// or the endpoint carries . Endpoints marked +/// and anything outside /api (e.g. +/// /iptv/*, /artwork/*, the SPA) are never affected. Independent of +/// . /// -public class ApiKeyAuthorizationFilter(IConfiguration configuration) : IAuthorizationFilter +public class ApiKeyAuthorizationFilter(IApiKeyProvider apiKeyProvider) : IAuthorizationFilter { public const string HeaderName = "X-Api-Key"; - public const string ConfigurationKey = "Api:WriteKey"; public void OnAuthorization(AuthorizationFilterContext context) { - if (ShouldSkipApiKeyAuthorization(context)) + HttpRequest request = context.HttpContext.Request; + + // Never gate anything outside the JSON API surface. + if (!request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)) { return; } - string configuredKey = configuration[ConfigurationKey]; - - // empty key => API-key auth disabled, endpoint is open - if (string.IsNullOrEmpty(configuredKey)) + // CORS preflight carries no custom headers and is handled by the CORS middleware. + if (HttpMethods.IsOptions(request.Method)) { return; } - string method = context.HttpContext.Request.Method; - bool isMutating = HttpMethods.IsPost(method) - || HttpMethods.IsPut(method) - || HttpMethods.IsPatch(method) - || HttpMethods.IsDelete(method); - - if (!isMutating) + // Explicit opt-out for internal, separately-guarded endpoints (e.g. the scanner callback). + if (HasMetadata(context)) { return; } - if (!context.HttpContext.Request.Headers.TryGetValue(HeaderName, out StringValues provided) - || !KeysMatch(provided.ToString(), configuredKey)) + if (!RequiresKey(context, request)) + { + return; + } + + if (!request.Headers.TryGetValue(HeaderName, out StringValues provided) + || !KeysMatch(provided.ToString(), apiKeyProvider.ApiKey)) { context.Result = new UnauthorizedObjectResult(new ProblemDetails { Status = StatusCodes.Status401Unauthorized, Title = "Unauthorized", - Detail = "A valid API key is required for write requests." + Detail = $"A valid API key is required. Provide it via the '{HeaderName}' header." }); } } + private bool RequiresKey(AuthorizationFilterContext context, HttpRequest request) + { + string method = request.Method; + bool isMutating = HttpMethods.IsPost(method) + || HttpMethods.IsPut(method) + || HttpMethods.IsPatch(method) + || HttpMethods.IsDelete(method); + + // Writes are always fail-closed; reads are gated by the global flag or a per-endpoint opt-in. + return isMutating + || apiKeyProvider.RequireKeyForReads + || HasMetadata(context); + } + // Compare in constant time so a remote attacker cannot use response-timing to recover the // key prefix-by-prefix. FixedTimeEquals also short-circuits length differences without // leaking anything beyond "lengths differ" (still not the matching-prefix length). @@ -66,23 +83,8 @@ public class ApiKeyAuthorizationFilter(IConfiguration configuration) : IAuthoriz Encoding.UTF8.GetBytes(provided), Encoding.UTF8.GetBytes(configured)); - private static bool ShouldSkipApiKeyAuthorization(AuthorizationFilterContext context) - { - if (context.Filters.OfType().Any() - || context.ActionDescriptor.EndpointMetadata.OfType().Any()) - { - return true; - } - - if (!context.HttpContext.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - string method = context.HttpContext.Request.Method; - return !HttpMethods.IsPost(method) - && !HttpMethods.IsPut(method) - && !HttpMethods.IsPatch(method) - && !HttpMethods.IsDelete(method); - } + private static bool HasMetadata(AuthorizationFilterContext context) + where TAttribute : class => + context.Filters.OfType().Any() + || context.ActionDescriptor.EndpointMetadata.OfType().Any(); } diff --git a/ErsatzTV/Filters/LocalhostOnlyAttribute.cs b/ErsatzTV/Filters/LocalhostOnlyAttribute.cs new file mode 100644 index 000000000..a5cdc7414 --- /dev/null +++ b/ErsatzTV/Filters/LocalhostOnlyAttribute.cs @@ -0,0 +1,38 @@ +using System.Net; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace ErsatzTV.Filters; + +/// +/// Restricts an endpoint to loopback callers (127.0.0.0/8, ::1). Used for the in-process scanner +/// callback surface (/api/scan/*), which is always reached over +/// http://localhost:{UiPort} from the co-located scanner child process. Replaces relying +/// on a guessable scan-id GUID as the sole gate (issue #285). This is only spoof-resistant when +/// ForwardedHeaders trust is restricted (KnownProxies/KnownNetworks configured), since the +/// forwarded-headers middleware rewrites . +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] +public sealed class LocalhostOnlyAttribute : ActionFilterAttribute +{ + public override void OnActionExecuting(ActionExecutingContext context) + { + IPAddress remoteIp = context.HttpContext.Connection.RemoteIpAddress; + if (remoteIp is null || !IsLoopback(remoteIp)) + { + context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); + } + } + + private static bool IsLoopback(IPAddress address) + { + if (IPAddress.IsLoopback(address)) + { + return true; + } + + // A loopback IPv4 address can arrive mapped into IPv6 (::ffff:127.0.0.1). + return address.IsIPv4MappedToIPv6 && IPAddress.IsLoopback(address.MapToIPv4()); + } +} diff --git a/ErsatzTV/Filters/RequiresApiKeyAttribute.cs b/ErsatzTV/Filters/RequiresApiKeyAttribute.cs new file mode 100644 index 000000000..4e444d29d --- /dev/null +++ b/ErsatzTV/Filters/RequiresApiKeyAttribute.cs @@ -0,0 +1,12 @@ +using Microsoft.AspNetCore.Mvc.Filters; + +namespace ErsatzTV.Filters; + +/// +/// Marks a read (GET/HEAD) API endpoint as always requiring the X-Api-Key header, even +/// when Api:RequireKeyForReads is disabled. Applied to the sensitive-read tier +/// (troubleshoot, logs, settings, maintenance) that discloses secrets/paths or triggers work. +/// The mirror of . See issue #282. +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] +public sealed class RequiresApiKeyAttribute : Attribute, IFilterMetadata; diff --git a/ErsatzTV/Services/ApiKeyProvider.cs b/ErsatzTV/Services/ApiKeyProvider.cs new file mode 100644 index 000000000..e2ef782e6 --- /dev/null +++ b/ErsatzTV/Services/ApiKeyProvider.cs @@ -0,0 +1,151 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using ErsatzTV.Core; + +namespace ErsatzTV.Services; + +/// +/// Resolves the effective API key used by and +/// the read-gating policy. Resolved once at startup: the configured Api:WriteKey wins; +/// otherwise a previously-persisted key is loaded from the config volume; otherwise a fresh +/// 256-bit key is generated and persisted. The key is never empty, so write authorization is +/// always fail-closed (issue #280). +/// +public interface IApiKeyProvider +{ + /// The effective API key. Never null or empty. + string ApiKey { get; } + + /// When true (the default), read (GET/HEAD) requests under /api also require the key. + bool RequireKeyForReads { get; } +} + +public sealed class ApiKeyProvider : IApiKeyProvider +{ + public const string WriteKeyConfigurationKey = "Api:WriteKey"; + public const string RequireKeyForReadsConfigurationKey = "Api:RequireKeyForReads"; + + public ApiKeyProvider(IConfiguration configuration, ILogger logger) + { + // Defense-in-depth default: gate reads too. Operators behind an authenticating proxy who + // want anonymous catalog reads can opt out with Api:RequireKeyForReads=false. + RequireKeyForReads = configuration.GetValue(RequireKeyForReadsConfigurationKey, true); + ApiKey = ResolveKey(configuration, FileSystemLayout.ApiKeyPath, logger); + } + + public string ApiKey { get; } + + public bool RequireKeyForReads { get; } + + internal static string ResolveKey( + IConfiguration configuration, + string keyFilePath, + ILogger logger, + Func readKeyFile = null) + { + readKeyFile ??= File.ReadAllText; + + string configured = configuration[WriteKeyConfigurationKey]; + if (!string.IsNullOrWhiteSpace(configured)) + { + logger.LogInformation("Using API key from configuration ({ConfigurationKey})", WriteKeyConfigurationKey); + return configured.Trim(); + } + + if (File.Exists(keyFilePath)) + { + try + { + string existing = readKeyFile(keyFilePath).Trim(); + if (!string.IsNullOrWhiteSpace(existing)) + { + logger.LogInformation("Loaded persisted API key from {Path}", keyFilePath); + return existing; + } + + logger.LogWarning("Persisted API key file {Path} was empty; generating a new key", keyFilePath); + } + catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) + { + // Raced with a delete between the existence check and the read; treat as absent. + logger.LogWarning( + "Persisted API key file {Path} disappeared before it could be read; generating a new key", + keyFilePath); + } + catch (Exception ex) + { + // Present but unreadable (e.g. wrong permissions). Fail loud rather than silently + // generate + overwrite it, which would invalidate every client's stored key. + logger.LogError( + ex, + "API key file {Path} exists but could not be read; refusing to overwrite it. Fix its " + + "permissions or set {ConfigurationKey}.", + keyFilePath, + WriteKeyConfigurationKey); + throw; + } + } + + string generated = GenerateKey(); + Persist(keyFilePath, generated, logger); + return generated; + } + + internal static string GenerateKey() => + // 256 bits of entropy, rendered as lowercase hex so it is trivial to copy/paste with no + // URL-/header-unsafe characters. + Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant(); + + private static void Persist(string path, string key, ILogger logger) + { + try + { + string directory = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + File.WriteAllText(path, key); + } + else + { + // Create the file owner-only (0600) up front so the key is never briefly world-readable + // between write and chmod. SetUnixFileMode afterwards re-asserts it if the file pre-existed + // (UnixCreateMode only applies to a newly-created file, not a truncated one). + const UnixFileMode ownerReadWrite = UnixFileMode.UserRead | UnixFileMode.UserWrite; + var options = new FileStreamOptions + { + Mode = FileMode.Create, + Access = FileAccess.Write, + UnixCreateMode = ownerReadWrite + }; + + using (var stream = new FileStream(path, options)) + using (var writer = new StreamWriter(stream)) + { + writer.Write(key); + } + + File.SetUnixFileMode(path, ownerReadWrite); + } + + logger.LogWarning( + "Generated a new API key and saved it to {Path}. Send it via the '{HeaderName}' header " + + "(ChicoryTV: Settings → API Key). The key is required for API requests.", + path, + Filters.ApiKeyAuthorizationFilter.HeaderName); + } + catch (Exception ex) + { + logger.LogError( + ex, + "Failed to persist generated API key to {Path}; it will not survive a restart. " + + "Set {ConfigurationKey} to a fixed value to avoid this.", + path, + WriteKeyConfigurationKey); + } + } +} diff --git a/ErsatzTV/Startup.cs b/ErsatzTV/Startup.cs index e2053ac93..ab71a36ed 100644 --- a/ErsatzTV/Startup.cs +++ b/ErsatzTV/Startup.cs @@ -1,6 +1,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO.Abstractions; +using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Text; @@ -117,6 +118,12 @@ public class Startup private IWebHostEnvironment CurrentEnvironment { get; } + // Parse a semicolon-separated configuration value into trimmed, non-empty entries. + private static string[] SplitConfig(string value) => + string.IsNullOrWhiteSpace(value) + ? [] + : value.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + private static void UseStringEnumSchemas(OpenApiDocument document) { if (document.Components?.Schemas is null) @@ -168,6 +175,45 @@ public class Startup options.ForwardLimit = 2; options.KnownIPNetworks.Clear(); options.KnownProxies.Clear(); + + // With both lists cleared, X-Forwarded-* is accepted from ANY peer (spoofable, issue + // #285). Restrict trust to the real reverse proxy by configuring + // ForwardedHeaders:KnownProxies (IPs) and/or ForwardedHeaders:KnownNetworks (CIDRs). + bool trustRestricted = false; + + foreach (string proxy in SplitConfig(Configuration["ForwardedHeaders:KnownProxies"])) + { + if (IPAddress.TryParse(proxy, out IPAddress address)) + { + options.KnownProxies.Add(address); + trustRestricted = true; + } + else + { + Log.Warning("Ignoring invalid ForwardedHeaders:KnownProxies entry {Entry}", proxy); + } + } + + foreach (string network in SplitConfig(Configuration["ForwardedHeaders:KnownNetworks"])) + { + if (System.Net.IPNetwork.TryParse(network, out System.Net.IPNetwork parsed)) + { + options.KnownIPNetworks.Add(parsed); + trustRestricted = true; + } + else + { + Log.Warning("Ignoring invalid ForwardedHeaders:KnownNetworks entry {Entry}", network); + } + } + + if (!trustRestricted) + { + Log.Warning( + "ForwardedHeaders trusts X-Forwarded-* from any peer (spoofable). Set " + + "ForwardedHeaders:KnownProxies and/or ForwardedHeaders:KnownNetworks to restrict " + + "trust to your reverse proxy when exposing ErsatzTV beyond a trusted LAN."); + } }); services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(FileSystemLayout.DataProtectionFolder)); @@ -336,12 +382,26 @@ public class Startup } services.AddCors(o => o.AddPolicy( - "AllowAll", + "ApiCors", builder => { - builder.AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader(); + string[] origins = SplitConfig(Configuration["Api:CorsAllowedOrigins"]); + if (origins.Length > 0) + { + // Exact-origin allowlist. Must permit the auth + optimistic-concurrency request + // headers and expose the ETag, or cross-origin API clients break (issue #284). + builder.WithOrigins(origins) + .AllowAnyMethod() + .WithHeaders( + "Accept", + "Content-Type", + "Authorization", + ApiKeyAuthorizationFilter.HeaderName, + "If-Match") + .WithExposedHeaders("ETag"); + } + + // No configured origins => no cross-origin access (the SPA is same-origin from /app). })); services.AddLocalization(); @@ -365,7 +425,9 @@ public class Startup services.AddScoped(_ => new ConditionalIptvAuthorizeFilter("JwtOnlyScheme")); - // optional API-key authorization for mutating JSON API endpoints (independent of JWT/OIDC) + // API-key authorization for the JSON API (independent of JWT/OIDC). The provider resolves the + // effective key once (config, else persisted, else generated) so writes are fail-closed. + services.AddSingleton(); services.AddScoped(); services.AddFluentValidationAutoValidation(); @@ -570,7 +632,11 @@ public class Startup app.UseMiddleware(); - app.UseCors("AllowAll"); + // Resolve the API key eagerly so a generated key is created + logged at startup rather than + // on the first API request. + app.ApplicationServices.GetRequiredService(); + + app.UseCors("ApiCors"); app.UseForwardedHeaders(); //app.UseHttpLogging(); diff --git a/ErsatzTV/wwwroot/openapi/v1.json b/ErsatzTV/wwwroot/openapi/v1.json index 3b4d11c46..a219dedd9 100644 --- a/ErsatzTV/wwwroot/openapi/v1.json +++ b/ErsatzTV/wwwroot/openapi/v1.json @@ -7816,7 +7816,7 @@ } }, "/api/maintenance/gc": { - "get": { + "post": { "tags": [ "Maintenance" ], diff --git a/docs/api-conventions.md b/docs/api-conventions.md index fb0543a37..eefbe63f7 100644 --- a/docs/api-conventions.md +++ b/docs/api-conventions.md @@ -281,6 +281,11 @@ single-leading-cap names (`fFmpegPath`, `fFprobePath`, `zIndex`, `rFrameRate`) a explicit `[SkipApiKeyAuthorizationAttribute]` exemption; only `ScannerController` is exempt today). A minimum-count guard asserts the scan found a sane number of controllers, so a namespace rename can't silently make the scan match nothing and give this test a false pass. + It also asserts the **sensitive-read tier** (`Troubleshoot`/`Logs`/`Settings`/`Maintenance`) + carries `[RequiresApiKey]` and that `ScannerController` carries `[LocalhostOnly]` — reflectively, + so the tier can't silently drop a gate. `ApiKeyAuthorizationFilterTests.cs` unit-tests the filter + itself: writes are always fail-closed, reads are gated when `Api:RequireKeyForReads` (default true) + or `[RequiresApiKey]`, `OPTIONS` preflight and non-`/api` paths are exempt. - **Handler tests** (business logic behind the controller) use the shared in-memory SQLite fixture: `ErsatzTV.Tests/Support/InMemoryTvContext.cs`. Pattern: `SqliteConnection("Data Source=:memory:;Foreign Keys=False")` kept open for the fixture's lifetime, `EnsureCreatedAsync()` (not full migration @@ -464,3 +469,29 @@ for items that have no group, so the SPA can render an "ungrouped" bucket (`Id = unusedGroup.Id * -1`, `Name = "(none)"`). See issue #172. If you add a similar "ungrouped" concept elsewhere, this is the established pattern to follow — but be aware it means `Id` is not a reliable real-entity id for those synthetic rows. + +## 9. Authentication — API key posture (fail-closed) + +The whole `/api` surface is gated by the `X-Api-Key` header via the global `ApiKeyAuthorizationFilter` +(issue #197 Bundle A). When you add an endpoint: + +- **Do nothing** for the common case. Writes (POST/PUT/PATCH/DELETE) always require the key + (fail-closed — there is no "open" mode). Reads (GET/HEAD) require the key when + `Api:RequireKeyForReads` is enabled, which is the **default** (`true`). `OPTIONS` preflight is exempt. +- The effective key comes from `IApiKeyProvider` (`ErsatzTV/Services/ApiKeyProvider.cs`): `Api:WriteKey` + if configured, else a key persisted at `FileSystemLayout.ApiKeyPath` (`/config/api.key`, `0600`), else + a freshly generated 256-bit key. It is never empty. +- **Sensitive-read GETs** that disclose secrets/paths or trigger work must carry `[RequiresApiKey]` so + they stay gated even if an operator sets `Api:RequireKeyForReads=false`. Current tier: + `Troubleshoot`/`Logs`/`Settings`/`Maintenance`. `ApiControllerSecurityTests` asserts this reflectively. +- **Internal loopback callbacks** (the scanner's `/api/scan/*`) use `[SkipApiKeyAuthorization]` + + `[LocalhostOnly]` — the API key is a poor fit for a co-located child process, so the gate is the + loopback check (sound only because `ForwardedHeaders` trust is restricted via + `ForwardedHeaders:KnownProxies`/`KnownNetworks`). +- **CORS** is opt-in: no cross-origin access by default (the SPA is same-origin from `/app`); set + `Api:CorsAllowedOrigins` (semicolon-separated exact origins) to allow specific browser origins — the + policy already permits `X-Api-Key`/`If-Match` and exposes `ETag`. +- The SPA sends the stored key (`ctv-api-key`) on **every** request; users enter it on the keyless + **API Key** screen (`web/src/screens/ApiKeyScreen.tsx`, route `/app/api-key`). See spa-conventions §5e. + +The declarative OpenAPI security scheme + global 401 documentation are Phase-2 (#286/#287), not this tier. diff --git a/docs/decisions.md b/docs/decisions.md index 34c42326e..73fce2a61 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -941,3 +941,48 @@ fail-closed/CORS/versioning posture work tracked in #280–#289. The larger #197 posture (fail-closed writes, sensitive-read auth tier, CORS lockdown, `/api/v1` versioning, the OpenAPI security scheme) is decomposed into #280–#289 with the phased roadmap on #197; those PRs will append their own decisions here as they land. + +## 2026-07-12 — Fail-closed API auth + sensitive-read tier + CORS/ForwardedHeaders lockdown (#197 Bundle A, PR #292) + +Phase-1 of the #197 remediation — the auth posture that must land before any remote exposure. +Owner decisions (confirmed this session): **single API key** (no read/write split), and +**`Api:RequireKeyForReads` defaults `true`** (the whole `/api` surface requires the key). This does +**not** affect Jellyfin/streaming: `/iptv/*` (playlist/guide/streams/logos) and `/artwork/*` are outside +the filter's `/api` scope and keep their own optional access-token; only the management API the SPA talks +to is gated. + +- **Fail-closed writes (#280, S1).** The empty-key "open" branch is deleted; there is no open mode. New + `IApiKeyProvider` (`ErsatzTV/Services/ApiKeyProvider.cs`, singleton, resolved once at startup) yields a + never-empty key: `Api:WriteKey` if set, else a key persisted at `FileSystemLayout.ApiKeyPath` + (`/config/api.key`, `0600`, path logged not value), else a generated 256-bit hex key. Every mutating + `/api` request now requires `X-Api-Key`. +- **Sensitive-read tier (#282, S3/S5).** Reads are gated by `Api:RequireKeyForReads` (default true) OR a + new `[RequiresApiKey]` marker (mirror of `[SkipApiKeyAuthorization]`) applied to + `Troubleshoot`/`Logs`/`Settings`/`Maintenance`, so that tier stays gated even if an operator opts reads + open. `OPTIONS` preflight is exempt (CORS middleware owns it). `ApiControllerSecurityTests` asserts the + tier reflectively. +- **Delete dead non-`/api` mutation surfaces (#281, S2).** `SortController` + (`POST media/collections/{id}/items`, dead Blazor SortableJS residue — the SPA uses + `PUT /api/collections/{id}/custom-order`) and `AccountController` (`POST account/logout`, dead OIDC) + bypassed the key because they sat outside `/api`. Removed rather than guarded. +- **CORS opt-in (#284, S6).** `AllowAnyOrigin/Method/Header` is replaced by the `ApiCors` policy: an + exact-origin allowlist from `Api:CorsAllowedOrigins` (semicolon list) that permits `X-Api-Key`/`If-Match` + and exposes `ETag`; with no origins configured there is no cross-origin access (the SPA is same-origin). +- **ForwardedHeaders trust + scanner loopback (#285, S7/S10).** `GET /api/maintenance/gc` → `POST` + (crawler-triggerable GC; spec regenerated). `ForwardedHeaders` trust is configurable via + `ForwardedHeaders:KnownProxies`/`KnownNetworks` — **unconfigured preserves the current trust-all + behavior but logs a warning** (flipping the default to loopback-only would break reverse-proxy scheme/host + detection and thus M3U/XMLTV absolute URLs — the operator must name their proxy network). `ScannerController` + gains `[LocalhostOnly]` (the scanner always calls back over `http://localhost:{UiPort}/api/scan/...`), which + is only spoof-resistant once ForwardedHeaders trust is restricted — the two interlock. `search/all-items` + DoS-paging is **deferred** (it feeds the SPA "add all" flow and needs coordinated pagination; the unauth + exposure is already closed by read-gating). +- **SPA (`web/`).** The client sends the stored key (`ctv-api-key`) on **every** method (not just + mutations); a new keyless **API Key** screen (`/app/api-key`) lets the user paste the generated key, and a + shell-level banner points there on any 401. See spa-conventions §5e. **First-run/upgrade UX:** with reads + gated by default, the SPA shows no data until the key (from `/config/api.key`) is entered — an intended + consequence of the strict default. + +Phase-2 (contract freeze) — the declarative OpenAPI security scheme, global 401 docs, and `/api/v1` +versioning — remains #286/#287/#288. Phase-3 follow-ups: #265, #269, #172 remainder, `search/all-items` +paging, per-key rate limiting. diff --git a/docs/endpoint-index.md b/docs/endpoint-index.md index 7f833e36d..dd7a82884 100644 --- a/docs/endpoint-index.md +++ b/docs/endpoint-index.md @@ -213,7 +213,7 @@ |---|---|---|---| | POST | `/api/maintenance/clean_artwork` | | Clean artwork cache | | POST | `/api/maintenance/empty_trash` | | Empty trash | -| GET | `/api/maintenance/gc` | | Garbage collect | +| POST | `/api/maintenance/gc` | | Garbage collect | ## Media Items diff --git a/docs/spa-conventions.md b/docs/spa-conventions.md index 50de7523e..8c0789a93 100644 --- a/docs/spa-conventions.md +++ b/docs/spa-conventions.md @@ -207,6 +207,29 @@ session — if a preference needs to be shared across devices or is really serve (e.g. Blazor's `ConfigElement`-backed settings), it belongs behind an API endpoint instead; see `docs/decisions.md` 2026-07-11 for the specific reasoning on logs page-size. +## 5e. API key: the one keyless screen + the global 401 signal (#197) + +The whole `/api` surface is gated behind an `X-Api-Key` header (server-side #197): writes always +require it and reads require it too (`Api:RequireKeyForReads` defaults true), so a missing/wrong key +yields **401** on every call. Two SPA seams support this: + +- **The request client sends the key on every request** (`web/src/api/client.ts`): whenever + `getStoredApiKey()` returns a value it's attached to `X-Api-Key`, regardless of method (there is no + reads-vs-mutations split — that older guard was removed). The key lives in `localStorage` + (`ctv-api-key`) via `web/src/api/auth.ts` (`get/set/clearStoredApiKey`), per §5d. +- **The API Key screen is the one screen that must render with ZERO successful `/api` calls** + (`web/src/screens/ApiKeyScreen.tsx`, route `/app/api-key`, System nav group). A keyless first load + 401s every read, so this screen reads/writes **only** `localStorage` (the `auth.ts` helpers) and + never fetches from `/api`. It shows a masked "key set / no key" state (never echoes the stored key + in plaintext — a `type="password"` input), Save (`setStoredApiKey`) and Clear (`clearStoredApiKey`), + and copy pointing at the server-generated `/config/api.key`. If you add a keyless bootstrap screen, + keep it `localStorage`-only for the same reason. +- **401 UX is one shell-level banner, not per-screen handling.** Rather than special-casing 401 in + every screen's error path, the request client emits a single app-wide signal on 401 + (`auth.ts` `notifyUnauthorized` / `subscribeUnauthorized`), and `web/src/UnauthorizedBanner.tsx` + (rendered once in the App shell) subscribes and points the user at `/app/api-key`. This is the DRY + seam for "the server rejected us" — reuse it instead of adding bespoke 401 branches. + ## 6. Tests - **vitest**, colocated `*.test.ts` / `*.test.tsx` next to the source file. diff --git a/web/src/App.tsx b/web/src/App.tsx index a66d29410..c814eb19d 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -27,6 +27,7 @@ import { FolderTree, Info, Layers, + KeyRound, LayoutDashboard, LayoutGrid, Library, @@ -81,6 +82,8 @@ import { import { ImageBrowserScreen } from './screens/ImageBrowserScreen'; import { SearchScreen } from './screens/SearchScreen'; import { SettingsScreen } from './screens/SettingsScreen'; +import { ApiKeyScreen } from './screens/ApiKeyScreen'; +import { UnauthorizedBanner } from './UnauthorizedBanner'; import { TraktListsScreen } from './screens/TraktListsScreen'; import { TrashScreen } from './screens/TrashScreen'; import { TroubleshootingScreen } from './screens/TroubleshootingScreen'; @@ -187,6 +190,7 @@ type ScreenId = | 'ffmpegProfiles' | 'watermarks' | 'settings' + | 'apiKey' | 'logs' | 'troubleshooting' | 'blockPlayoutTroubleshooting' @@ -504,6 +508,19 @@ const routes: ScreenRoute[] = [ placeholder: 'Settings workspace', allowSubPaths: true }, + { + // Keyless by design: this screen reads/writes only localStorage (auth.ts) and never calls + // `/api`, so it works on a fresh install where every `/api` read 401s (#280 / #197). + id: 'apiKey', + path: '/app/api-key', + label: 'API Key', + title: 'API Key', + kicker: 'System', + description: 'Store the API key this server requires on every request.', + icon: