Reorganize backend to mirror Musify.slnx folder structure
Moves the six backend projects on disk into Core/ and Hosts/ subfolders, matching the solution folders already defined in Musify.slnx, so the file explorer reflects the same layout as the solution: backend/Core/Musify.Domain backend/Core/Musify.Application backend/Core/Musify.Infrastructure backend/Hosts/Musify.Api backend/Hosts/Musify.Worker backend/Hosts/Musify.StreamingGateway Updates every reference to the old paths: ProjectReference entries in Musify.Api.csproj and Musify.Worker.csproj, the three Dockerfiles, deploy/scripts/migrate.ps1|sh, deploy/zitadel/provision.ps1, deploy/up.ps1, deploy/README.md and docs/development.md. Also fixes a stale Dockerfile comment pointing at a compose file that no longer exists. Verified with `dotnet build Musify.slnx` against the new layout.
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<string> ValidateTicketAsync(string? token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
return string.Empty;
|
||||
|
||||
var result = await _handler.ValidateTokenAsync(token, _validationParameters);
|
||||
if (!result.IsValid)
|
||||
return string.Empty;
|
||||
|
||||
var prefix = result.ClaimsIdentity?.FindFirst("prefix")?.Value;
|
||||
return string.IsNullOrEmpty(prefix)? string.Empty : 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,74 @@
|
||||
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 prefix = await ticketValidator.ValidateTicketAsync(token);
|
||||
|
||||
if (string.IsNullOrEmpty(prefix))
|
||||
{
|
||||
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 (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;
|
||||
}
|
||||
|
||||
StripQueryParameter(context, options.QueryParameterName);
|
||||
await next(context);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<UserSecretsId>media-gateway-2f1c9b6a-7d3e-4c0a-9a21-0b8e5d4c3f10</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<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,5 @@
|
||||
{
|
||||
"StreamTicket": {
|
||||
"PublicKeyPath": "../../deploy/keys/stream_public.pem"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Yarp": "Information"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
|
||||
"StreamTicket": {
|
||||
"PublicKeyPath": "",
|
||||
"Audience": "media-gateway",
|
||||
"Issuer": "musify-webapi",
|
||||
"QueryParameterName": "t",
|
||||
"MediaPathPrefix": "/media"
|
||||
},
|
||||
|
||||
"Cors": {
|
||||
"AllowedOrigins": []
|
||||
},
|
||||
|
||||
"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/" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user