Files
Musify/backend/Musify.StreamingGateway/Authentication/TicketValidator.cs
T
AdminandClaude Opus 4.8 45ce66a6ee harden(gateway): prefix-boundary + path-traversal checks; simplify ticket validation
Tighten the stream-ticket authorization in the gateway middleware:
- Enforce a path-segment boundary on the prefix check instead of a bare
  StartsWith, so a ticket for 'users/12' no longer grants 'users/1234/...'
  (exact-match still allowed for single-object grants)
- Reject object keys containing '..'/'.' segments before proxying, closing a
  path-traversal bypass that SeaweedFS would otherwise resolve outside the
  authorized prefix

Also simplify TicketValidator.ValidateTicketAsync from ErrorOr<string> to
string? (null = invalid) since it has a single failure mode; drop the now
unused ErrorOr package reference from the gateway.

Verified: build clean; the authorization predicate passes a table of cases
covering both the escalation and traversal vulnerabilities.

Build: 0 warnings, 0 errors.

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

59 lines
1.9 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;
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),
};
}
/// <summary>
/// Validates the stream ticket and returns the authorized object-key prefix,
/// or <see langword="null"/> if the ticket is missing, invalid, or carries no prefix.
/// </summary>
public async Task<string?> ValidateTicketAsync(string? token)
{
if (string.IsNullOrWhiteSpace(token))
return null;
var result = await _handler.ValidateTokenAsync(token, _validationParameters);
if (!result.IsValid)
return null;
return result.Claims.TryGetValue("prefix", out var claim)
&& claim is string prefix
&& !string.IsNullOrEmpty(prefix)
? prefix
: null;
}
public void Dispose() => _rsa.Dispose();
}