Forge

Jessie / forge public

Self-hosted git - made by qwen 3.8 27b

branch: main

Branches

main
WebTests.cs 33 kB · 650 lines RawPermalinkHistory
using System.Net;
using Forge.Data;
using Forge.Features.Repos;
using Forge.Tests.Support;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Forge.Tests;

/// <summary>Pages, permissions and the raw endpoint, over HTTP against the running app.</summary>
public class WebTests(ForgeHost host) : IClassFixture<ForgeHost>
{
    private static string[] RepoPages(string repo, string sha) =>
    [
        $"/jessie/{repo}",
        $"/jessie/{repo}/tree/main",
        $"/jessie/{repo}/blob/main/README.md",
        $"/jessie/{repo}/raw/main/README.md",
        $"/jessie/{repo}/commits/main",
        $"/jessie/{repo}/commits",
        $"/jessie/{repo}/commit/{sha}",
        $"/jessie/{repo}/branches",
        $"/jessie/{repo}/tags",
        $"/jessie/{repo}/atom",
        $"/jessie/{repo}/search?q=Demo",
        $"/jessie/{repo}/activity",
    ];

    private static string[] AdminPages(string repo) =>
    [
        $"/jessie/{repo}/settings",
        $"/jessie/{repo}/settings/webhooks",
    ];

    [Fact]
    public async Task Anonymous_visitor_gets_404_for_everything_in_a_private_repository()
    {
        var user = await host.CreateUserAsync();
        var (_, sha, _) = await host.CreatePushedRepoAsync(user, "secret", Visibility.Private);
        using var anonymous = host.CreateClient();

        foreach (var url in RepoPages("secret", sha).Concat(AdminPages("secret")))
        {
            var response = await anonymous.GetAsync(url);
            Assert.True(response.StatusCode == HttpStatusCode.NotFound, $"{url} answered {(int)response.StatusCode}, expected 404");
        }

        // The home page does not list it either.
        Assert.DoesNotContain("secret", await anonymous.GetStringAsync("/"));

        // The owner sees all of it.
        using var owner = await host.CreateSignedInClientAsync();
        foreach (var url in RepoPages("secret", sha).Concat(AdminPages("secret")))
        {
            var response = await owner.GetAsync(url);
            Assert.True(response.StatusCode == HttpStatusCode.OK, $"{url} answered {(int)response.StatusCode} for the owner, expected 200");
        }

        Assert.Contains("secret", await owner.GetStringAsync("/"));
    }

