Files
Musify/backend/Hosts/Musify.StreamingGateway/Authentication/TicketValidator.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

69 lines
2.6 KiB
C#

using System.Security.Cryptography;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using Musify.StreamingGateway.Configuration;
namespace Musify.StreamingGateway.Authentication;
/// <param name="Prefix">The storage key prefix the ticket authorizes reading from. Empty means the
/// ticket was missing, malformed, expired, or otherwise invalid.</param>
/// <param name="MaxBytes">When set, the caller is limited to the first <c>MaxBytes</c> bytes of the
/// object — the anonymous preview fragment cap carried by the <c>maxBytes</c> claim.</param>
public sealed record TicketValidationResult(string Prefix, long? MaxBytes)
{
public static readonly TicketValidationResult Invalid = new(string.Empty, null);
public bool IsValid => Prefix.Length > 0;
}
public sealed class TicketValidator : IDisposable
{
private readonly StreamTicketValidationOptions _options;
private readonly RSA _rsa;
private readonly TokenValidationParameters _validationParameters;
private readonly JsonWebTokenHandler _handler = new();
public TicketValidator(IOptions<StreamTicketValidationOptions> options)
{
_options = options.Value;
_rsa = RSA.Create();
_rsa.ImportFromPem(File.ReadAllText(_options.PublicKeyPath));
_validationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = _options.Issuer,
ValidateAudience = true,
ValidAudience = _options.Audience,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new RsaSecurityKey(_rsa),
ValidAlgorithms = [SecurityAlgorithms.RsaSha256],
ClockSkew = TimeSpan.FromSeconds(30),
};
}
public async Task<TicketValidationResult> ValidateTicketAsync(string? token)
{
if (string.IsNullOrWhiteSpace(token))
return TicketValidationResult.Invalid;
var result = await _handler.ValidateTokenAsync(token, _validationParameters);
if (!result.IsValid)
return TicketValidationResult.Invalid;
var prefix = result.ClaimsIdentity?.FindFirst("prefix")?.Value;
if (string.IsNullOrEmpty(prefix))
return TicketValidationResult.Invalid;
var maxBytesClaim = result.ClaimsIdentity?.FindFirst("maxBytes")?.Value;
var maxBytes = long.TryParse(maxBytesClaim, out var parsed) ? parsed : (long?)null;
return new TicketValidationResult(prefix, maxBytes);
}
public void Dispose() => _rsa.Dispose();
}