Files
ersatztv/ErsatzTV.Tests/Filters/ApiKeyEndpointRequiresKeyTests.cs
T
timothyandClaude Opus 4.8 ef2bd65c27
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 10s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 10s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 1m12s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 3m4s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m17s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 10m36s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
feat(api): #286 — mount the whole /api surface at /api/v1
Version every /api route to /api/v1 (251 controller routes + ~24 Location
headers + the scanner callback URL + the Startup request-log literal),
uniform across the machine API, auth, scanner and scripted-build surfaces.

Add ApiVersionRewriteMiddleware: a legacy unversioned /api/* request is
rewritten (NOT redirected) to /api/v1/* in-pipeline — method, body, auth
headers and query survive — carrying RFC 8594 Deprecation/Sunset headers,
so curl / the future MCP server / bookmarks keep working. An already-
versioned path passes through; a future /api/v2 is never forced to v1.

Standardize the route convention (leading-slash absolute route per method,
no class-[Route] — except the two Scanner/Scripted controllers whose ~all
actions share a parametrized {id} prefix), enforced by ApiRouteVersioningTests
(^/api/v\d+/ over the whole Controllers.Api surface; browser-nav
/auth/oidc/login is out of scope).

Regenerate v1.json (160 paths, all /api/v1)/endpoint-index/v1.d.ts; sweep 945
SPA request literals + the test mocks (regex + positional URL parsers). /api/v1
is additive-only after freeze; the legacy-rewrite shim sunsets in ~2 releases
(owner decision) with removal tracked as a Phase-3 follow-up.

Docs: decisions.md 2026-07-13, api-conventions §1/§9, rest-api/spa-conventions/
blazor-route-parity/e2e-local/domain-model.

fixes #286
refs #197

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 00:30:20 +02:00

133 lines
5.2 KiB
C#

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 NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Filters;
/// <summary>
/// Proves the shared <see cref="ApiAuthorizationFilter.EndpointRequiresKey" /> predicate — the one
/// the OpenAPI security/401 transformer consumes — agrees with what the filter actually enforces at
/// runtime, across a representative matrix. If the two ever diverged, the spec could claim an endpoint
/// is open while the filter gates it (or vice-versa); this test is the anti-drift guard (#287).
/// </summary>
[TestFixture]
public class ApiKeyEndpointRequiresKeyTests
{
private const string Key = "secret";
private sealed class FakeApiKeyProvider(bool requireKeyForReads) : IApiKeyProvider
{
public string ApiKey => Key;
public bool RequireKeyForReads { get; } = requireKeyForReads;
}
// (method, requiresApiKey, skip, requireKeyForReads, expectedRequiresKey)
private static readonly object[] Matrix =
[
new object[] { "POST", false, false, false, true }, // write always gated
new object[] { "PUT", false, false, false, true },
new object[] { "PATCH", false, false, false, true },
new object[] { "DELETE", false, false, false, true },
new object[] { "GET", false, false, true, true }, // read gated when reads-required
new object[] { "GET", false, false, false, false }, // read open when reads-not-required
new object[] { "GET", true, false, false, true }, // [RequiresAuthentication] gates read even so
new object[] { "HEAD", false, false, false, false }, // read verb, open
new object[] { "OPTIONS", false, false, true, false },// preflight always exempt
new object[] { "POST", false, true, false, false } // [SkipApiAuthorization] exempt
];
[TestCaseSource(nameof(Matrix))]
public void Predicate_Matches_Expected(
string method,
bool requiresApiKey,
bool skip,
bool requireKeyForReads,
bool expected)
{
var metadata = new List<object>();
if (requiresApiKey)
{
metadata.Add(new RequiresAuthenticationAttribute());
}
if (skip)
{
metadata.Add(new SkipApiAuthorizationAttribute());
}
ApiAuthorizationFilter.EndpointRequiresKey(method, metadata, requireKeyForReads)
.ShouldBe(expected);
}
[TestCaseSource(nameof(Matrix))]
public void Predicate_Agrees_With_Filter_Enforcement(
string method,
bool requiresApiKey,
bool skip,
bool requireKeyForReads,
bool expected)
{
// The filter, on an /api path with the header MISSING, produces a 401 exactly when the predicate
// says the endpoint requires a key. Drive the real filter and compare its decision to the predicate.
AuthorizationFilterContext context = MakeContext(method, requiresApiKey, skip);
new ApiAuthorizationFilter(new FakeApiKeyProvider(requireKeyForReads)).OnAuthorization(context);
bool filterGated = context.Result is not null;
filterGated.ShouldBe(expected);
filterGated.ShouldBe(
ApiAuthorizationFilter.EndpointRequiresKey(method, Metadata(requiresApiKey, skip), requireKeyForReads));
}
[Test]
public void Filter_Never_Gates_Non_Api_Paths_Even_When_Predicate_Would()
{
// The predicate assumes an /api endpoint; the filter's path scoping precedes it. A mutating request
// outside /api must pass untouched even though the predicate (given the same method) returns true.
ApiAuthorizationFilter.EndpointRequiresKey("POST", new List<object>(), requireKeyForReads: true)
.ShouldBeTrue();
AuthorizationFilterContext context = MakeContext("POST", requiresApiKey: false, skip: false, path: "/iptv/x.m3u");
new ApiAuthorizationFilter(new FakeApiKeyProvider(requireKeyForReads: true)).OnAuthorization(context);
context.Result.ShouldBeNull();
}
private static List<object> Metadata(bool requiresApiKey, bool skip)
{
var metadata = new List<object>();
if (requiresApiKey)
{
metadata.Add(new RequiresAuthenticationAttribute());
}
if (skip)
{
metadata.Add(new SkipApiAuthorizationAttribute());
}
return metadata;
}
private static AuthorizationFilterContext MakeContext(
string method,
bool requiresApiKey,
bool skip,
string path = "/api/v1/channels")
{
var httpContext = new DefaultHttpContext();
httpContext.Request.Method = method;
httpContext.Request.Path = path;
var actionDescriptor = new ActionDescriptor { EndpointMetadata = Metadata(requiresApiKey, skip) };
var actionContext = new ActionContext(httpContext, new RouteData(), actionDescriptor);
return new AuthorizationFilterContext(actionContext, new List<IFilterMetadata>());
}
}