    [Fact]
    public async Task Public_repository_is_readable_but_its_settings_are_hidden()
    {
        var user = await host.CreateUserAsync();
        var (_, sha, _) = await host.CreatePushedRepoAsync(user, "open", Visibility.Public);
        using var anonymous = host.CreateClient();

        foreach (var url in RepoPages("open", sha))
        {
            var response = await anonymous.GetAsync(url);
            Assert.True(response.StatusCode == HttpStatusCode.OK, $"{url} answered {(int)response.StatusCode}, expected 200");
        }

        foreach (var url in AdminPages("open"))
        {
            Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync(url)).StatusCode);
        }

        Assert.Contains("open", await anonymous.GetStringAsync("/"));
    }

    [Fact]
    public async Task Home_page_searches_and_sorts_repositories()
    {
        var user = await host.CreateUserAsync();
        await host.WithScopeAsync(async sp =>
        {
            var repos = sp.GetRequiredService<RepoService>();
            await repos.CreateAsync(user.Id, "zebra-tools", "Stripes for everyone", Visibility.Public);
            await repos.CreateAsync(user.Id, "aardvark", "100% ants", Visibility.Public);
            return 0;
        });
        using var client = host.CreateClient();

        var byName = await client.GetStringAsync("/?q=ZEBRA");
        Assert.Contains("zebra-tools", byName);
        Assert.DoesNotContain("aardvark", byName);

        // The description is searched too, and LIKE wildcards in the text are literal.
        var byDescription = await client.GetStringAsync("/?q=100%25");
        Assert.Contains("aardvark", byDescription);
        Assert.DoesNotContain("zebra-tools", byDescription);
        Assert.DoesNotContain("zebra-tools", await client.GetStringAsync("/?q=_ebra"));

        var nothing = await ForgeHost.TextAsync(await client.GetAsync("/?q=no-such-thing"));
        Assert.Contains("No repository matches “no-such-thing”.", nothing);

        var sorted = await client.GetStringAsync("/jessie?sort=name");
        Assert.True(sorted.IndexOf("aardvark", StringComparison.Ordinal) < sorted.IndexOf("zebra-tools", StringComparison.Ordinal));
    }

    [Fact]
    public async Task Pages_show_repository_content()
    {
        var user = await host.CreateUserAsync();
        var repo = await host.CreateRepoAsync(user, "content", Visibility.Public);
        var token = await host.CreateTokenAsync(user, canWrite: true);
        using var client = host.CreateClient();

        // Before the first push the page explains how to push.
        var empty = await client.GetStringAsync("/jessie/content");
        Assert.Contains("The repository is empty", empty);
        Assert.Contains("git clone http://forge.test/jessie/content.git", empty);

        var work = host.NewDir("work");
        await host.Git.CreateWorkRepoAsync(work, content: "# Hello\n\nSee [the code](src/app.cs) and ![logo](logo.png).\n");
        Directory.CreateDirectory(Path.Combine(work, "src"));
        await File.WriteAllTextAsync(Path.Combine(work, "src", "app.cs"), "class App\n{\n}\n");
        await host.Git.MustAsync(work, "add", "-A");
        await host.Git.MustAsync(work, "commit", "-m", "Add the app");
        var sha = await host.Git.MustAsync(work, "rev-parse", "HEAD");
        await host.Git.MustAsync(work, "checkout", "-b", "feature/x");
        await host.Git.MustAsync(work, "tag", "v1");
        await host.Git.MustAsync(work, "push", host.GitUrl("jessie", "content", token), "main", "feature/x", "v1");

        var home = await client.GetStringAsync("/jessie/content");
        Assert.Contains("README.md", home);
        Assert.Contains(">src</a>", home);
        Assert.Contains("<h1>Hello</h1>", home);
        Assert.Contains("href=\"/jessie/content/blob/main/src/app.cs\"", home);
        Assert.Contains("src=\"/jessie/content/raw/main/logo.png\"", home);
        Assert.Contains("Add the app", home);

        // Every entry shows the commit that last changed it; the side panel summarises the repository.
        Assert.Contains("First commit</a>", home);
        Assert.Contains("2 commits", home);
        Assert.Contains("2 branches", home);
        Assert.Contains("1 tag<", home);
        Assert.Contains("class=\"lang-csharp\"", home);
        Assert.Contains("100.0 %", home);

        // A branch name with a slash resolves, and the rest of the URL is the path.
        var tree = await client.GetStringAsync("/jessie/content/tree/feature/x/src");
        Assert.Contains("app.cs", tree);

        var blob = await client.GetStringAsync("/jessie/content/blob/main/src/app.cs");
        Assert.Contains("class App", blob);
        Assert.Contains("id=\"L3\"", blob);
        Assert.Contains("language-csharp", blob);
        Assert.Contains("/lib/highlight/highlight.min.js", blob);
        Assert.DoesNotContain("/lib/highlight/highlight.min.js", home);

        // A Markdown file is rendered; ?plain=1 shows its source with line numbers instead.
        var preview = await client.GetStringAsync("/jessie/content/blob/main/README.md");
        Assert.Contains("<h1>Hello</h1>", preview);
        Assert.DoesNotContain("id=\"L1\"", preview);
        var source = await client.GetStringAsync("/jessie/content/blob/main/README.md?plain=1");
        Assert.Contains("# Hello", source);
        Assert.Contains("id=\"L1\"", source);

        // The permalink names the commit, so it keeps pointing at this version.
        Assert.Contains($"href=\"/jessie/content/blob/{sha}/src/app.cs\"", blob);

        var commits = await client.GetStringAsync("/jessie/content/commits/main/src/app.cs");
        Assert.Contains("Add the app", commits);
        Assert.DoesNotContain("First commit", commits);
        Assert.Contains("Commits on ", commits);
        Assert.Contains($"data-copy=\"{sha}\"", commits);

        var commit = await client.GetStringAsync($"/jessie/content/commit/{sha}");
        Assert.Contains("src/app.cs", commit);
        Assert.Contains("class App", commit);

        // Both commits were made just now, so they fall into the current week of the chart.
        var activity = await client.GetStringAsync("/jessie/content/activity");
        Assert.Contains("Commits per week", activity);
        Assert.Contains("The last 52 weeks, 2 commits in total", activity);
        Assert.Single(System.Text.RegularExpressions.Regex.Matches(activity, "class=\"week-bar\""));
        Assert.Single(System.Text.RegularExpressions.Regex.Matches(activity, "class=\"contributor\""));

        Assert.Contains("feature/x", await client.GetStringAsync("/jessie/content/branches"));
        Assert.Contains("v1", await client.GetStringAsync("/jessie/content/tags"));

        var atom = await client.GetAsync("/jessie/content/atom");
        Assert.Equal("application/atom+xml", atom.Content.Headers.ContentType?.MediaType);
        var feed = await atom.Content.ReadAsStringAsync();
        Assert.Contains("<title>Add the app</title>", feed);
        Assert.Contains($"http://forge.test/jessie/content/commit/{sha}", feed);

        // Paths and refs that do not exist are plain 404s.
        Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/content/tree/nope")).StatusCode);
        Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/content/blob/main/nope.txt")).StatusCode);
        Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/content/commit/" + new string('0', 40))).StatusCode);
        Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/nope")).StatusCode);

        // A blob URL for a directory, and a tree URL for a file, redirect to the right view.
        var redirect = await client.GetAsync("/jessie/content/blob/main/src");
        Assert.Equal("/jessie/content/tree/main/src", redirect.Headers.Location?.PathAndQuery);
    }

    [Fact]
    public async Task Search_finds_file_names_and_code_and_treats_the_text_literally()
    {
        var user = await host.CreateUserAsync();
        var repo = await host.CreateRepoAsync(user, "searchable", Visibility.Public);
        var token = await host.CreateTokenAsync(user, canWrite: true);
        var work = host.NewDir("work");
        await host.Git.CreateWorkRepoAsync(work, content: "# Notes\n\nThe Anvil is heavy.\n");
        Directory.CreateDirectory(Path.Combine(work, "src"));
        await File.WriteAllTextAsync(Path.Combine(work, "src", "anvil.cs"), "class Hammer\n{\n    // strikes <b>the</b> anvil.*\n}\n");
        await File.WriteAllBytesAsync(Path.Combine(work, "anvil.bin"), [1, 0, (byte)'a', (byte)'n', (byte)'v', (byte)'i', (byte)'l']);
        await host.Git.MustAsync(work, "add", "-A");
        await host.Git.MustAsync(work, "commit", "-m", "Add files");
        await host.Git.MustAsync(work, "tag", "v1");
        await host.Git.MustAsync(work, "push", host.GitUrl("jessie", repo.Name, token), "main", "v1");
        using var client = host.CreateClient();
        var marker = Path.Combine(host.DataPath, "pwned-by-search");

        // Case does not matter; both the file names and the lines are found, binary content is not.
        var page = await client.GetStringAsync("/jessie/searchable/search?q=ANVIL");
        Assert.Contains("src/<mark>anvil</mark>.cs", page);
        Assert.Contains("<mark>anvil</mark>.bin", page);
        Assert.Contains("The <mark>Anvil</mark> is heavy.", page);
        Assert.Contains("href=\"/jessie/searchable/blob/main/src/anvil.cs#L3\"", page);
        // A match in a Markdown file links to its source view, where the line exists.
        Assert.Contains("href=\"/jessie/searchable/blob/main/README.md?plain=1#L3\"", page);

        // The text is literal (no regular expression) and is encoded on the way out.
        var literal = await client.GetStringAsync("/jessie/searchable/search?q=" + Uri.EscapeDataString("anvil.*"));
        Assert.Contains("<mark>anvil.*</mark>", literal);
        Assert.DoesNotContain("is heavy", literal);
        var html = await client.GetStringAsync("/jessie/searchable/search?q=" + Uri.EscapeDataString("<b>the</b>"));
        Assert.Contains("<mark>&lt;b&gt;the&lt;/b&gt;</mark>", html);
        Assert.DoesNotContain("<b>the</b>", html);

        // Text that looks like an option is still just text.
        foreach (var hostile in (string[])["--output=" + marker, "-O" + marker, "--open-files-in-pager=touch " + marker])
        {
            var response = await client.GetAsync("/jessie/searchable/search?q=" + Uri.EscapeDataString(hostile));
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }

        Assert.False(File.Exists(marker));

        // A tag can be searched; a ref that does not exist is a 404; nothing found says so.
        Assert.Contains("class <mark>Hammer</mark>", await client.GetStringAsync("/jessie/searchable/search?q=hammer&ref=v1"));
        Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/searchable/search?q=hammer&ref=--all")).StatusCode);
        var nothing = await ForgeHost.TextAsync(await client.GetAsync("/jessie/searchable/search?q=zzzz"));
        Assert.Contains("Nothing in main matches “zzzz”.", nothing);

        // One character is too short to search for.
        Assert.Contains("Search this repository", await client.GetStringAsync("/jessie/searchable/search?q=a"));
    }

    [Fact]
    public async Task Option_like_refs_are_not_found()
    {
        var user = await host.CreateUserAsync();
        await host.CreatePushedRepoAsync(user, "hostile", Visibility.Public);
        using var client = host.CreateClient();
        var marker = Path.Combine(host.DataPath, "pwned");

        string[] refs = ["--upload-pack=touch " + marker, "--output=" + marker, "-n", "--all"];
        foreach (var hostile in refs)
        {
            var encoded = Uri.EscapeDataString(hostile);
            foreach (var view in (string[])["tree", "blob", "raw", "commits"])
            {
                var response = await client.GetAsync($"/jessie/hostile/{view}/{encoded}/README.md");
                Assert.True(response.StatusCode == HttpStatusCode.NotFound, $"{view}/{hostile} answered {(int)response.StatusCode}");
            }

            Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync($"/jessie/hostile/commit/{encoded}")).StatusCode);
        }

        Assert.False(File.Exists(marker));
    }

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

        var work = host.NewDir("work");
        await host.Git.CreateWorkRepoAsync(work, fileName: "index.html", content: "<script>alert(1)</script>\n");
        await File.WriteAllTextAsync(Path.Combine(work, "icon.svg"), "<svg xmlns=\"http://www.w3.org/2000/svg\"><script>alert(1)</script></svg>\n");
        await File.WriteAllBytesAsync(Path.Combine(work, "pixel.png"), [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0]);
        await File.WriteAllBytesAsync(Path.Combine(work, "data.bin"), [1, 0, 2, 0, 3]);
        await File.WriteAllTextAsync(Path.Combine(work, "name with space.txt"), "spaced\n");
        await host.Git.MustAsync(work, "add", "-A");
        await host.Git.MustAsync(work, "commit", "-m", "Files");
        await host.Git.MustAsync(work, "push", host.GitUrl("jessie", repo.Name, token), "main");
        using var client = host.CreateClient();

        var html = await client.GetAsync("/jessie/raw/raw/main/index.html");
        Assert.Equal(HttpStatusCode.OK, html.StatusCode);
        Assert.Equal("text/plain; charset=utf-8", html.Content.Headers.ContentType?.ToString());
        Assert.Equal("nosniff", html.Headers.GetValues("X-Content-Type-Options").Single());
        Assert.Equal("<script>alert(1)</script>\n", await html.Content.ReadAsStringAsync());

        var svg = await client.GetAsync("/jessie/raw/raw/main/icon.svg");
        Assert.Equal("application/octet-stream", svg.Content.Headers.ContentType?.MediaType);
        Assert.Equal("attachment", svg.Content.Headers.ContentDisposition?.DispositionType);

        var png = await client.GetAsync("/jessie/raw/raw/main/pixel.png");
        Assert.Equal("image/png", png.Content.Headers.ContentType?.MediaType);
        Assert.Null(png.Content.Headers.ContentDisposition);
        Assert.Equal(12, (await png.Content.ReadAsByteArrayAsync()).Length);

        var bin = await client.GetAsync("/jessie/raw/raw/main/data.bin");
        Assert.Equal("application/octet-stream", bin.Content.Headers.ContentType?.MediaType);
        Assert.Equal("attachment", bin.Content.Headers.ContentDisposition?.DispositionType);
        Assert.Equal(new byte[] { 1, 0, 2, 0, 3 }, await bin.Content.ReadAsByteArrayAsync());

        var spaced = await client.GetAsync("/jessie/raw/raw/main/name%20with%20space.txt");
        Assert.Equal("spaced\n", await spaced.Content.ReadAsStringAsync());

        // ETag is the blob SHA; a matching If-None-Match gets 304 with no body.
        var etag = html.Headers.ETag;
        Assert.NotNull(etag);
        using var conditional = new HttpRequestMessage(HttpMethod.Get, "/jessie/raw/raw/main/index.html");
        conditional.Headers.IfNoneMatch.Add(etag);
        var notModified = await client.SendAsync(conditional);
        Assert.Equal(HttpStatusCode.NotModified, notModified.StatusCode);
        Assert.Empty(await notModified.Content.ReadAsByteArrayAsync());

        // The blob page shows the HTML file as escaped source, never as markup.
        var page = await client.GetStringAsync("/jessie/raw/blob/main/index.html");
        Assert.Contains("&lt;script&gt;alert(1)&lt;/script&gt;", page);
        Assert.DoesNotContain("<script>alert(1)</script>", page);
    }

    [Fact]
    public async Task Security_headers_are_on_every_page()
    {
        await host.CreateUserAsync();
        using var client = host.CreateClient();

        var response = await client.GetAsync("/login");

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.StartsWith("default-src 'self'", response.Headers.GetValues("Content-Security-Policy").Single());
        Assert.Equal("nosniff", response.Headers.GetValues("X-Content-Type-Options").Single());
        Assert.Equal("DENY", response.Headers.GetValues("X-Frame-Options").Single());
        // The CSP forbids inline script and style, so pages must not contain any.
        var html = await response.Content.ReadAsStringAsync();
        Assert.DoesNotContain("style=\"", html);
        Assert.DoesNotContain("<script>", html);
    }

    [Theory]
    [InlineData("/style.css", "text/css")]
    [InlineData("/app.js", "text/javascript")]
    [InlineData("/theme.js", "text/javascript")]
    [InlineData("/favicon.png", "image/png")]
    [InlineData("/lib/highlight/highlight.min.js", "text/javascript")]
    [InlineData("/lib/highlight/github.min.css", "text/css")]
    public async Task Static_assets_are_served_and_not_mistaken_for_pages(string url, string contentType)
    {
        await host.CreateUserAsync();
        using var client = host.CreateClient();

        var response = await client.GetAsync(url);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.Equal(contentType, response.Content.Headers.ContentType?.MediaType);
    }

    [Fact]
    public async Task Forms_require_an_antiforgery_token()
    {
        await host.CreateUserAsync();
        using var client = host.CreateClient();

        var response = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["_handler"] = "login",
            ["Username"] = "jessie",
            ["Password"] = ForgeHost.Password,
        }));

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
    }

    [Fact]
    public async Task Signed_in_owner_manages_repository_through_forms()
    {
        var user = await host.CreateUserAsync();
        using var client = await host.CreateSignedInClientAsync();

        // Pages that need a session send anonymous visitors to the login page.
        using var anonymous = host.CreateClient();
        var bounced = await anonymous.GetAsync("/new");
        Assert.Equal(HttpStatusCode.Redirect, bounced.StatusCode);
        Assert.StartsWith("/login", bounced.Headers.Location!.PathAndQuery);

        // Invalid names are refused with a message.
        var invalid = await ForgeHost.PostFormAsync(client, "/new", "new-repo", new() { ["Name"] = "bad..name", ["Visibility"] = "private" });
        Assert.Equal(HttpStatusCode.OK, invalid.StatusCode);
        Assert.Contains("alert error", await ForgeHost.TextAsync(invalid));

        var created = await ForgeHost.PostFormAsync(client, "/new", "new-repo", new()
        {
            ["Name"] = "managed",
            ["Description"] = "A managed repo",
            ["Visibility"] = "private",
        });
        Assert.Equal("/jessie/managed", created.Headers.Location?.PathAndQuery);

        var repo = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().Repositories.SingleAsync(r => r.Name == "managed"));
        var directory = host.RepoDirectory(repo.Id);
        Assert.True(File.Exists(Path.Combine(directory, "HEAD")));
        Assert.Equal(Visibility.Private, repo.Visibility);

        // A duplicate name is refused.
        var duplicate = await ForgeHost.PostFormAsync(client, "/new", "new-repo", new() { ["Name"] = "MANAGED", ["Visibility"] = "private" });
        Assert.Contains("already exists", await ForgeHost.TextAsync(duplicate));

        // Description and visibility.
        var saved = await ForgeHost.PostFormAsync(client, "/jessie/managed/settings", "general", new()
        {
            ["Description"] = "Now public",
            ["Visibility"] = "public",
        });
        Assert.Contains("Saved.", await ForgeHost.TextAsync(saved));
        Assert.Equal(Visibility.Public, (await host.ReloadRepoAsync(repo.Id)).Visibility);

        // Rename changes the row and the URL, never the directory.
        var renamed = await ForgeHost.PostFormAsync(client, "/jessie/managed/settings", "rename", new() { ["NewName"] = "renamed" });
        Assert.Equal("/jessie/renamed/settings", renamed.Headers.Location?.PathAndQuery);
        Assert.Equal("renamed", (await host.ReloadRepoAsync(repo.Id)).Name);
        Assert.True(Directory.Exists(directory));
        Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/managed")).StatusCode);
        Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/jessie/renamed")).StatusCode);

        // Default branch: push two branches, then switch.
        var token = await host.CreateTokenAsync(user, canWrite: true);
        var work = host.NewDir("work");
        await host.Git.CreateWorkRepoAsync(work);
        await host.Git.MustAsync(work, "branch", "develop");
        await host.Git.MustAsync(work, "push", host.GitUrl("jessie", "renamed", token), "main", "develop");
        await ForgeHost.PostFormAsync(client, "/jessie/renamed/settings", "default-branch", new() { ["Branch"] = "develop" });
        Assert.Equal("develop", (await host.ReloadRepoAsync(repo.Id)).DefaultBranch);
        var bogus = await ForgeHost.PostFormAsync(client, "/jessie/renamed/settings", "default-branch", new() { ["Branch"] = "--delete" });
        Assert.Contains("alert error", await ForgeHost.TextAsync(bogus));

        // Delete needs the name typed back.
        var refused = await ForgeHost.PostFormAsync(client, "/jessie/renamed/settings", "delete", new() { ["ConfirmName"] = "wrong" });
        Assert.Contains("does not match", await ForgeHost.TextAsync(refused));
        Assert.True(Directory.Exists(directory));

        var deleted = await ForgeHost.PostFormAsync(client, "/jessie/renamed/settings", "delete", new() { ["ConfirmName"] = "renamed" });
        Assert.Equal("/", deleted.Headers.Location?.PathAndQuery);
        Assert.False(Directory.Exists(directory));
        Assert.False(await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().Repositories.AnyAsync(r => r.Id == repo.Id)));
    }

    [Fact]
    public async Task Tokens_are_shown_once_and_stored_hashed()
    {
        var user = await host.CreateUserAsync();
        using var client = await host.CreateSignedInClientAsync();

        var created = await ForgeHost.PostFormAsync(client, "/settings/tokens", "create-token", new()
        {
            ["Name"] = "laptop",
            ["Scope"] = "write",
            ["ExpiresInDays"] = "30",
        });
        var html = await created.Content.ReadAsStringAsync();
        var plaintext = System.Text.RegularExpressions.Regex.Match(html, "forge_[0-9a-f]{64}").Value;
        Assert.NotEmpty(plaintext);

        var row = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().AccessTokens.SingleAsync(t => t.Name == "laptop"));
        Assert.Equal(Features.Auth.TokenService.Hash(plaintext), row.TokenHash);
        Assert.True(row.CanWrite);
        Assert.InRange(row.ExpiresAt!.Value, DateTime.UtcNow.AddDays(29), DateTime.UtcNow.AddDays(31));

        // Loading the page again does not show it, and the database never had it.
        Assert.DoesNotContain(plaintext, await client.GetStringAsync("/settings/tokens"));
        foreach (var file in Directory.GetFiles(host.DataPath, "forge.db*"))
        {
            // The app has the database open, so read it with sharing. The WAL file counts too.
            await using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
            using var buffer = new MemoryStream();
            await stream.CopyToAsync(buffer);
            Assert.DoesNotContain(plaintext, System.Text.Encoding.Latin1.GetString(buffer.ToArray()));
        }

        // The token works for git, and stops working once revoked.
        var repo = await host.CreateRepoAsync(user, "token-check", Visibility.Private);
        var work = host.NewDir("work");
        await host.Git.CreateWorkRepoAsync(work);
        await host.Git.MustAsync(work, "push", host.GitUrl("jessie", repo.Name, plaintext), "main");

        await ForgeHost.PostFormAsync(client, "/settings/tokens", "revoke-token", new() { ["TokenId"] = row.Id.ToString() });
        Assert.False(await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().AccessTokens.AnyAsync(t => t.Id == row.Id)));
        Assert.False((await host.Git.RunAsync(work, "push", host.GitUrl("jessie", repo.Name, plaintext), "main", "--force")).Ok);
    }

    [Fact]
    public async Task Rename_does_not_touch_the_directory()
    {
        var user = await host.CreateUserAsync();
        var repo = await host.CreateRepoAsync(user, "before-rename", Visibility.Private);
        var directory = host.RepoDirectory(repo.Id);
        var created = Directory.GetCreationTimeUtc(directory);

        var error = await host.WithScopeAsync(async sp =>
        {
            var service = sp.GetRequiredService<RepoService>();
            var tracked = await service.FindAsync("jessie", "before-rename");
            return await service.RenameAsync(tracked!, "after-rename");
        });

        Assert.Null(error);
        Assert.True(Directory.Exists(directory));
        Assert.Equal(created, Directory.GetCreationTimeUtc(directory));
        Assert.Equal([directory], Directory.GetDirectories(Path.GetDirectoryName(directory)!, repo.Id + ".git"));
    }
}

