< Summary

Information
Class: Anichron.API.Endpoints.ProxyEndpoints
Assembly: Anichron.API
File(s): /home/runner/work/anichron/anichron/src/Anichron.API/Endpoints/ProxyEndpoints.cs
Tag: 19_45211875487
Line coverage
97%
Covered lines: 48
Uncovered lines: 1
Coverable lines: 49
Total lines: 92
Line coverage: 97.9%
Branch coverage
90%
Covered branches: 9
Total branches: 10
Branch coverage: 90%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
AddProxyEndpoints(...)100%11100%
MapProxyEndpoints(...)100%11100%
BearerOrMediaCookie()100%11100%
ProducesProxy(...)100%11100%
GetProxyAsync()90%101094.11%

File(s)

/home/runner/work/anichron/anichron/src/Anichron.API/Endpoints/ProxyEndpoints.cs

#LineLine coverage
 1using Anichron.API.Infrastructure;
 2using Anichron.Core.Data.Repository;
 3using Anichron.Infrastructure.Storage;
 4using Microsoft.AspNetCore.Authentication.JwtBearer;
 5using Microsoft.AspNetCore.Authorization;
 6using Microsoft.AspNetCore.Mvc;
 7using Microsoft.Net.Http.Headers;
 8using System.Security.Claims;
 9
 10namespace Anichron.API.Endpoints;
 11
 12/// <summary>The proxy route, the one route that accepts the media cookie as well as the bearer header (ADR 0013).</summ
 13public static class ProxyEndpoints
 14{
 15    internal const string MediaCookieName = "media_token";
 16    internal const string MediaCookiePath = $"{ApiPaths.Base}/{ApiPaths.Proxies.Group}";
 17
 18    private const string mediaCookieScheme = "MediaCookie";
 19    private const string currentProxyCacheControl = "private, max-age=31536000, immutable";
 20    private const string staleProxyCacheControl = "private, no-cache";
 21
 22    public static IServiceCollection AddProxyEndpoints(this IServiceCollection services)
 3123    {
 3124        services.AddAuthentication().AddJwtBearer(mediaCookieScheme, options => options.Events = new JwtBearerEvents
 3125        {
 3126            OnMessageReceived = context =>
 3127            {
 3128                context.Token = context.Request.Cookies[MediaCookieName];
 3129                if (context.Token is null)
 3130                    context.NoResult();
 3131                return Task.CompletedTask;
 3132            },
 3133        });
 3134        return services.AddJwtValidation(mediaCookieScheme);
 3135    }
 36
 37    public static IEndpointRouteBuilder MapProxyEndpoints(this IEndpointRouteBuilder app)
 6638    {
 6639        var proxies = app.MapGroup(ApiPaths.Proxies.Group).WithTags("Media").RequireUser(BearerOrMediaCookie());
 6640        proxies.MapGet(ApiPaths.Proxies.Proxy, GetProxyAsync)
 6641               .ProducesProxy(StatusCodes.Status200OK)
 6642               .ProducesProxy(StatusCodes.Status206PartialContent)
 6643               .Produces(StatusCodes.Status304NotModified)
 6644               .Produces(StatusCodes.Status404NotFound)
 6645               .Produces(StatusCodes.Status412PreconditionFailed)
 6646               .ProducesWithoutBody(StatusCodes.Status416RangeNotSatisfiable);
 6647        return app;
 6648    }
 49
 50    private static AuthorizationPolicy BearerOrMediaCookie()
 6651        => new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme, mediaCookieScheme)
 6652            .RequireAuthenticatedUser()
 6653            .AddRequirements(new MustChangePasswordRequirement())
 6654            .Build();
 55
 56    private static RouteHandlerBuilder ProducesProxy(this RouteHandlerBuilder builder, int statusCode)
 13257    {
 13258        var contentTypes = ProxyKinds.All.Select(kind => kind.ContentType).Distinct().ToArray();
 13259        return builder.Produces<Stream>(statusCode, contentTypes[0], contentTypes[1..]);
 13260    }
 61
 62    internal static async Task<IResult> GetProxyAsync(
 63        Guid assetId,
 64        string type,
 65        [FromQuery(Name = "v")] string? version,
 66        ClaimsPrincipal user,
 67        [FromServices] IMediaAssetReadRepository assets,
 68        [FromServices] IProxyStore proxies,
 69        HttpContext context,
 70        CancellationToken ct)
 2171    {
 2172        if (!Guid.TryParse(user.FindFirstValue(ClaimTypes.NameIdentifier), out var userId))
 073            return Results.Unauthorized();
 74
 2175        if (ProxyKinds.FromSlug(type) is not { } kind)
 376            return Results.NotFound();
 77
 1878        var proxy = await assets.FindVisibleProxyAsync(assetId, userId, kind.Type, ct);
 1879        if (proxy is null)
 180            return Results.NotFound();
 81
 1782        if (proxies.OpenRead(proxy.ProxyPath) is not { } stream)
 183            return Results.NotFound();
 84
 1685        context.Response.Headers.CacheControl = version == proxy.ContentHash ? currentProxyCacheControl : staleProxyCach
 1686        return Results.Stream(
 1687            stream,
 1688            kind.ContentType,
 1689            entityTag: new EntityTagHeaderValue($"\"{proxy.ContentHash}-{kind.Type}\""),
 1690            enableRangeProcessing: true);
 2191    }
 92}