// SPDX-FileCopyrightText: 2026 Progmasoft // SPDX-License-Identifier: AGPL-3.0-or-later using System.Text; using Microsoft.Extensions.Options; namespace Progmasoft.Progmaweb.Api.Git; /// A repository in a listing. /// Its name. /// What it is. /// Where it is developed, on GitHub. /// Where it is cloned from. /// Its default branch. /// When its default branch last changed. internal sealed record GitRepositoryResponse( string Name, string Description, string Homepage, string CloneUrl, string? DefaultBranch, DateTimeOffset? UpdatedAt); /// A section of the listing. /// Its heading. /// Its repositories. internal sealed record GitSectionResponse(string Name, IReadOnlyList Repositories); /// What is at a path of a commit. /// The branch, tag or commit the request named. /// The commit it resolved to. /// The path; empty for the root. /// tree or blob. /// The entries of a tree; null for a blob. /// The size of a blob; null for a tree. /// Whether the blob is not text; a binary blob carries no text. /// The text of a blob up to . /// Whether the text was cut. internal sealed record GitTreeResponse( string Reference, string Commit, string Path, string Kind, IReadOnlyList? Entries, long? Size, bool IsBinary, string? Text, bool IsTruncated); /// The read-only mirrors of git.progmasoft.com, for the pages of the Progmasoft site. /// /// The pages are rendered by Next.js on the same host, which calls these endpoints on loopback. Two of them reach the /// browser through Nginx: the raw files and the archives. Clones are served by git-http-backend, not here. /// internal static class GitEndpoints { /// The prefix of every endpoint. public const string Prefix = "/api/v1/git"; /// Maps the endpoints. /// The application. public static void MapGitEndpoints(this WebApplication app) { RouteGroupBuilder api = app.MapGroup(Prefix + "/repositories").RequireRateLimiting("git"); api.MapGet("/", ListAsync); api.MapGet("/{name}", ShowAsync); api.MapGet("/{name}/refs", RefsAsync); api.MapGet("/{name}/tree", TreeAsync); api.MapGet("/{name}/log", LogAsync); api.MapGet("/{name}/commits/{commit}", CommitAsync); api.MapGet("/{name}/raw", RawAsync); api.MapGet("/{name}/archive", ArchiveAsync); } /// Where a repository is developed. /// Its name. /// Its address on GitHub. private static string Homepage(string name) => $"https://github.com/Progmasoft/{name}"; /// Where a repository is cloned from. /// The host of the mirrors. /// Its name. /// Its address on git.progmasoft.com. private static string CloneUrl(IOptions options, string name) => $"https://{options.Value.Host}/{name}"; /// The sections of the catalog with their mirrored repositories. /// The catalog. /// The reader. /// The host of the mirrors. /// Cancels the request. /// The sections. private static async Task ListAsync( GitCatalog catalog, GitReader git, IOptions options, CancellationToken cancellationToken) { List sections = []; foreach (GitCatalogSection section in catalog.Sections()) { List repositories = []; foreach (GitCatalogRepository repository in section.Repositories) { if (catalog.Find(repository.Name) is not { } found) { continue; } repositories.Add(await DescribeAsync(git, options, found.Repository, found.MirrorPath, cancellationToken)); } if (repositories.Count > 0) { sections.Add(new GitSectionResponse(section.Name, repositories)); } } return Results.Ok(sections); } /// Describes a repository: its addresses, default branch and when that last changed. /// The reader. /// The host of the mirrors. /// The repository. /// The path of its mirror. /// Cancels the request. /// The description. private static async Task DescribeAsync( GitReader git, IOptions options, GitCatalogRepository repository, string mirror, CancellationToken cancellationToken) { string? branch = await git.DefaultBranchAsync(mirror, cancellationToken); DateTimeOffset? updated = null; if (branch is not null && await git.ResolveAsync(mirror, branch, cancellationToken) is { } head) { (IReadOnlyList commits, _) = await git.LogAsync(mirror, head, "", 0, cancellationToken); updated = commits.Count > 0 ? commits[0].Date : null; } return new GitRepositoryResponse( repository.Name, repository.Description, Homepage(repository.Name), CloneUrl(options, repository.Name), branch, updated); } /// One repository. /// Its name. /// The catalog. /// The reader. /// The host of the mirrors. /// Cancels the request. /// The repository, or 404. private static async Task ShowAsync( string name, GitCatalog catalog, GitReader git, IOptions options, CancellationToken cancellationToken) => catalog.Find(name) is { } found ? Results.Ok(await DescribeAsync(git, options, found.Repository, found.MirrorPath, cancellationToken)) : Results.NotFound(); /// The branches and the tags of a repository. /// Its name. /// The catalog. /// The reader. /// Cancels the request. /// The branches and tags, or 404. private static async Task RefsAsync( string name, GitCatalog catalog, GitReader git, CancellationToken cancellationToken) { if (catalog.Find(name) is not { } found) { return Results.NotFound(); } (IReadOnlyList branches, IReadOnlyList tags) = await git.RefsAsync(found.MirrorPath, cancellationToken); return Results.Ok(new { branches, tags }); } /// Finds the mirror, the commit a reference names (the default branch without one) and checks a path. private static async Task<(string Mirror, string Reference, string Commit, string Path)?> LocateAsync( string name, string? reference, string? path, GitCatalog catalog, GitReader git, CancellationToken cancellationToken) { string trimmed = (path ?? "").Trim('/'); if (catalog.Find(name) is not { } found || !GitReader.IsTreePath(trimmed)) { return null; } string? named = string.IsNullOrEmpty(reference) ? await git.DefaultBranchAsync(found.MirrorPath, cancellationToken) : reference; if (named is null || await git.ResolveAsync(found.MirrorPath, named, cancellationToken) is not { } commit) { return null; } return (found.MirrorPath, named, commit, trimmed); } /// A directory or a file of a branch, tag or commit. /// The repository. /// The branch, tag or commit; the default branch without one. /// The path; the root without one. /// The catalog. /// The reader. /// Cancels the request. /// What is there, or 404. private static async Task TreeAsync( string name, string? @ref, string? path, GitCatalog catalog, GitReader git, CancellationToken cancellationToken) { if (await LocateAsync(name, @ref, path, catalog, git, cancellationToken) is not { } at) { return Results.NotFound(); } string? kind = await git.KindAsync(at.Mirror, at.Commit, at.Path, cancellationToken); if (kind == "tree") { IReadOnlyList entries = await git.TreeAsync(at.Mirror, at.Commit, at.Path, cancellationToken); return Results.Ok(new GitTreeResponse(at.Reference, at.Commit, at.Path, "tree", entries, null, false, null, false)); } if (kind != "blob") { return Results.NotFound(); } long size = await git.SizeAsync(at.Mirror, at.Commit, at.Path, cancellationToken); (byte[] bytes, bool isTruncated) = await git.BlobAsync(at.Mirror, at.Commit, at.Path, GitReader.MaxTextBytes, cancellationToken); bool isBinary = IsBinary(bytes); return Results.Ok(new GitTreeResponse( at.Reference, at.Commit, at.Path, "blob", null, size, isBinary, isBinary ? null : Encoding.UTF8.GetString(bytes), isTruncated)); } /// Whether bytes are not text: a NUL in the first 8000, as Git decides. internal static bool IsBinary(ReadOnlySpan bytes) => bytes[..Math.Min(bytes.Length, 8000)].Contains((byte)0); /// A page of the commits of a branch, tag or commit, of a path in it when one is given. /// The repository. /// The branch, tag or commit; the default branch without one. /// The path; the whole tree without one. /// The page, from zero. /// The catalog. /// The reader. /// Cancels the request. /// The commits, or 404. private static async Task LogAsync( string name, string? @ref, string? path, int? page, GitCatalog catalog, GitReader git, CancellationToken cancellationToken) { if (page is < 0 or > 10_000 || await LocateAsync(name, @ref, path, catalog, git, cancellationToken) is not { } at) { return Results.NotFound(); } (IReadOnlyList commits, bool hasMore) = await git.LogAsync(at.Mirror, at.Commit, at.Path, page ?? 0, cancellationToken); return Results.Ok(new { reference = at.Reference, commit = at.Commit, path = at.Path, page = page ?? 0, commits, hasMore }); } /// A commit with its message and patch. /// The repository. /// The full commit identifier. /// The catalog. /// The reader. /// Cancels the request. /// The commit, or 404. private static async Task CommitAsync( string name, string commit, GitCatalog catalog, GitReader git, CancellationToken cancellationToken) { if (!GitReader.IsCommitId(commit) || catalog.Find(name) is not { } found || await git.ResolveAsync(found.MirrorPath, commit, cancellationToken) is not { } resolved) { return Results.NotFound(); } return Results.Ok(await git.CommitAsync(found.MirrorPath, resolved, cancellationToken)); } /// A file as it is: plain text, or a download when it is binary. /// The repository. /// The branch, tag or commit; the default branch without one. /// The path of the file. /// The request, for the Content-Disposition header. /// The catalog. /// The reader. /// Cancels the request. /// The file, 404, or 413 past . private static async Task RawAsync( string name, string? @ref, string? path, HttpContext context, GitCatalog catalog, GitReader git, CancellationToken cancellationToken) { if (await LocateAsync(name, @ref, path, catalog, git, cancellationToken) is not { } at || at.Path.Length == 0 || await git.KindAsync(at.Mirror, at.Commit, at.Path, cancellationToken) != "blob") { return Results.NotFound(); } long size = await git.SizeAsync(at.Mirror, at.Commit, at.Path, cancellationToken); if (size > GitReader.MaxRawBytes) { return Results.StatusCode(StatusCodes.Status413PayloadTooLarge); } (byte[] bytes, _) = await git.BlobAsync(at.Mirror, at.Commit, at.Path, GitReader.MaxRawBytes, cancellationToken); // Raw files are never rendered by the browser: text is plain text, anything else is a download, and the // content security policy of the API allows nothing to run. context.Response.Headers.ContentDisposition = IsBinary(bytes) ? $"attachment; filename=\"{SafeFileName(at.Path)}\"" : "inline"; return Results.Bytes(bytes, IsBinary(bytes) ? "application/octet-stream" : "text/plain; charset=utf-8"); } /// Writes a .tar.gz of a branch, tag or commit. /// The repository. /// The branch, tag or commit; the default branch without one. /// The request, which the archive is written to. /// The catalog. /// The reader. /// Cancels the request. /// A task that completes when the archive is written. private static async Task ArchiveAsync( string name, string? @ref, HttpContext context, GitCatalog catalog, GitReader git, CancellationToken cancellationToken) { if (await LocateAsync(name, @ref, "", catalog, git, cancellationToken) is not { } at) { context.Response.StatusCode = StatusCodes.Status404NotFound; return; } string label = SafeFileName(at.Reference.Replace('/', '-')); string prefix = $"{name}-{label}"; context.Response.ContentType = "application/gzip"; context.Response.Headers.ContentDisposition = $"attachment; filename=\"{prefix}.tar.gz\""; await git.ArchiveAsync(at.Mirror, at.Commit, prefix + "/", context.Response.Body, cancellationToken); } /// The last segment of a path with only safe characters, for a Content-Disposition file name. internal static string SafeFileName(string path) { string last = path[(path.LastIndexOf('/') + 1)..]; string safe = new([.. last.Select(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' or '_' or '+' ? c : '_')]); return safe.Length == 0 ? "file" : safe; } } /// Keeps the Git endpoints on git.progmasoft.com and loopback, and everything else off that host. /// The rest of the pipeline. /// The host of the mirrors. internal sealed class GitHostFilter(RequestDelegate next, IOptions options) { /// Answers 404 for a Git path on another host, or another path on the Git host. /// The request. /// A task that completes when the request has been answered. public Task InvokeAsync(HttpContext context) { PathString path = context.Request.Path; string host = context.Request.Host.Host; bool isGitPath = path.StartsWithSegments(GitEndpoints.Prefix, StringComparison.OrdinalIgnoreCase); bool isHealth = path.StartsWithSegments("/health", StringComparison.OrdinalIgnoreCase); bool isGitHost = string.Equals(host, options.Value.Host, StringComparison.OrdinalIgnoreCase); bool isLoopback = host is "127.0.0.1" or "localhost" or "::1" or "[::1]"; bool allowed = isGitHost ? isGitPath || isHealth : !isGitPath || isLoopback; if (allowed) { return next(context); } context.Response.StatusCode = StatusCodes.Status404NotFound; return Task.CompletedTask; } }