/// <summary>First-run setup needs an empty database, so it gets a host of its own.</summary>
public class SetupTests(ForgeHost host) : IClassFixture<ForgeHost>
{
    [Fact]
    public async Task Setup_creates_the_first_account_and_then_closes_for_good()
    {
        using var client = host.CreateClient();

        // With no account, the home page leads to setup.
        var home = await client.GetAsync("/");
        Assert.Equal("/setup", home.Headers.Location?.PathAndQuery);
        Assert.True(File.Exists(Path.Combine(host.DataPath, "forge.db")));
        Assert.True(Directory.Exists(Path.Combine(host.DataPath, "repos")));

        var mismatch = await ForgeHost.PostFormAsync(client, "/setup", "setup", new()
        {
            ["Username"] = "jessie",
            ["Password"] = ForgeHost.Password,
            ["PasswordRepeat"] = "something else",
        });
        Assert.Contains("do not match", await ForgeHost.TextAsync(mismatch));

        var reserved = await ForgeHost.PostFormAsync(client, "/setup", "setup", new()
        {
            ["Username"] = "settings",
            ["Password"] = ForgeHost.Password,
            ["PasswordRepeat"] = ForgeHost.Password,
        });
        Assert.Contains("reserved", await ForgeHost.TextAsync(reserved));

        var created = await ForgeHost.PostFormAsync(client, "/setup", "setup", new()
        {
            ["Username"] = "jessie",
            ["DisplayName"] = "Jessie",
            ["Password"] = ForgeHost.Password,
            ["PasswordRepeat"] = ForgeHost.Password,
        });
        Assert.Equal(HttpStatusCode.Redirect, created.StatusCode);
        Assert.Equal("/", created.Headers.Location?.PathAndQuery);

        // Setup signed the new user in.
        var signedIn = await client.GetStringAsync("/");
        Assert.Contains("Sign out (jessie)", signedIn);

        // The password is stored hashed.
        var user = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().Users.SingleAsync());
        Assert.DoesNotContain(ForgeHost.Password, user.PasswordHash);

