Files
Musify/backend/Hosts/Musify.StreamingGateway/Middleware/TicketValidationMiddleware.cs
T
Admin 356e5c1101 Add anonymous playback with an optional Spotify-style preview cap
New Playback:AllowAnonymousListening / Playback:AnonymousFragmentSeconds
settings control whether a request without a session can stream at all,
and if so, whether it's limited to a fragment instead of the full track:

- GET /tracks/{id}/stream and GET /youtube/tracks/{videoId}/stream no
  longer require authorization outright; the handlers gate on the config
  instead, so both keep working exactly as before when it's off (the
  default).
- The fragment cap is enforced by the Streaming Gateway, not the client:
  the stream ticket now carries an optional maxBytes claim (computed from
  AnonymousFragmentSeconds and the transcoder's known bitrate), and
  TicketValidationMiddleware clamps the Range it forwards to SeaweedFS to
  stay under it — synthesizing one if the request didn't send one, and
  answering 416 outright if the requested range starts past the cap.
- A YouTube track that hasn't been provisioned server-side yet streams
  straight from YouTube's CDN, bypassing the Gateway entirely — there's no
  way to cap that, so an anonymous request for one is refused (409) instead
  of silently handing out an uncapped stream.
- ListeningHistory has a non-nullable UserId, so anonymous plays simply
  don't get recorded rather than trying to force a row through the FK.

Also fixes a real, pre-existing bug this surfaced: the AppSettings.Development.json
of the Api, Worker, and StreamingGateway all pointed StreamTicket/Workers
paths at "../../deploy/..." — one directory short of deploy/'s actual
location at the repo root relative to each project's own folder. Docker
never hit this (it mounts an absolute /keys path), so it had apparently
never been exercised via `dotnet run` before.
2026-09-10 09:56:57 +02:00

116 lines
4.6 KiB
C#

using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
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.IsValid)
{
logger.LogWarning("Rejected media request {Path}: missing or invalid ticket", path);
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
var prefix = validation.Prefix;
var objectKey = remaining.Value?.TrimStart('/') ?? string.Empty;
if (HasTraversalSegment(objectKey))
{
logger.LogWarning("Rejected media request {ObjectKey}: contains a path traversal segment", objectKey);
context.Response.StatusCode = StatusCodes.Status400BadRequest;
return;
}
var prefixBoundary = prefix.EndsWith('/') ? prefix : prefix + "/";
if (!string.Equals(objectKey, prefix, StringComparison.Ordinal)
&& !objectKey.StartsWith(prefixBoundary, StringComparison.Ordinal))
{
logger.LogWarning("Rejected media request {ObjectKey}: outside authorized prefix {Prefix}", objectKey, prefix);
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
if (validation.MaxBytes is { } maxBytes && !TryClampRange(context, maxBytes))
{
logger.LogInformation(
"Rejected media request {ObjectKey}: requested range starts beyond the {MaxBytes}-byte preview limit",
objectKey, maxBytes);
context.Response.StatusCode = StatusCodes.Status416RangeNotSatisfiable;
context.Response.Headers[HeaderNames.ContentRange] = $"bytes */{maxBytes}";
return;
}
StripQueryParameter(context, options.QueryParameterName);
await next(context);
}
/// <summary>Rewrites the request's <c>Range</c> header so nothing past <paramref name="maxBytes"/>
/// is ever asked of the filer — this is what actually enforces the anonymous preview length,
/// downstream of the ticket carrying that cap. A request with no <c>Range</c> header (a plain,
/// whole-file GET) gets one synthesized, so the filer always responds with a bounded 206 instead of
/// streaming the full object. Returns false when the requested range starts at or past the cap, in
/// which case the caller should answer 416 directly instead of proxying anything.</summary>
private static bool TryClampRange(HttpContext context, long maxBytes)
{
var rangeHeader = context.Request.Headers.Range;
if (StringValues.IsNullOrEmpty(rangeHeader))
{
context.Request.Headers.Range = $"bytes=0-{maxBytes - 1}";
return true;
}
if (!RangeHeaderValue.TryParse(rangeHeader.ToString(), out var range) || range.Ranges.Count != 1)
return true;
var requested = range.Ranges.Single();
var start = requested.From ?? 0;
if (start >= maxBytes)
return false;
var end = requested.To is { } requestedEnd ? Math.Min(requestedEnd, maxBytes - 1) : maxBytes - 1;
context.Request.Headers.Range = $"bytes={start}-{end}";
return true;
}
private static bool HasTraversalSegment(string objectKey) =>
objectKey.Split('/').Any(segment => segment is ".." or ".");
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);
}
}