using System.Net; using Forge.Data; using Forge.Features.Repos; using Forge.Tests.Support; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace Forge.Tests; /// Pages, permissions and the raw endpoint, over HTTP against the running app. public class WebTests(ForgeHost host) : IClassFixture { 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(); 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", home); Assert.Contains("

Hello

", 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", 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("

Hello

", 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("Add the app", 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 the 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/anvil.cs", page); Assert.Contains("anvil.bin", page); Assert.Contains("The Anvil 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("anvil.*", literal); Assert.DoesNotContain("is heavy", literal); var html = await client.GetStringAsync("/jessie/searchable/search?q=" + Uri.EscapeDataString("the")); Assert.Contains("<b>the</b>", html); Assert.DoesNotContain("the", 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 Hammer", 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: "\n"); await File.WriteAllTextAsync(Path.Combine(work, "icon.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("\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("<script>alert(1)</script>", page); Assert.DoesNotContain("", 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("