        // Setup is gone, for the signed-in user and for strangers, on GET and on POST.
        using var stranger = host.CreateClient();
        Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/setup")).StatusCode);
        Assert.Equal(HttpStatusCode.NotFound, (await stranger.GetAsync("/setup")).StatusCode);
        var loginPage = await stranger.GetAsync("/login");
        var token = System.Text.RegularExpressions.Regex.Match(
            await loginPage.Content.ReadAsStringAsync(), "name=\"__RequestVerificationToken\" value=\"([^\"]+)\"").Groups[1].Value;
        var second = await stranger.PostAsync("/setup", new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["__RequestVerificationToken"] = token,
            ["_handler"] = "setup",
            ["Username"] = "intruder",
            ["Password"] = ForgeHost.Password,
            ["PasswordRepeat"] = ForgeHost.Password,
        }));
        // The page no longer renders a form, so the framework refuses the post (400) before any handler runs.
        Assert.True(
            second.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.BadRequest,
            $"POST /setup answered {(int)second.StatusCode}");
        Assert.Equal(1, await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().Users.CountAsync()));

        // Logout ends the session; a wrong password does not start one; the right one does.
        var page = await client.GetStringAsync("/");
        var logoutToken = System.Text.RegularExpressions.Regex.Match(page, "name=\"__RequestVerificationToken\" value=\"([^\"]+)\"").Groups[1].Value;
        var loggedOut = await client.PostAsync("/logout", new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["__RequestVerificationToken"] = logoutToken,
        }));
        Assert.Equal(HttpStatusCode.Redirect, loggedOut.StatusCode);
        Assert.Contains("Sign in", await client.GetStringAsync("/"));

        var wrong = await ForgeHost.PostFormAsync(client, "/login", "login", new() { ["Username"] = "jessie", ["Password"] = "wrong password" });
        Assert.Equal(HttpStatusCode.OK, wrong.StatusCode);
        Assert.Contains("Wrong username or password", await ForgeHost.TextAsync(wrong));

        var right = await ForgeHost.PostFormAsync(client, "/login?returnUrl=%2Fnew", "login", new() { ["Username"] = "JESSIE", ["Password"] = ForgeHost.Password });
        Assert.Equal("/new", right.Headers.Location?.PathAndQuery);

        // An off-site return URL is ignored.
        using var other = host.CreateClient();
        var offsite = await ForgeHost.PostFormAsync(other, "/login?returnUrl=%2F%2Fevil.example", "login", new() { ["Username"] = "jessie", ["Password"] = ForgeHost.Password });
        Assert.Equal("/", offsite.Headers.Location?.PathAndQuery);
    }
}

/// <summary>The login limiter is per client address, so this needs a host nobody else is logging in to.</summary>
public class RateLimitTests(ForgeHost host) : IClassFixture<ForgeHost>
{
    [Fact]
    public async Task Login_attempts_are_rate_limited()
    {
        await host.CreateUserAsync();
        using var client = host.CreateClient();

        var statuses = new List<HttpStatusCode>();
        for (var i = 0; i < 12; i++)
        {
            var response = await ForgeHost.PostFormAsync(client, "/login", "login", new() { ["Username"] = "jessie", ["Password"] = "guess " + i });
            statuses.Add(response.StatusCode);
        }

        Assert.All(statuses.Take(10), s => Assert.Equal(HttpStatusCode.OK, s));
        Assert.Contains(HttpStatusCode.TooManyRequests, statuses.Skip(10));
        // Reading the login page is still possible.
        Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/login")).StatusCode);
    }
}

Keyboard shortcuts

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