Forge

Jessie / forge public

Self-hosted git - made by qwen 3.8 27b

commit: 0c9688e9

Branches

main
SmartHttpTests.cs 11.2 kB · 218 lines RawHistory
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using Forge.Data;
using Forge.Tests.Support;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Forge.Tests;

/// <summary>Real `git clone` and `git push` against the running app.</summary>
public class SmartHttpTests(ForgeHost host) : IClassFixture<ForgeHost>
{
    [Theory]
    [InlineData("0")]
    [InlineData("2")]
    public async Task Push_then_clone_round_trips(string protocolVersion)
    {
        var user = await host.CreateUserAsync();
        var name = "roundtrip-v" + protocolVersion;
        var repo = await host.CreateRepoAsync(user, name, Visibility.Public);
        var token = await host.CreateTokenAsync(user, canWrite: true);
        var protocol = "protocol.version=" + protocolVersion;

        var work = host.NewDir("work");
        var sha = await host.Git.CreateWorkRepoAsync(work);
        await host.Git.MustAsync(work, "-c", protocol, "push", host.GitUrl(user.Username, name, token), "main");

        // Tags go up with --tags.
        await host.Git.MustAsync(work, "tag", "-a", "v1", "-m", "one");
        await host.Git.MustAsync(work, "-c", protocol, "push", "--tags", host.GitUrl(user.Username, name, token));

        // A public repository clones without credentials.
        var clone = host.NewDir("clone");
        await host.Git.MustAsync(clone, "-c", protocol, "clone", host.GitUrl(user.Username, name), ".");
        Assert.Equal(sha, await host.Git.MustAsync(clone, "rev-parse", "HEAD"));
        Assert.Equal("# Demo\n", await File.ReadAllTextAsync(Path.Combine(clone, "README.md")));
        Assert.Equal("v1", await host.Git.MustAsync(clone, "tag", "--list"));

        // A second push is a fast-forward and is recorded as an update.
        await File.WriteAllTextAsync(Path.Combine(work, "second.txt"), "more\n");
        await host.Git.MustAsync(work, "add", "-A");
        await host.Git.MustAsync(work, "commit", "-m", "Second");
        var secondSha = await host.Git.MustAsync(work, "rev-parse", "HEAD");
        await host.Git.MustAsync(work, "-c", protocol, "push", host.GitUrl(user.Username, name, token), "main");
        await host.Git.MustAsync(clone, "-c", protocol, "pull", "--ff-only");
        Assert.Equal(secondSha, await host.Git.MustAsync(clone, "rev-parse", "HEAD"));

        var events = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().PushEvents
            .Where(e => e.RepoId == repo.Id).OrderBy(e => e.Id).ToListAsync());
        Assert.Collection(
            events,
            e => Assert.Equal(("refs/heads/main", Git.GitParsers.ZeroSha, sha), (e.RefName, e.OldSha, e.NewSha)),
            e => Assert.Equal(("refs/tags/v1", Git.GitParsers.ZeroSha), (e.RefName, e.OldSha)),
            e => Assert.Equal(("refs/heads/main", sha, secondSha), (e.RefName, e.OldSha, e.NewSha)));

