Files
Musify/backend/Tests/Musify.Infrastructure.Tests/Services/StreamTicketServiceTests.cs
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

110 lines
4.0 KiB
C#

using System.Security.Cryptography;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using Musify.Infrastructure.Configuration;
using Musify.Infrastructure.Services;
using Xunit;
namespace Musify.Infrastructure.Tests.Services
{
public sealed class StreamTicketServiceTests : IDisposable
{
private readonly string privateKeyPath = Path.GetTempFileName();
private readonly RSA rsa = RSA.Create(2048);
public StreamTicketServiceTests() => File.WriteAllText(privateKeyPath, rsa.ExportPkcs8PrivateKeyPem());
public void Dispose()
{
rsa.Dispose();
File.Delete(privateKeyPath);
}
private StreamTicketService CreateService(int ticketTtlSeconds = 3600) => new(new StreamTicketConfiguration
{
PrivateKeyPath = privateKeyPath,
Audience = "media-gateway",
Issuer = "musify-webapi",
TicketTtlSeconds = ticketTtlSeconds
});
[Fact]
public void IssueTicket_ReturnsATokenSignedWithTheConfiguredKeyAndClaims()
{
using var service = CreateService(ticketTtlSeconds: 120);
var ticket = service.IssueTicket(userId: 42, keyPrefix: "Tracks/ProcessedAudios/abc/");
Assert.Equal(120, ticket.ExpiresInSeconds);
var handler = new JsonWebTokenHandler();
var jwt = handler.ReadJsonWebToken(ticket.Token);
Assert.Equal("42", jwt.GetClaim("sub").Value);
Assert.Equal("Tracks/ProcessedAudios/abc/", jwt.GetClaim("prefix").Value);
Assert.Equal("musify-webapi", jwt.Issuer);
Assert.Contains("media-gateway", jwt.Audiences);
}
[Fact]
public void IssueTicket_AnonymousUser_OmitsTheSubClaim()
{
using var service = CreateService();
var ticket = service.IssueTicket(userId: null, keyPrefix: "Tracks/ProcessedAudios/abc/");
var handler = new JsonWebTokenHandler();
var jwt = handler.ReadJsonWebToken(ticket.Token);
Assert.DoesNotContain(jwt.Claims, c => c.Type == "sub");
Assert.Equal("Tracks/ProcessedAudios/abc/", jwt.GetClaim("prefix").Value);
}
[Fact]
public void IssueTicket_WithMaxBytes_IncludesTheMaxBytesClaim()
{
using var service = CreateService();
var ticket = service.IssueTicket(userId: null, keyPrefix: "Tracks/ProcessedAudios/abc/", maxBytes: 480_000);
var handler = new JsonWebTokenHandler();
var jwt = handler.ReadJsonWebToken(ticket.Token);
Assert.Equal("480000", jwt.GetClaim("maxBytes").Value);
}
[Fact]
public void IssueTicket_WithoutMaxBytes_OmitsTheMaxBytesClaim()
{
using var service = CreateService();
var ticket = service.IssueTicket(userId: 1, keyPrefix: "Tracks/ProcessedAudios/abc/");
var handler = new JsonWebTokenHandler();
var jwt = handler.ReadJsonWebToken(ticket.Token);
Assert.DoesNotContain(jwt.Claims, c => c.Type == "maxBytes");
}
[Fact]
public async Task IssueTicket_TokenValidatesAgainstTheMatchingPublicKey()
{
using var service = CreateService();
var ticket = service.IssueTicket(userId: 1, keyPrefix: "Tracks/ProcessedAudios/xyz/");
var publicKeyPem = rsa.ExportSubjectPublicKeyInfoPem();
using var verifyingRsa = RSA.Create();
verifyingRsa.ImportFromPem(publicKeyPem);
var handler = new JsonWebTokenHandler();
var result = await handler.ValidateTokenAsync(ticket.Token, new TokenValidationParameters
{
ValidIssuer = "musify-webapi",
ValidAudience = "media-gateway",
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
IssuerSigningKey = new RsaSecurityKey(verifyingRsa),
});
Assert.True(result.IsValid);
}
}
}