Files
Musify/backend/Musify.StreamingGateway/Middleware/TicketValidationMiddleware.cs
T
AdminandClaude Opus 4.8 6e469dbb4a refactor: replace Ardalis.Result with ErrorOr across the app
Ardalis Result<T> carried incoherent success sub-statuses and a clunky
generic converter; ErrorOr models success-or-errors cleanly.

- Application: all commands/queries/handlers now return ErrorOr<T>
  (non-generic Result -> ErrorOr<Success>); errors via Error.NotFound/
  Conflict/Validation/Unauthorized/Failure; success via value or new Success()
- Drop ResultExtensions.As<>(): error propagation is now just return .Errors
- Rewrite HTTP mapping (ErrorOrHttpExtensions) off Error.Type; success maps
  to 200 (value) or 204 (Success); Created still built in the endpoints
- Endpoints/gateway middleware: !IsSuccess -> IsError
- Swap Ardalis.Result package for ErrorOr 2.1.1 (remove unused ref from Worker)

Build: 0 warnings, 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 04:05:43 +02:00

64 lines
2.2 KiB
C#

using Microsoft.Extensions.Options;
using Musify.StreamingGateway.Authentication;
using Musify.StreamingGateway.Configuration;
namespace Musify.StreamingGateway.Middleware;
public sealed class TicketValidationMiddleware(
RequestDelegate next,
TicketValidator ticketValidator,
IOptions<StreamTicketValidationOptions> options,
ILogger<TicketValidationMiddleware> logger)
{
private readonly StreamTicketValidationOptions options = options.Value;
public async Task InvokeAsync(HttpContext context)
{
var path = context.Request.Path;
if (!path.StartsWithSegments(options.MediaPathPrefix, out var remaining))
{
await next(context);
return;
}
var token = context.Request.Query[options.QueryParameterName].ToString();
if (string.IsNullOrEmpty(token))
{
token = context.Request.Headers[options.HeaderName].ToString();
}
var validation = await ticketValidator.ValidateTicketAsync(token);
if (validation.IsError)
{
logger.LogWarning("Rejected media request {Path}: missing or invalid ticket", path);
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
var prefix = validation.Value;
var objectKey = remaining.Value?.TrimStart('/') ?? string.Empty;
if (!objectKey.StartsWith(prefix, StringComparison.Ordinal))
{
logger.LogWarning("Rejected media request {ObjectKey}: outside authorized prefix {Prefix}", objectKey, prefix);
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
StripQueryParameter(context, options.QueryParameterName);
await next(context);
}
private static void StripQueryParameter(HttpContext context, string name)
{
var remaining = context.Request.Query
.Where(pair => !string.Equals(pair.Key, name, StringComparison.Ordinal))
.SelectMany(pair => pair.Value.Select(value => new KeyValuePair<string, string?>(pair.Key, value)))
.ToList();
context.Request.QueryString = QueryString.Create(remaining);
}
}