Add project files.

This commit is contained in:
2026-05-30 02:16:39 +02:00
parent bbcb9e22ab
commit 20c0c33cde
8 changed files with 239 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
<Solution>
<Project Path="StreamingGateway/StreamingGateway.csproj" />
</Solution>
@@ -0,0 +1,52 @@
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)
{
this.options = options.Value;
rsa = RSA.Create();
rsa.ImportFromPem(File.ReadAllText(this.options.PublicKeyPath));
validationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = this.options.Issuer,
ValidateAudience = true,
ValidAudience = this.options.Audience,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new RsaSecurityKey(rsa),
ValidAlgorithms = [SecurityAlgorithms.RsaSha256],
ClockSkew = TimeSpan.FromSeconds(30),
};
}
public async Task<string?> TryGetPrefixAsync(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 prefix)
? prefix as string
: null;
}
public void Dispose() => rsa.Dispose();
}
@@ -0,0 +1,21 @@
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 MediaPathPrefix { get; set; } = "/media";
}
@@ -0,0 +1,57 @@
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();
var prefix = await ticketValidator.TryGetPrefixAsync(token);
if (prefix is null)
{
logger.LogWarning("Rejected media request {Path}: missing or invalid ticket", path);
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
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);
}
}
+35
View File
@@ -0,0 +1,35 @@
using Musify.StreamingGateway.Authentication;
using Musify.StreamingGateway.Configuration;
using Musify.StreamingGateway.Middleware;
var builder = WebApplication.CreateBuilder(args);
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 => policy
.WithOrigins(allowedOrigins)
.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"));
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"
}
}
}
}
+16
View File
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>Musify.StreamingGateway</RootNamespace>
<UserSecretsId>media-gateway-2f1c9b6a-7d3e-4c0a-9a21-0b8e5d4c3f10</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.14.0" />
<PackageReference Include="Yarp.ReverseProxy" Version="2.3.0" />
</ItemGroup>
</Project>
+41
View File
@@ -0,0 +1,41 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Yarp": "Information"
}
},
"AllowedHosts": "*",
"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/" }
}
}
}
}
}