Change editor rule
This commit is contained in:
@@ -3,58 +3,59 @@ using Microsoft.IdentityModel.JsonWebTokens;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Musify.StreamingGateway.Configuration;
|
||||
|
||||
namespace Musify.StreamingGateway.Authentication;
|
||||
|
||||
public sealed record TicketValidationResult(string Prefix, long? MaxBytes)
|
||||
namespace Musify.StreamingGateway.Authentication
|
||||
{
|
||||
public static readonly TicketValidationResult Invalid = new(string.Empty, null);
|
||||
|
||||
public bool IsValid => Prefix.Length > 0;
|
||||
}
|
||||
|
||||
public sealed class TicketValidator : IDisposable
|
||||
{
|
||||
private readonly RSA rsa;
|
||||
private readonly TokenValidationParameters validationParameters;
|
||||
private readonly JsonWebTokenHandler handler = new();
|
||||
|
||||
public TicketValidator(StreamTicketValidationConfiguration configuration)
|
||||
public sealed record TicketValidationResult(string Prefix, long? MaxBytes)
|
||||
{
|
||||
rsa = RSA.Create();
|
||||
rsa.ImportFromPem(File.ReadAllText(configuration.PublicKeyPath));
|
||||
public static readonly TicketValidationResult Invalid = new(string.Empty, null);
|
||||
|
||||
validationParameters = new TokenValidationParameters
|
||||
public bool IsValid => Prefix.Length > 0;
|
||||
}
|
||||
|
||||
public sealed class TicketValidator : IDisposable
|
||||
{
|
||||
private readonly RSA rsa;
|
||||
private readonly TokenValidationParameters validationParameters;
|
||||
private readonly JsonWebTokenHandler handler = new();
|
||||
|
||||
public TicketValidator(StreamTicketValidationConfiguration configuration)
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = configuration.Issuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = configuration.Audience,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new RsaSecurityKey(rsa),
|
||||
ValidAlgorithms = [SecurityAlgorithms.RsaSha256],
|
||||
ClockSkew = TimeSpan.FromSeconds(30),
|
||||
};
|
||||
rsa = RSA.Create();
|
||||
rsa.ImportFromPem(File.ReadAllText(configuration.PublicKeyPath));
|
||||
|
||||
validationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = configuration.Issuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = configuration.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();
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
+14
-13
@@ -1,23 +1,24 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Musify.StreamingGateway.Configuration;
|
||||
|
||||
public sealed class StreamTicketValidationConfiguration
|
||||
namespace Musify.StreamingGateway.Configuration
|
||||
{
|
||||
public const string SectionName = "StreamTicket";
|
||||
public sealed class StreamTicketValidationConfiguration
|
||||
{
|
||||
public const string SectionName = "StreamTicket";
|
||||
|
||||
[Required]
|
||||
public required string PublicKeyPath { get; set; }
|
||||
[Required]
|
||||
public required string PublicKeyPath { get; set; }
|
||||
|
||||
[Required]
|
||||
public string Audience { get; set; } = "media-gateway";
|
||||
[Required]
|
||||
public string Audience { get; set; } = "media-gateway";
|
||||
|
||||
[Required]
|
||||
public string Issuer { get; set; } = "musify-webapi";
|
||||
[Required]
|
||||
public string Issuer { get; set; } = "musify-webapi";
|
||||
|
||||
public string QueryParameterName { get; set; } = "t";
|
||||
public string QueryParameterName { get; set; } = "t";
|
||||
|
||||
public string HeaderName { get; set; } = "X-Stream-Ticket";
|
||||
public string HeaderName { get; set; } = "X-Stream-Ticket";
|
||||
|
||||
public string MediaPathPrefix { get; set; } = "/media";
|
||||
public string MediaPathPrefix { get; set; } = "/media";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,112 +3,113 @@ 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,
|
||||
StreamTicketValidationConfiguration options,
|
||||
ILogger<TicketValidationMiddleware> logger)
|
||||
namespace Musify.StreamingGateway.Middleware
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
public sealed class TicketValidationMiddleware(
|
||||
RequestDelegate next,
|
||||
TicketValidator ticketValidator,
|
||||
StreamTicketValidationConfiguration options,
|
||||
ILogger<TicketValidationMiddleware> logger)
|
||||
{
|
||||
var path = context.Request.Path;
|
||||
|
||||
if (!path.StartsWithSegments(options.MediaPathPrefix, out var remaining))
|
||||
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 is a suffix range or 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);
|
||||
return;
|
||||
}
|
||||
|
||||
var token = context.Request.Query[options.QueryParameterName].ToString();
|
||||
if (string.IsNullOrEmpty(token))
|
||||
private static bool TryClampRange(HttpContext context, long maxBytes)
|
||||
{
|
||||
token = context.Request.Headers[options.HeaderName].ToString();
|
||||
}
|
||||
var rangeHeader = context.Request.Headers.Range;
|
||||
if (StringValues.IsNullOrEmpty(rangeHeader))
|
||||
{
|
||||
context.Request.Headers.Range = $"bytes=0-{maxBytes - 1}";
|
||||
return true;
|
||||
}
|
||||
|
||||
var validation = await ticketValidator.ValidateTicketAsync(token);
|
||||
if (!RangeHeaderValue.TryParse(rangeHeader.ToString(), out var range)
|
||||
|| range.Ranges.Count != 1
|
||||
|| !string.Equals(range.Unit.ToString(), "bytes", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
context.Request.Headers.Range = $"bytes=0-{maxBytes - 1}";
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!validation.IsValid)
|
||||
{
|
||||
logger.LogWarning("Rejected media request {Path}: missing or invalid ticket", path);
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
return;
|
||||
}
|
||||
var requested = range.Ranges.Single();
|
||||
if (requested.From is null)
|
||||
return false;
|
||||
|
||||
var prefix = validation.Prefix;
|
||||
var objectKey = remaining.Value?.TrimStart('/') ?? string.Empty;
|
||||
var start = requested.From.Value;
|
||||
if (start >= maxBytes)
|
||||
return false;
|
||||
|
||||
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 is a suffix range or 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);
|
||||
}
|
||||
|
||||
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}";
|
||||
var end = requested.To is { } requestedEnd ? Math.Min(requestedEnd, maxBytes - 1) : maxBytes - 1;
|
||||
context.Request.Headers.Range = $"bytes={start}-{end}";
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!RangeHeaderValue.TryParse(rangeHeader.ToString(), out var range)
|
||||
|| range.Ranges.Count != 1
|
||||
|| !string.Equals(range.Unit.ToString(), "bytes", StringComparison.OrdinalIgnoreCase))
|
||||
private static bool HasTraversalSegment(string objectKey) =>
|
||||
objectKey.Split('/').Any(segment => segment is ".." or ".");
|
||||
|
||||
private static void StripQueryParameter(HttpContext context, string name)
|
||||
{
|
||||
context.Request.Headers.Range = $"bytes=0-{maxBytes - 1}";
|
||||
return true;
|
||||
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);
|
||||
}
|
||||
|
||||
var requested = range.Ranges.Single();
|
||||
if (requested.From is null)
|
||||
return false;
|
||||
|
||||
var start = requested.From.Value;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user