chore: group .NET into backend/ and drop non-.NET test artifacts
- Move all .NET (6 projects, solution, Directory.*.props, nuget.config) into backend/ so the monorepo root can host non-.NET projects later - Remove throwaway test artifacts: player.html, pl.json - Trim dead Flutter rules from .gitignore Build from backend/Musify.slnx: 0 warnings, 0 errors.
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
using System.Security.Cryptography;
|
||||
using Ardalis.Result;
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<Result<string>> ValidateTicketAsync(string? token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
return Result.Unauthorized();
|
||||
|
||||
var result = await _handler.ValidateTokenAsync(token, _validationParameters);
|
||||
if (!result.IsValid)
|
||||
return Result.Unauthorized();
|
||||
|
||||
if (!result.Claims.TryGetValue("prefix", out var claim))
|
||||
return Result.Unauthorized();
|
||||
|
||||
if (claim is not string prefix)
|
||||
return Result.Unauthorized();
|
||||
|
||||
if (string.IsNullOrEmpty(prefix))
|
||||
return Result.Unauthorized();
|
||||
|
||||
return Result.Success(prefix);
|
||||
}
|
||||
|
||||
public void Dispose() => _rsa.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Musify.StreamingGateway.Configuration;
|
||||
|
||||
public sealed class StreamTicketValidationOptions
|
||||
{
|
||||
public const string SectionName = "StreamTicket";
|
||||
|
||||
[Required]
|
||||
public required string PublicKeyPath { get; set; }
|
||||
|
||||
[Required]
|
||||
public string Audience { get; set; } = "media-gateway";
|
||||
|
||||
[Required]
|
||||
public string Issuer { get; set; } = "musify-webapi";
|
||||
|
||||
public string QueryParameterName { get; set; } = "t";
|
||||
|
||||
public string HeaderName { get; set; } = "X-Stream-Ticket";
|
||||
|
||||
public string MediaPathPrefix { get; set; } = "/media";
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
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.IsSuccess)
|
||||
{
|
||||
logger.LogWarning("Rejected media request {Path}: missing or invalid ticket", path);
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
return;
|
||||
}
|
||||
|
||||
var prefix = validation.Value;
|
||||
|
||||
var objectKey = remaining.Value?.TrimStart('/') ?? string.Empty;
|
||||
if (!objectKey.StartsWith(prefix, StringComparison.Ordinal))
|
||||
{
|
||||
logger.LogWarning("Rejected media request {ObjectKey}: outside authorized prefix {Prefix}", objectKey, prefix);
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
return;
|
||||
}
|
||||
|
||||
StripQueryParameter(context, options.QueryParameterName);
|
||||
await next(context);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<UserSecretsId>media-gateway-2f1c9b6a-7d3e-4c0a-9a21-0b8e5d4c3f10</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Ardalis.Result" />
|
||||
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />
|
||||
<PackageReference Include="Yarp.ReverseProxy" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,42 @@
|
||||
using Musify.StreamingGateway.Authentication;
|
||||
using Musify.StreamingGateway.Configuration;
|
||||
using Musify.StreamingGateway.Middleware;
|
||||
|
||||
var builder = WebApplication.CreateBuilder();
|
||||
|
||||
builder.Services
|
||||
.AddOptions<StreamTicketValidationOptions>()
|
||||
.Bind(builder.Configuration.GetRequiredSection(StreamTicketValidationOptions.SectionName))
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
builder.Services.AddSingleton<TicketValidator>();
|
||||
|
||||
const string corsPolicy = "media-clients";
|
||||
var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
|
||||
builder.Services.AddCors(options => options.AddPolicy(corsPolicy, policy =>
|
||||
{
|
||||
if (builder.Environment.IsDevelopment())
|
||||
policy.AllowAnyOrigin();
|
||||
else
|
||||
policy.WithOrigins(allowedOrigins);
|
||||
|
||||
policy.AllowAnyHeader()
|
||||
.WithMethods("GET", "HEAD")
|
||||
.WithExposedHeaders("Content-Range", "Accept-Ranges", "Content-Length");
|
||||
} ));
|
||||
|
||||
builder.Services
|
||||
.AddReverseProxy()
|
||||
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapGet("/health", () => Results.Ok("healthy"))
|
||||
.WithSummary("Health Check Endpoint");
|
||||
|
||||
app.UseCors(corsPolicy);
|
||||
app.UseMiddleware<TicketValidationMiddleware>();
|
||||
app.MapReverseProxy();
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"StreamingGateway": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:8081",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"StreamTicket": {
|
||||
"PublicKeyPath": "D:\\weed\\stream_public.pem",
|
||||
"Audience": "media-gateway",
|
||||
"Issuer": "musify-webapi",
|
||||
"QueryParameterName": "t",
|
||||
"MediaPathPrefix": "/media"
|
||||
},
|
||||
|
||||
"Cors": {
|
||||
"AllowedOrigins": [ "http://localhost:5173", "http://localhost:3000" ]
|
||||
},
|
||||
|
||||
"ReverseProxy": {
|
||||
"Routes": {
|
||||
"media": {
|
||||
"ClusterId": "seaweed-filer",
|
||||
"Match": { "Path": "/media/{**rest}" },
|
||||
"Transforms": [
|
||||
{ "PathPattern": "/buckets/webapi-storage/{**rest}" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"Clusters": {
|
||||
"seaweed-filer": {
|
||||
"Destinations": {
|
||||
"filer": { "Address": "http://localhost:8888/" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Yarp": "Information"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
Reference in New Issue
Block a user