Files
ersatztv/ErsatzTV/Serialization/ApiSecuritySchemeDocumentTransformer.cs
T
timothyandClaude Opus 4.8 0b23d4b6b1
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 7s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m28s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 5m42s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
feat(api): #295 PR1 — browser SPA session auth (session-OR-key gate, server-only)
Implements the ratified #295 design (PR1, server-only, backward compatible). The
/api surface now accepts a valid X-Api-Key (machine) OR an authenticated session
(browser cookie, local login or OIDC), gated by the evolved ApiAuthorizationFilter
(renamed from ApiKeyAuthorizationFilter; same fail-closed EndpointRequiresKey
predicate). Machine/key behavior is byte-identical and the SPA keeps working via
its stored key — the SPA login flow lands in PR2.

- ApiAuthorizationFilter: key-first (CSRF-immune) then session; session-authed
  mutations require the X-CSRF header (403 otherwise). Attributes renamed
  [RequiresApiKey]->[RequiresAuthentication], [SkipApiKeyAuthorization]->[SkipApiAuthorization].
- Cookie scheme ctv-session always registered (Lax/SameAsRequest/14d sliding, 401 not
  redirect for /api); OIDC handler revived when configured (profile scope, userinfo,
  auth-method claim); UseAuthentication/UseAuthorization/UseRateLimiter revived in the
  legacy MapWhen branch.
- Local admin = single credential in ConfigElement rows (username / PBKDF2 hash via
  Microsoft.Extensions.Identity.Core / rotating security stamp) — NO DB migration.
  Password change rotates the stamp; CookieSecurityStampValidator revokes stale local
  sessions. Env-seed recovery (Auth:LocalAdmin:*) via LocalAdminSeedService.
- AuthController /api/auth/{config,session,setup,login,logout,password} + browser-nav
  GET /auth/oidc/login; excluded from OpenAPI (machine-audience spec). Per-IP rate limit
  on login/setup/password; dummy-hash verify (no user enumeration).
- ForwardedHeaders now strict opt-in: X-Forwarded-* ignored unless KnownProxies/Networks
  configured (rate-limiter IP + cookie-Secure integrity). Deployment: operators behind a
  proxy must set ForwardedHeaders:KnownProxies.
- Tests: session/CSRF filter cases + 17 Application/Auth handler tests; full ErsatzTV.Tests
  green (1499). No OpenAPI/generated-artifact drift.
- Docs: api-conventions section 9 rewritten; decisions.md entry (supersedes #206 inert-OIDC note).

Refs #295 #197 #206 #58

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 16:14:54 +02:00

104 lines
4.8 KiB
C#

#nullable enable
using ErsatzTV.Filters;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;
namespace ErsatzTV.Serialization;
/// <summary>
/// OpenAPI document transformer that declares the components the per-operation transformers reference:
/// the <c>ApiKey</c> security scheme (<c>X-Api-Key</c> request header) used by
/// <see cref="ApiSecurityOperationTransformer" />, and the <c>ValidationProblemDetails</c> schema used
/// by <see cref="ValidationProblemOperationTransformer" /> for documented <c>400</c> responses. Runs on
/// the "v1" document only. See issues #286/#287.
/// </summary>
public static class ApiSecuritySchemeDocumentTransformer
{
public const string ValidationProblemDetailsSchemaId = "ValidationProblemDetails";
public const string ProblemDetailsSchemaId = "ProblemDetails";
public static Task TransformAsync(
OpenApiDocument document,
OpenApiDocumentTransformerContext context,
CancellationToken cancellationToken)
{
document.Components ??= new OpenApiComponents();
document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
document.Components.SecuritySchemes[ApiSecurityOperationTransformer.SchemeName] = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.ApiKey,
Name = ApiAuthorizationFilter.HeaderName,
In = ParameterLocation.Header,
Description =
"API key sent in the 'X-Api-Key' request header. Required for all mutating requests and, " +
"under the default posture (Api:RequireKeyForReads=true), for reads as well."
};
document.Components.Schemas ??= new Dictionary<string, IOpenApiSchema>();
if (!document.Components.Schemas.ContainsKey(ValidationProblemDetailsSchemaId))
{
document.Components.Schemas[ValidationProblemDetailsSchemaId] = BuildValidationProblemDetailsSchema();
}
// The injected 401 (ApiSecurityOperationTransformer) references the ProblemDetails schema. It
// normally already exists because other actions declare ProducesResponseType(typeof(ProblemDetails)),
// but self-provision it if absent so the 401 reference never dangles (belt-and-suspenders).
if (!document.Components.Schemas.ContainsKey(ProblemDetailsSchemaId))
{
document.Components.Schemas[ProblemDetailsSchemaId] = BuildProblemDetailsSchema();
}
return Task.CompletedTask;
}
// The RFC 7807 shape ASP.NET Core returns for a plain ProblemDetails response (the ValidationProblemDetails
// members minus the "errors" map).
private static OpenApiSchema BuildProblemDetailsSchema() =>
new()
{
Type = JsonSchemaType.Object,
Properties = new Dictionary<string, IOpenApiSchema>
{
["type"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
["title"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
["status"] = new OpenApiSchema
{
Type = JsonSchemaType.Integer | JsonSchemaType.Null,
Format = "int32"
},
["detail"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
["instance"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null }
}
};
// The RFC 7807 shape ASP.NET Core's [ApiController] + FluentValidation return on a model-binding /
// validation failure: the standard ProblemDetails members plus an "errors" map of field -> messages.
private static OpenApiSchema BuildValidationProblemDetailsSchema() =>
new()
{
Type = JsonSchemaType.Object,
Properties = new Dictionary<string, IOpenApiSchema>
{
["type"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
["title"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
["status"] = new OpenApiSchema
{
Type = JsonSchemaType.Integer | JsonSchemaType.Null,
Format = "int32"
},
["detail"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
["instance"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
["errors"] = new OpenApiSchema
{
Type = JsonSchemaType.Object,
AdditionalProperties = new OpenApiSchema
{
Type = JsonSchemaType.Array,
Items = new OpenApiSchema { Type = JsonSchemaType.String }
}
}
}
};
}