Forge

Jessie / forge public

Self-hosted git - made by qwen 3.8 27b

branch: main

Branches

main
ForgeHost.cs 8.5 kB · 213 lines RawPermalinkHistory
using System.Net;
using System.Text.RegularExpressions;
using Forge.Data;
using Forge.Features.Auth;
using Forge.Features.Repos;
using Forge.Git;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.DependencyInjection;

namespace Forge.Tests.Support;

/// <summary>
/// The real app on a random local port with a temporary data directory and database.
/// Tests talk to it over HTTP, with HttpClient and with the real git client.
/// </summary>
public sealed partial class ForgeHost : IAsyncLifetime
{
    public const string Password = "correct horse battery";

    private readonly TempDir _temp = new();
    private WebApplication _app = null!;

    public string BaseUrl { get; private set; } = "";
    public string DataPath => Path.Combine(_temp.Path, "data");
    public IServiceProvider Services => _app.Services;
    public TestGit Git { get; private set; } = null!;

    /// <summary>Extra command-line configuration, set by a subclass-free test before InitializeAsync runs.</summary>
    public List<string> ExtraArgs { get; } = [];

    /// <summary>The forge project folder, found by walking up to the solution file, wherever the build output lives.</summary>
    public static string WebProjectDirectory
    {
        get
        {
            for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
            {
                if (File.Exists(Path.Combine(dir.FullName, "forge.slnx")))
                {
                    return Path.Combine(dir.FullName, "forge");
                }
            }

            throw new DirectoryNotFoundException("forge.slnx was not found above " + AppContext.BaseDirectory);
        }
    }

    public async Task InitializeAsync()
    {
        Git = new TestGit(_temp.Sub("client-home"));
        string[] args =
        [
            "--urls=http://127.0.0.1:0",
            "--environment=Production",
            "--Forge:DataPath=" + DataPath,
            "--Forge:BaseUrl=http://forge.test",
            "--Forge:GitPath=" + TestGit.Executable,
            "--Logging:LogLevel:Default=Warning",
            // The web project's directory, so wwwroot is served as it is in a real run.
            "--contentRoot=" + WebProjectDirectory,
            .. ExtraArgs,
        ];
        _app = ForgeApp.Build(args);
        await ForgeApp.InitializeAsync(_app);
        await _app.StartAsync();
        BaseUrl = _app.Urls.First().TrimEnd('/');
    }

    public async Task DisposeAsync()
    {
        await _app.StopAsync();
        await _app.DisposeAsync();
        SqliteConnection.ClearAllPools();
        _temp.Dispose();
    }

    public string NewDir(string name) => _temp.Sub(name + "-" + Guid.NewGuid().ToString("N")[..8]);

    public string RepoDirectory(long repoId) => Path.Combine(DataPath, "repos", repoId + ".git");

    /// <summary>Clone URL with the token embedded as the password, the way a user would paste it.</summary>
    public string GitUrl(string owner, string repo, string? token = null)
    {
        var authority = BaseUrl["http://".Length..];
        return token is null
            ? $"http://{authority}/{owner}/{repo}.git"
            : $"http://git:{token}@{authority}/{owner}/{repo}.git";
    }

    public async Task<T> WithScopeAsync<T>(Func<IServiceProvider, Task<T>> action)
    {
        await using var scope = Services.CreateAsyncScope();
        return await action(scope.ServiceProvider);
    }

    public Task<User> CreateUserAsync(string username = "jessie") =>
        WithScopeAsync(async sp =>
        {
            var db = sp.GetRequiredService<ForgeDb>();
            // Tests in one class share the host, so the user may already be there.
            if (db.Users.FirstOrDefault(u => u.Username == username) is { } existing)
            {
                return existing;
            }

            var user = new User { Username = username, DisplayName = username, CreatedAt = DateTime.UtcNow };
            user.PasswordHash = sp.GetRequiredService<IPasswordHasher<User>>().HashPassword(user, Password);
            db.Users.Add(user);
            await db.SaveChangesAsync();
            return user;
        });