        var reloaded = await host.ReloadRepoAsync(repo.Id);
        Assert.NotNull(reloaded.PushedAt);
        Assert.Equal("main", reloaded.DefaultBranch);
    }

    [Fact]
    public async Task First_push_of_another_branch_becomes_the_default_branch()
    {
        var user = await host.CreateUserAsync();
        var repo = await host.CreateRepoAsync(user, "master-first", Visibility.Public);
        var token = await host.CreateTokenAsync(user, canWrite: true);

        var work = host.NewDir("work");
        var sha = await host.Git.CreateWorkRepoAsync(work, branch: "master");
        await host.Git.MustAsync(work, "push", host.GitUrl(user.Username, repo.Name, token), "master");

        Assert.Equal("master", (await host.ReloadRepoAsync(repo.Id)).DefaultBranch);

        // HEAD moved too, so a clone checks out the pushed branch.
        var clone = host.NewDir("clone");
        await host.Git.MustAsync(clone, "clone", host.GitUrl(user.Username, repo.Name), ".");
        Assert.Equal(sha, await host.Git.MustAsync(clone, "rev-parse", "HEAD"));
    }

    [Fact]
    public async Task Private_repository_needs_a_token_to_clone()
    {
        var user = await host.CreateUserAsync();
        var (repo, sha, _) = await host.CreatePushedRepoAsync(user, "private-clone", Visibility.Private);
        var readToken = await host.CreateTokenAsync(user, canWrite: false);

        var anonymous = await host.Git.RunAsync(host.NewDir("anon"), "clone", host.GitUrl(user.Username, repo.Name), ".");
        Assert.False(anonymous.Ok);

        var clone = host.NewDir("clone");
        await host.Git.MustAsync(clone, "clone", host.GitUrl(user.Username, repo.Name, readToken), ".");
        Assert.Equal(sha, await host.Git.MustAsync(clone, "rev-parse", "HEAD"));

        var used = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().AccessTokens
            .Where(t => !t.CanWrite && t.UserId == user.Id).Select(t => t.LastUsedAt).ToListAsync());
        Assert.Contains(used, u => u is not null);
    }

    [Fact]
    public async Task Push_is_rejected_without_a_write_token()
    {
        var user = await host.CreateUserAsync();
        var (repo, sha, work) = await host.CreatePushedRepoAsync(user, "push-rights", Visibility.Public);
        var readToken = await host.CreateTokenAsync(user, canWrite: false);
        var expired = await host.CreateTokenAsync(user, canWrite: true, DateTime.UtcNow.AddMinutes(-1));

        await File.WriteAllTextAsync(Path.Combine(work, "new.txt"), "x\n");
        await host.Git.MustAsync(work, "add", "-A");
        await host.Git.MustAsync(work, "commit", "-m", "Not allowed");

        Assert.False((await host.Git.RunAsync(work, "push", host.GitUrl(user.Username, repo.Name), "main")).Ok);
        Assert.False((await host.Git.RunAsync(work, "push", host.GitUrl(user.Username, repo.Name, readToken), "main")).Ok);
        Assert.False((await host.Git.RunAsync(work, "push", host.GitUrl(user.Username, repo.Name, expired), "main")).Ok);
        Assert.False((await host.Git.RunAsync(work, "push", host.GitUrl(user.Username, repo.Name, "forge_wrong"), "main")).Ok);

        // Nothing moved on the server.
        var check = host.NewDir("check");
        await host.Git.MustAsync(check, "clone", host.GitUrl(user.Username, repo.Name), ".");
        Assert.Equal(sha, await host.Git.MustAsync(check, "rev-parse", "HEAD"));
    }

    [Fact]
    public async Task Status_codes_do_not_reveal_private_repositories()
    {
        var user = await host.CreateUserAsync();
        var other = await host.CreateUserAsync("other");
        await host.CreatePushedRepoAsync(user, "hidden", Visibility.Private);
        var readToken = await host.CreateTokenAsync(user, canWrite: false);
        var otherToken = await host.CreateTokenAsync(other, canWrite: true);
        var expired = await host.CreateTokenAsync(user, canWrite: true, DateTime.UtcNow.AddMinutes(-1));
        using var client = host.CreateClient();

        const string upload = "/jessie/hidden.git/info/refs?service=git-upload-pack";
        const string receive = "/jessie/hidden.git/info/refs?service=git-receive-pack";
        const string missing = "/jessie/does-not-exist.git/info/refs?service=git-upload-pack";

        // Anonymous: a private repository and a missing one answer identically, and git is asked for credentials.
        var hidden = await client.GetAsync(upload);
        var absent = await client.GetAsync(missing);
        Assert.Equal(HttpStatusCode.Unauthorized, hidden.StatusCode);
        Assert.Equal(HttpStatusCode.Unauthorized, absent.StatusCode);
        Assert.StartsWith("Basic realm=\"forge\"", hidden.Headers.WwwAuthenticate.ToString());
        Assert.Equal(await hidden.Content.ReadAsStringAsync(), await absent.Content.ReadAsStringAsync());

        // Another user's valid token: the repository does not exist for them.
        Assert.Equal(HttpStatusCode.NotFound, (await GetAsync(client, upload, otherToken)).StatusCode);
        Assert.Equal(HttpStatusCode.NotFound, (await GetAsync(client, receive, otherToken)).StatusCode);

        // The owner's read token reads but may not push; an expired token is no token.
        Assert.Equal(HttpStatusCode.OK, (await GetAsync(client, upload, readToken)).StatusCode);
        Assert.Equal(HttpStatusCode.Forbidden, (await GetAsync(client, receive, readToken)).StatusCode);
        Assert.Equal(HttpStatusCode.Unauthorized, (await GetAsync(client, upload, expired)).StatusCode);
    }

    [Fact]
    public async Task Info_refs_validates_the_service_and_sets_headers()
    {
        var user = await host.CreateUserAsync();
        await host.CreatePushedRepoAsync(user, "headers", Visibility.Public);
        using var client = host.CreateClient();

        var bad = await client.GetAsync("/jessie/headers.git/info/refs?service=git-upload-archive");
        Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode);
        Assert.Equal(HttpStatusCode.BadRequest, (await client.GetAsync("/jessie/headers.git/info/refs")).StatusCode);

        var v0 = await client.GetAsync("/jessie/headers.git/info/refs?service=git-upload-pack");
        Assert.Equal(HttpStatusCode.OK, v0.StatusCode);
        Assert.Equal("application/x-git-upload-pack-advertisement", v0.Content.Headers.ContentType?.MediaType);
        Assert.Equal("no-cache", v0.Headers.CacheControl?.ToString());
        Assert.StartsWith("001e# service=git-upload-pack\n0000", await v0.Content.ReadAsStringAsync());

        // Protocol v2: the header reaches git as GIT_PROTOCOL and the answer is a v2 capability advertisement.
        using var request = new HttpRequestMessage(HttpMethod.Get, "/jessie/headers.git/info/refs?service=git-upload-pack");
        request.Headers.Add("Git-Protocol", "version=2");
        var v2 = await (await client.SendAsync(request)).Content.ReadAsStringAsync();
        Assert.StartsWith("000eversion 2\n", v2);
    }

    [Fact]
    public async Task Oversized_push_is_rejected()
    {
        var small = new ForgeHost();
        small.ExtraArgs.Add("--Forge:MaxPushSizeMb=1");
        await small.InitializeAsync();
        try
        {
            var user = await small.CreateUserAsync();
            var repo = await small.CreateRepoAsync(user, "small", Visibility.Public);
            var token = await small.CreateTokenAsync(user, canWrite: true);

            var work = small.NewDir("work");
            await small.Git.CreateWorkRepoAsync(work);
            // Random bytes do not compress, so the pack is larger than the 1 MB limit.
            await File.WriteAllBytesAsync(Path.Combine(work, "big.bin"), System.Security.Cryptography.RandomNumberGenerator.GetBytes(3 * 1024 * 1024));
            await small.Git.MustAsync(work, "add", "-A");
            await small.Git.MustAsync(work, "commit", "-m", "Too big");

            var push = await small.Git.RunAsync(work, "push", small.GitUrl(user.Username, repo.Name, token), "main");
            Assert.False(push.Ok);

            var refs = await small.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().PushEvents.CountAsync());
            Assert.Equal(0, refs);
        }
        finally
        {
            await small.DisposeAsync();
        }
    }

    private static Task<HttpResponseMessage> GetAsync(HttpClient client, string url, string token)
    {
        var request = new HttpRequestMessage(HttpMethod.Get, url);
        request.Headers.Authorization = new AuthenticationHeaderValue(
            "Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("git:" + token)));
        return client.SendAsync(request);
    }
}

Keyboard shortcuts

/
Search repositories
s
Search file names and code
y
Open the permalink of the file being viewed
?
Show this help