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; /// /// 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. /// 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!; /// Extra command-line configuration, set by a subclass-free test before InitializeAsync runs. public List ExtraArgs { get; } = []; /// The forge project folder, found by walking up to the solution file, wherever the build output lives. 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"); /// Clone URL with the token embedded as the password, the way a user would paste it. 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 WithScopeAsync(Func> action) { await using var scope = Services.CreateAsyncScope(); return await action(scope.ServiceProvider); } public Task CreateUserAsync(string username = "jessie") => WithScopeAsync(async sp => { var db = sp.GetRequiredService(); // 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>().HashPassword(user, Password); db.Users.Add(user); await db.SaveChangesAsync(); return user; }); public Task CreateRepoAsync(User owner, string name, Visibility visibility) => WithScopeAsync(async sp => { var (repo, error) = await sp.GetRequiredService().CreateAsync(owner.Id, name, "", visibility); Assert.True(repo is not null, error); return repo!; }); public Task CreateTokenAsync(User user, bool canWrite, DateTime? expiresAt = null) => WithScopeAsync(async sp => { var (_, plaintext) = await sp.GetRequiredService() .CreateAsync(user.Id, canWrite ? "write" : "read", canWrite, expiresAt); return plaintext; }); public Task ReloadRepoAsync(long id) => WithScopeAsync(async sp => (await sp.GetRequiredService().Repositories.FindAsync(id))!); /// A client that keeps cookies and does not follow redirects, so tests can assert on them. public HttpClient CreateClient() => new(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = new Uri(BaseUrl), }; /// Submits a server-rendered form the way a browser would: load the page, then post with its antiforgery token. public static async Task PostFormAsync( HttpClient client, string pageUrl, string formName, Dictionary 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(fields) { ["__RequestVerificationToken"] = WebUtility.HtmlDecode(match.Groups[1].Value), ["_handler"] = formName, }; return await client.PostAsync(pageUrl, new FormUrlEncodedContent(form)); } /// Page text with HTML entities decoded; the renderer writes non-ASCII letters as entities. public static async Task TextAsync(HttpResponseMessage response) => WebUtility.HtmlDecode(await response.Content.ReadAsStringAsync()); private readonly Dictionary _sessions = []; /// /// 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. /// public async Task 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; } /// Creates a repository and pushes one commit to it. Returns the pushed commit SHA. 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(); }