    public Task<Repository> CreateRepoAsync(User owner, string name, Visibility visibility) =>
        WithScopeAsync(async sp =>
        {
            var (repo, error) = await sp.GetRequiredService<RepoService>().CreateAsync(owner.Id, name, "", visibility);
            Assert.True(repo is not null, error);
            return repo!;
        });

    public Task<string> CreateTokenAsync(User user, bool canWrite, DateTime? expiresAt = null) =>
        WithScopeAsync(async sp =>
        {
            var (_, plaintext) = await sp.GetRequiredService<TokenService>()
                .CreateAsync(user.Id, canWrite ? "write" : "read", canWrite, expiresAt);
            return plaintext;
        });

    public Task<Repository> ReloadRepoAsync(long id) =>
        WithScopeAsync(async sp => (await sp.GetRequiredService<ForgeDb>().Repositories.FindAsync(id))!);

    /// <summary>A client that keeps cookies and does not follow redirects, so tests can assert on them.</summary>
    public HttpClient CreateClient() =>
        new(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() })
        {
            BaseAddress = new Uri(BaseUrl),
        };

    /// <summary>Submits a server-rendered form the way a browser would: load the page, then post with its antiforgery token.</summary>
    public static async Task<HttpResponseMessage> PostFormAsync(
        HttpClient client,
        string pageUrl,
        string formName,
        Dictionary<string, string> fields)
    {
        var page = await client.GetAsync(pageUrl);
        var html = await page.Content.ReadAsStringAsync();
        var match = AntiforgeryToken().Match(html);
        Assert.True(match.Success, $"No antiforgery token on {pageUrl} (status {(int)page.StatusCode}).");

        var form = new Dictionary<string, string>(fields)
        {
            ["__RequestVerificationToken"] = WebUtility.HtmlDecode(match.Groups[1].Value),
            ["_handler"] = formName,
        };
        return await client.PostAsync(pageUrl, new FormUrlEncodedContent(form));
    }

    /// <summary>Page text with HTML entities decoded; the renderer writes non-ASCII letters as entities.</summary>
    public static async Task<string> TextAsync(HttpResponseMessage response) =>
        WebUtility.HtmlDecode(await response.Content.ReadAsStringAsync());

    private readonly Dictionary<string, CookieContainer> _sessions = [];

    /// <summary>
    /// A client signed in as the user. The login happens once per host and its cookies are reused,
    /// so a class with many tests does not run into the login rate limit.
    /// </summary>
    public async Task<HttpClient> CreateSignedInClientAsync(string username = "jessie")
    {
        if (_sessions.TryGetValue(username, out var cookies))
        {
            return new HttpClient(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true, CookieContainer = cookies })
            {
                BaseAddress = new Uri(BaseUrl),
            };
        }

        cookies = new CookieContainer();
        _sessions[username] = cookies;
        var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true, CookieContainer = cookies })
        {
            BaseAddress = new Uri(BaseUrl),
        };
        var response = await PostFormAsync(client, "/login", "login", new()
        {
            ["Username"] = username,
            ["Password"] = Password,
        });
        Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
        return client;
    }

    /// <summary>Creates a repository and pushes one commit to it. Returns the pushed commit SHA.</summary>
    public async Task<(Repository Repo, string Sha, string WorkDir)> CreatePushedRepoAsync(
        User owner,
        string name,
        Visibility visibility,
        string fileName = "README.md",
        string content = "# Demo\n")
    {
        var repo = await CreateRepoAsync(owner, name, visibility);
        var token = await CreateTokenAsync(owner, canWrite: true);
        var work = NewDir("work");
        var sha = await Git.CreateWorkRepoAsync(work, fileName: fileName, content: content);
        await Git.MustAsync(work, "push", GitUrl(owner.Username, name, token), "main");
        return (repo, sha, work);
    }

    [GeneratedRegex("name=\"__RequestVerificationToken\" value=\"([^\"]+)\"")]
    private static partial Regex AntiforgeryToken();
}

Keyboard shortcuts

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