security(#197): fail-closed API auth posture (Bundle A: #280/#281/#282/#284/#285) #292
@@ -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");
|
||||
|
||||
@@ -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<RequiresApiKeyAttribute>(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<LocalhostOnlyAttribute>(inherit: true)
|
||||
.Any()
|
||||
.ShouldBeTrue();
|
||||
}
|
||||
|
||||
private static bool IsGloballyProtected() => ApiKeyAuthorizationFilterIsGlobal;
|
||||
|
||||
private static bool IsApiKeyAuthorizationFilterRegisteredGlobally()
|
||||
|
||||
@@ -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<object>();
|
||||
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<IFilterMetadata>());
|
||||
}
|
||||
|
||||
private static ApiKeyAuthorizationFilter MakeFilter(string? configuredKey)
|
||||
{
|
||||
var settings = new Dictionary<string, string?>();
|
||||
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<UnauthorizedObjectResult>();
|
||||
var problemDetails = result.Value.ShouldBeOfType<ProblemDetails>();
|
||||
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<UnauthorizedObjectResult>();
|
||||
var problemDetails = result.Value.ShouldBeOfType<ProblemDetails>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<string, string?>();
|
||||
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<IOException>(() =>
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<IBackgroundServiceRequest> workerChannel)
|
||||
{
|
||||
[HttpGet("/api/maintenance/gc")]
|
||||
[HttpPost("/api/maintenance/gc")]
|
||||
[Tags("Maintenance")]
|
||||
[EndpointSummary("Garbage collect")]
|
||||
public async Task<IActionResult> GarbageCollection([FromQuery] bool force = false)
|
||||
|
||||
@@ -10,6 +10,7 @@ namespace ErsatzTV.Controllers.Api;
|
||||
[ApiController]
|
||||
[ApiExplorerSettings(IgnoreApi = true)]
|
||||
[SkipApiKeyAuthorization]
|
||||
[LocalhostOnly]
|
||||
[Route("api/scan/{scanId:guid}")]
|
||||
public class ScannerController(
|
||||
IScannerProxyService scannerProxyService,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<IFFmpegWorkerRequest> channelWriter,
|
||||
IFileSystem fileSystem,
|
||||
|
||||
@@ -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<string> Item);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Optional API-key authorization for mutating JSON API endpoints.
|
||||
/// Reads the configured key from <c>Api:WriteKey</c>. When that key is empty the filter is
|
||||
/// a no-op (preserving the current open LAN behavior); when it is set, mutating requests
|
||||
/// under <c>/api/*</c> (POST/PUT/PATCH/DELETE) must present a matching <c>X-Api-Key</c>
|
||||
/// header or receive 401. This is fully independent of <see cref="JwtHelper" /> and never
|
||||
/// affects /iptv/* or any read endpoint.
|
||||
/// API-key authorization for the JSON API. The effective key (from <see cref="IApiKeyProvider" />)
|
||||
/// is never empty, so this is fail-closed by construction (issue #280): every mutating request
|
||||
/// under <c>/api/*</c> must present a matching <c>X-Api-Key</c> header. Read (GET/HEAD) requests
|
||||
/// under <c>/api/*</c> are also gated when <c>Api:RequireKeyForReads</c> is enabled (the default)
|
||||
/// or the endpoint carries <see cref="RequiresApiKeyAttribute" />. Endpoints marked
|
||||
/// <see cref="SkipApiKeyAuthorizationAttribute" /> and anything outside <c>/api</c> (e.g.
|
||||
/// <c>/iptv/*</c>, <c>/artwork/*</c>, the SPA) are never affected. Independent of
|
||||
/// <see cref="JwtHelper" />.
|
||||
/// </summary>
|
||||
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<SkipApiKeyAuthorizationAttribute>(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<RequiresApiKeyAttribute>(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<SkipApiKeyAuthorizationAttribute>().Any()
|
||||
|| context.ActionDescriptor.EndpointMetadata.OfType<SkipApiKeyAuthorizationAttribute>().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<TAttribute>(AuthorizationFilterContext context)
|
||||
where TAttribute : class =>
|
||||
context.Filters.OfType<TAttribute>().Any()
|
||||
|| context.ActionDescriptor.EndpointMetadata.OfType<TAttribute>().Any();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace ErsatzTV.Filters;
|
||||
|
||||
/// <summary>
|
||||
/// Restricts an endpoint to loopback callers (127.0.0.0/8, ::1). Used for the in-process scanner
|
||||
/// callback surface (<c>/api/scan/*</c>), which is always reached over
|
||||
/// <c>http://localhost:{UiPort}</c> 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
|
||||
/// <c>ForwardedHeaders</c> trust is restricted (KnownProxies/KnownNetworks configured), since the
|
||||
/// forwarded-headers middleware rewrites <see cref="ConnectionInfo.RemoteIpAddress" />.
|
||||
/// </summary>
|
||||
[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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace ErsatzTV.Filters;
|
||||
|
||||
/// <summary>
|
||||
/// Marks a read (GET/HEAD) API endpoint as always requiring the <c>X-Api-Key</c> header, even
|
||||
/// when <c>Api:RequireKeyForReads</c> is disabled. Applied to the sensitive-read tier
|
||||
/// (troubleshoot, logs, settings, maintenance) that discloses secrets/paths or triggers work.
|
||||
/// The mirror of <see cref="SkipApiKeyAuthorizationAttribute" />. See issue #282.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
||||
public sealed class RequiresApiKeyAttribute : Attribute, IFilterMetadata;
|
||||
@@ -0,0 +1,151 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using ErsatzTV.Core;
|
||||
|
||||
namespace ErsatzTV.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the effective API key used by <see cref="Filters.ApiKeyAuthorizationFilter" /> and
|
||||
/// the read-gating policy. Resolved once at startup: the configured <c>Api:WriteKey</c> 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).
|
||||
/// </summary>
|
||||
public interface IApiKeyProvider
|
||||
{
|
||||
/// <summary>The effective API key. Never null or empty.</summary>
|
||||
string ApiKey { get; }
|
||||
|
||||
/// <summary>When true (the default), read (GET/HEAD) requests under <c>/api</c> also require the key.</summary>
|
||||
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<ApiKeyProvider> 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<string, string> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+72
-6
@@ -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<IApiKeyProvider, ApiKeyProvider>();
|
||||
services.AddScoped<ApiKeyAuthorizationFilter>();
|
||||
|
||||
services.AddFluentValidationAutoValidation();
|
||||
@@ -570,7 +632,11 @@ public class Startup
|
||||
|
||||
app.UseMiddleware<SecurityHeadersMiddleware>();
|
||||
|
||||
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<IApiKeyProvider>();
|
||||
|
||||
app.UseCors("ApiCors");
|
||||
app.UseForwardedHeaders();
|
||||
|
||||
//app.UseHttpLogging();
|
||||
|
||||
@@ -7816,7 +7816,7 @@
|
||||
}
|
||||
},
|
||||
"/api/maintenance/gc": {
|
||||
"get": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"Maintenance"
|
||||
],
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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: <KeyRound aria-hidden="true" size={16} />,
|
||||
primaryAction: 'Save key',
|
||||
placeholder: 'API key workspace'
|
||||
},
|
||||
{
|
||||
id: 'logs',
|
||||
path: '/app/logs',
|
||||
@@ -589,6 +606,7 @@ const mediaNavIds: ScreenId[] = [
|
||||
];
|
||||
const systemNavIds: ScreenId[] = [
|
||||
'settings',
|
||||
'apiKey',
|
||||
'logs',
|
||||
'troubleshooting',
|
||||
'blockPlayoutTroubleshooting',
|
||||
@@ -2663,6 +2681,10 @@ function ScreenContent({
|
||||
return <SettingsScreen />;
|
||||
}
|
||||
|
||||
if (route.id === 'apiKey') {
|
||||
return <ApiKeyScreen />;
|
||||
}
|
||||
|
||||
if (route.id === 'media') {
|
||||
return <MediaRouteScreen />;
|
||||
}
|
||||
@@ -2813,6 +2835,7 @@ export function App() {
|
||||
<Sidebar activeRoute={route} healthState={healthState} onNavigate={navigate} />
|
||||
<div className="ctv-shell-body">
|
||||
<TopBar route={route} />
|
||||
<UnauthorizedBanner />
|
||||
<main className="ctv-main">
|
||||
<ThemeSwitcher theme={theme} onThemeChange={setTheme} />
|
||||
<ScreenContent healthState={healthState} librariesSubPath={librariesSubPath} route={route} />
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { notifyUnauthorized } from './api';
|
||||
import { UnauthorizedBanner } from './UnauthorizedBanner';
|
||||
|
||||
describe('UnauthorizedBanner', () => {
|
||||
beforeEach(() => {
|
||||
window.history.pushState(null, '', '/app');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('stays hidden until a 401 signal fires', () => {
|
||||
render(<UnauthorizedBanner />);
|
||||
|
||||
expect(screen.queryByRole('alert')).toBeNull();
|
||||
|
||||
act(() => notifyUnauthorized());
|
||||
|
||||
expect(screen.getByRole('alert')).toBeTruthy();
|
||||
expect(screen.getByText(/requires an API key/)).toBeTruthy();
|
||||
expect(screen.getByText(/Settings → API Key/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('navigates to the API Key screen from the pointer link', () => {
|
||||
render(<UnauthorizedBanner />);
|
||||
act(() => notifyUnauthorized());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Open API Key' }));
|
||||
|
||||
expect(window.location.pathname).toBe('/app/api-key');
|
||||
expect(screen.queryByRole('alert')).toBeNull();
|
||||
});
|
||||
|
||||
it('can be dismissed', () => {
|
||||
render(<UnauthorizedBanner />);
|
||||
act(() => notifyUnauthorized());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));
|
||||
|
||||
expect(screen.queryByRole('alert')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { KeyRound, X } from 'lucide-react';
|
||||
import { subscribeUnauthorized } from './api';
|
||||
import { navigateToPath } from './routing';
|
||||
|
||||
const API_KEY_PATH = '/app/api-key';
|
||||
|
||||
// Shell-level pointer shown when any `/api` request returns 401 (#197). Rather than teach every
|
||||
// screen's error path to special-case 401, the request client emits one app-wide signal (auth.ts)
|
||||
// and this single banner subscribes — DRY, and it renders regardless of which screen triggered it.
|
||||
export function UnauthorizedBanner() {
|
||||
const [visible, setVisible] = useState(false);
|
||||
|
||||
useEffect(() => subscribeUnauthorized(() => setVisible(true)), []);
|
||||
|
||||
if (!visible) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const goToApiKey = () => {
|
||||
setVisible(false);
|
||||
navigateToPath(API_KEY_PATH);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="ctv-auth-banner" role="alert">
|
||||
<KeyRound aria-hidden="true" size={15} />
|
||||
<span className="ctv-auth-banner-text">
|
||||
This server requires an API key. Enter it in Settings → API Key.
|
||||
</span>
|
||||
<button className="ctv-auth-banner-link ctv-press" onClick={goToApiKey} type="button">
|
||||
Open API Key
|
||||
</button>
|
||||
<button aria-label="Dismiss" className="ctv-auth-banner-dismiss ctv-press" onClick={() => setVisible(false)} type="button">
|
||||
<X aria-hidden="true" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { clearStoredApiKey, getStoredApiKey, setStoredApiKey } from './auth';
|
||||
import { clearStoredApiKey, getStoredApiKey, notifyUnauthorized, setStoredApiKey, subscribeUnauthorized } from './auth';
|
||||
|
||||
describe('API key storage', () => {
|
||||
beforeEach(() => {
|
||||
@@ -40,3 +40,17 @@ describe('API key storage', () => {
|
||||
localStorageGetter.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('unauthorized signal', () => {
|
||||
it('notifies subscribers and stops after unsubscribe', () => {
|
||||
const listener = vi.fn();
|
||||
const unsubscribe = subscribeUnauthorized(listener);
|
||||
|
||||
notifyUnauthorized();
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
|
||||
unsubscribe();
|
||||
notifyUnauthorized();
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -31,3 +31,26 @@ export function setStoredApiKey(apiKey: string): void {
|
||||
export function clearStoredApiKey(): void {
|
||||
getStorage()?.removeItem(apiKeyStorageKey);
|
||||
}
|
||||
|
||||
// --- 401 signal -------------------------------------------------------------
|
||||
// The whole `/api` surface is gated behind the API key (#197). Rather than teach
|
||||
// every screen's error path to special-case 401, the request client emits a single
|
||||
// app-wide signal when any request comes back Unauthorized; a shell-level banner
|
||||
// subscribes and points the user at the API Key screen. Kept here (next to the key
|
||||
// storage it concerns) so it never depends on a successful `/api` call.
|
||||
type UnauthorizedListener = () => void;
|
||||
|
||||
const unauthorizedListeners = new Set<UnauthorizedListener>();
|
||||
|
||||
export function subscribeUnauthorized(listener: UnauthorizedListener): () => void {
|
||||
unauthorizedListeners.add(listener);
|
||||
return () => {
|
||||
unauthorizedListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function notifyUnauthorized(): void {
|
||||
for (const listener of unauthorizedListeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { setStoredApiKey } from './auth';
|
||||
import { setStoredApiKey, subscribeUnauthorized } from './auth';
|
||||
import { ApiError, request, requestWithMeta } from './client';
|
||||
|
||||
describe('API request client', () => {
|
||||
@@ -8,21 +8,39 @@ describe('API request client', () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('omits the API key header for read requests', async () => {
|
||||
it('adds the API key header for read requests when a key is stored', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify([{ id: 1, number: '1', name: 'News' }]), {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
status: 200
|
||||
})
|
||||
);
|
||||
setStoredApiKey('write-secret');
|
||||
setStoredApiKey('read-secret');
|
||||
|
||||
await request('/api/channels');
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/channels',
|
||||
expect.objectContaining({
|
||||
headers: expect.not.objectContaining({ 'X-Api-Key': 'write-secret' })
|
||||
headers: expect.objectContaining({ 'X-Api-Key': 'read-secret' })
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('sends no API key header when none is stored', async () => {
|
||||
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify([]), {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
status: 200
|
||||
})
|
||||
);
|
||||
|
||||
await request('/api/channels');
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/channels',
|
||||
expect.objectContaining({
|
||||
headers: expect.not.objectContaining({ 'X-Api-Key': expect.anything() })
|
||||
})
|
||||
);
|
||||
});
|
||||
@@ -63,6 +81,40 @@ describe('API request client', () => {
|
||||
await expect(request('/api/channels', { method: 'POST' })).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('signals unauthorized subscribers on a 401 response', async () => {
|
||||
vi.spyOn(window, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify({ status: 401, title: 'Unauthorized' }), {
|
||||
headers: { 'Content-Type': 'application/problem+json' },
|
||||
status: 401
|
||||
})
|
||||
);
|
||||
|
||||
const onUnauthorized = vi.fn();
|
||||
const unsubscribe = subscribeUnauthorized(onUnauthorized);
|
||||
|
||||
await expect(request('/api/channels')).rejects.toMatchObject({ status: 401 });
|
||||
|
||||
expect(onUnauthorized).toHaveBeenCalledTimes(1);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it('does not signal unauthorized subscribers on other error statuses', async () => {
|
||||
vi.spyOn(window, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify({ status: 403, title: 'Forbidden' }), {
|
||||
headers: { 'Content-Type': 'application/problem+json' },
|
||||
status: 403
|
||||
})
|
||||
);
|
||||
|
||||
const onUnauthorized = vi.fn();
|
||||
const unsubscribe = subscribeUnauthorized(onUnauthorized);
|
||||
|
||||
await expect(request('/api/channels')).rejects.toMatchObject({ status: 403 });
|
||||
|
||||
expect(onUnauthorized).not.toHaveBeenCalled();
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it('reads problem details from application/problem+json responses', async () => {
|
||||
vi.spyOn(window, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify({ status: 401, title: 'Unauthorized', detail: 'A valid API key is required for write requests.' }), {
|
||||
|
||||
+10
-4
@@ -1,4 +1,4 @@
|
||||
import { getStoredApiKey } from './auth';
|
||||
import { getStoredApiKey, notifyUnauthorized } from './auth';
|
||||
import type { components } from './generated/v1';
|
||||
|
||||
type ProblemDetails = components['schemas']['ProblemDetails'];
|
||||
@@ -22,8 +22,6 @@ export interface ApiRequestOptions extends Omit<RequestInit, 'body'> {
|
||||
body?: RequestBody;
|
||||
}
|
||||
|
||||
const mutatingMethods = new Set(['DELETE', 'PATCH', 'POST', 'PUT']);
|
||||
|
||||
export interface ResponseWithMeta<T> {
|
||||
data: T;
|
||||
/** Strong ETag of the resource's version, when the endpoint emits one (issue #253). */
|
||||
@@ -48,7 +46,9 @@ export async function requestWithMeta<TResponse = unknown>(
|
||||
const body = serializeBody(options.body, headers);
|
||||
const apiKey = getStoredApiKey();
|
||||
|
||||
if (apiKey && mutatingMethods.has(method)) {
|
||||
// #197/#282: the whole `/api` surface is gated (reads too, since `Api:RequireKeyForReads`
|
||||
// defaults true), so send the key on every request whenever one is stored — not only mutations.
|
||||
if (apiKey) {
|
||||
headers['X-Api-Key'] = apiKey;
|
||||
}
|
||||
|
||||
@@ -60,6 +60,12 @@ export async function requestWithMeta<TResponse = unknown>(
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// A gated `/api` surface answers a missing/wrong key with 401 (#197). Signal the shell so it can
|
||||
// point the user at the API Key screen, regardless of which screen made the call.
|
||||
if (response.status === 401) {
|
||||
notifyUnauthorized();
|
||||
}
|
||||
|
||||
throw new ApiError(response.status, await readProblemDetails(response));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ApiKeyScreen } from './ApiKeyScreen';
|
||||
|
||||
describe('ApiKeyScreen', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('renders and functions without any /api call', () => {
|
||||
const fetchSpy = vi.spyOn(window, 'fetch');
|
||||
|
||||
render(<ApiKeyScreen />);
|
||||
|
||||
expect(screen.getByText('No key')).toBeTruthy();
|
||||
expect(screen.getByText(/No key is stored in this browser/)).toBeTruthy();
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('saves a pasted key to local storage and shows the key-set state', () => {
|
||||
render(<ApiKeyScreen />);
|
||||
|
||||
fireEvent.change(screen.getByLabelText('API key'), { target: { value: ' secret-123 ' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save key' }));
|
||||
|
||||
// Trimmed and written through to the shared ctv-api-key slot.
|
||||
expect(window.localStorage.getItem('ctv-api-key')).toBe('secret-123');
|
||||
expect(screen.getByText('Key set')).toBeTruthy();
|
||||
expect(screen.getByText(/Key saved/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('does not render the stored key value in plaintext', () => {
|
||||
window.localStorage.setItem('ctv-api-key', 'super-secret');
|
||||
|
||||
render(<ApiKeyScreen />);
|
||||
|
||||
expect(screen.getByText('Key set')).toBeTruthy();
|
||||
// The masked state never echoes the stored key back to the DOM.
|
||||
expect(screen.queryByText(/super-secret/)).toBeNull();
|
||||
expect(document.body.innerHTML).not.toContain('super-secret');
|
||||
});
|
||||
|
||||
it('clears a stored key', () => {
|
||||
window.localStorage.setItem('ctv-api-key', 'super-secret');
|
||||
|
||||
render(<ApiKeyScreen />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Clear key' }));
|
||||
|
||||
expect(window.localStorage.getItem('ctv-api-key')).toBeNull();
|
||||
expect(screen.getByText('No key')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('ignores a save with only whitespace', () => {
|
||||
render(<ApiKeyScreen />);
|
||||
|
||||
const save = screen.getByRole('button', { name: 'Save key' });
|
||||
expect(save.hasAttribute('disabled')).toBe(true);
|
||||
|
||||
fireEvent.change(screen.getByLabelText('API key'), { target: { value: ' ' } });
|
||||
expect(save.hasAttribute('disabled')).toBe(true);
|
||||
expect(window.localStorage.getItem('ctv-api-key')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useState } from 'react';
|
||||
import { Check, KeyRound, ShieldCheck, Trash2, TriangleAlert } from 'lucide-react';
|
||||
import { Badge, Button, Card, Input } from '../components';
|
||||
import { clearStoredApiKey, getStoredApiKey, setStoredApiKey } from '../api';
|
||||
|
||||
// The one screen that must work with ZERO successful `/api` calls: a keyless first load 401s every
|
||||
// read, so this screen relies only on localStorage (auth.ts helpers) and never fetches from `/api`.
|
||||
// It's how a fresh install gets its key in before anything else can load (#280 / #197).
|
||||
export function ApiKeyScreen() {
|
||||
const [hasKey, setHasKey] = useState(() => getStoredApiKey() !== null);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [justSaved, setJustSaved] = useState(false);
|
||||
|
||||
const trimmed = draft.trim();
|
||||
|
||||
const save = () => {
|
||||
if (trimmed.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setStoredApiKey(trimmed);
|
||||
setHasKey(true);
|
||||
setDraft('');
|
||||
setJustSaved(true);
|
||||
};
|
||||
|
||||
const clear = () => {
|
||||
clearStoredApiKey();
|
||||
setHasKey(false);
|
||||
setJustSaved(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="ctv-collections">
|
||||
<Card
|
||||
actions={
|
||||
hasKey ? (
|
||||
<Badge tone="ok">Key set</Badge>
|
||||
) : (
|
||||
<Badge tone="warn">No key</Badge>
|
||||
)
|
||||
}
|
||||
padded
|
||||
subtitle="This server requires an API key on every request. The server generates one on first run and writes it to /config/api.key on the server host — open that file and paste its contents below."
|
||||
title="API Key"
|
||||
>
|
||||
{hasKey ? (
|
||||
<div className="ctv-settings-warn-callout" role="status" style={{ borderColor: 'var(--status-ok)' }}>
|
||||
<ShieldCheck aria-hidden="true" color="var(--status-ok)" size={15} />
|
||||
<span>A key is stored in this browser. It's sent with every request to this server.</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="ctv-settings-warn-callout" role="status">
|
||||
<TriangleAlert aria-hidden="true" color="var(--status-warn)" size={15} />
|
||||
<span>No key is stored in this browser, so requests to this server will be rejected. Paste your key to continue.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Input
|
||||
label={hasKey ? 'Replace key' : 'API key'}
|
||||
leadingIcon={<KeyRound aria-hidden="true" size={14} />}
|
||||
onChange={(event) => {
|
||||
setDraft(event.target.value);
|
||||
setJustSaved(false);
|
||||
}}
|
||||
placeholder="Paste the contents of /config/api.key"
|
||||
style={{ fontFamily: 'var(--font-mono)' }}
|
||||
type="password"
|
||||
value={draft}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="ctv-channels-actionbar" style={{ marginTop: 16 }}>
|
||||
{justSaved && (
|
||||
<span style={{ alignItems: 'center', color: 'var(--status-ok)', display: 'inline-flex', gap: 6 }}>
|
||||
<Check aria-hidden="true" size={14} />
|
||||
<span>Key saved — reload a screen to load its data.</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="ctv-channels-spacer" />
|
||||
{hasKey && (
|
||||
<Button onClick={clear} startIcon={<Trash2 aria-hidden="true" size={14} />} variant="ghost">
|
||||
Clear key
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
disabled={trimmed.length === 0}
|
||||
onClick={save}
|
||||
startIcon={<Check aria-hidden="true" size={14} />}
|
||||
variant="primary"
|
||||
>
|
||||
Save key
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4424,3 +4424,44 @@ body {
|
||||
font-weight: 600;
|
||||
color: var(--ctv-text);
|
||||
}
|
||||
|
||||
/* API-key required banner — shell-level 401 pointer (#197). */
|
||||
.ctv-auth-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-5, 10px);
|
||||
margin: 12px 24px 0;
|
||||
padding: 10px 14px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--ctv-warn-soft);
|
||||
border: 1px solid var(--status-warn);
|
||||
font: var(--text-sm) / 1.4 var(--font-sans);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.ctv-auth-banner-text {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.ctv-auth-banner-link {
|
||||
border: 1px solid var(--ctv-accent);
|
||||
background: transparent;
|
||||
color: var(--ctv-accent);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 4px 10px;
|
||||
font: var(--text-xs) / 1 var(--font-sans);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ctv-auth-banner-dismiss {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
padding: 4px;
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user