diff --git a/.github/workflows/tls-lifecycle.yml b/.github/workflows/tls-lifecycle.yml index 839e3e5..312634b 100644 --- a/.github/workflows/tls-lifecycle.yml +++ b/.github/workflows/tls-lifecycle.yml @@ -1,15 +1,22 @@ -name: TLS lifecycle tests +name: Application regression tests on: pull_request: paths: - "TruthGate-Web/**" + - "Test.TruthGate/**" + - "Publish.CLI/**" + - "TruthGate-IPFS.sln" + - "docker/**" - ".github/workflows/tls-lifecycle.yml" push: - branches: - - master + branches: [master] paths: - "TruthGate-Web/**" + - "Test.TruthGate/**" + - "Publish.CLI/**" + - "TruthGate-IPFS.sln" + - "docker/**" - ".github/workflows/tls-lifecycle.yml" workflow_call: @@ -19,28 +26,19 @@ permissions: jobs: test: runs-on: ubuntu-latest - steps: - uses: actions/checkout@v4 - - uses: actions/setup-dotnet@v4 with: dotnet-version: "10.0.x" - + - uses: actions/setup-node@v4 + with: + node-version: "22" - name: Restore solution run: dotnet restore TruthGate-IPFS.sln - - # This test project is intentionally outside TruthGate-IPFS.sln, so restore it explicitly. - - name: Restore TLS tests - run: dotnet restore TruthGate-Web/TruthGate-Web.Tests/TruthGate-Web.Tests.csproj - - name: Build solution run: dotnet build TruthGate-IPFS.sln --no-restore --configuration Release - - - name: Test TLS lifecycle - run: >- - dotnet test - TruthGate-Web/TruthGate-Web.Tests/TruthGate-Web.Tests.csproj - --no-restore - --configuration Release - --logger "console;verbosity=normal" + - name: Test application regressions + run: dotnet test TruthGate-IPFS.sln --no-build --configuration Release --logger "console;verbosity=normal" + - name: Check persisted Kubo boolean settings + run: bash docker/tests/kubo-settings.sh diff --git a/Publish.CLI/Program.cs b/Publish.CLI/Program.cs index 46f154f..802e8df 100644 --- a/Publish.CLI/Program.cs +++ b/Publish.CLI/Program.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using System.Net.Http.Headers; using System.Net.Security; using System.Net.Sockets; @@ -46,6 +46,7 @@ public static int Main(string[] args) } Console.WriteLine($"→ Found {safeCount:n0} safe files; total size ≈ {FormatBytes(totalBytes)}"); + if (safeCount == 0) throw new Options.BadOptions("The selected root contains no files to publish."); if (skipped > 0) Console.WriteLine($"→ Skipped {skipped:n0} file(s) due to unsafe relative paths."); @@ -112,9 +113,9 @@ public static int Main(string[] args) }; } - var client = new HttpClient(handler) + using var client = new HttpClient(handler) { - Timeout = Timeout.InfiniteTimeSpan + Timeout = TimeSpan.FromSeconds(opts.TimeoutSeconds) }; // If you want to avoid any HTTP/2/ALPN surprises: @@ -153,7 +154,7 @@ public static int Main(string[] args) UploadBatch(batch, batchIndex, url, opts, client, rootCanonical, ref sentBytes); } - Console.WriteLine("✔ Done."); + Console.WriteLine("✔ Upload accepted. Check the returned publication status URL for completion."); return 0; } catch (Options.BadOptions ex) @@ -168,7 +169,7 @@ public static int Main(string[] args) Console.Error.WriteLine("❌ HTTP error: " + ex.Message); return 3; } - catch (TaskCanceledException) + catch (OperationCanceledException) { Console.Error.WriteLine("❌ Upload canceled or timed out."); return 4; @@ -220,14 +221,19 @@ static void UploadBatch( Console.WriteLine($"→ Uploading batch {batchIndex:n0} …"); using var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = multipart }; - using var resp = client.Send(req, HttpCompletionOption.ResponseHeadersRead); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(opts.TimeoutSeconds)); + // ConnectCallback is asynchronous, and the same deadline also bounds reading the status body. + using var resp = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, timeout.Token).GetAwaiter().GetResult(); if (!resp.IsSuccessStatusCode) { - string body = SafeReadString(resp); + string body = SafeReadString(resp, timeout.Token); throw new HttpRequestException($"Server responded {((int)resp.StatusCode)} {resp.ReasonPhrase}. Body: {Truncate(body, 800)}"); } + var responseBody = SafeReadString(resp, timeout.Token); + if (!string.IsNullOrWhiteSpace(responseBody)) Console.WriteLine(responseBody); + long batchBytes = 0; foreach (var p in batch) { @@ -395,9 +401,10 @@ static string Encode5987(string value) // ------------------------------------------------------------------------- - static string SafeReadString(HttpResponseMessage resp) + static string SafeReadString(HttpResponseMessage resp, CancellationToken ct) { - try { return resp.Content.ReadAsStringAsync().GetAwaiter().GetResult(); } + try { return resp.Content.ReadAsStringAsync(ct).GetAwaiter().GetResult(); } + catch (OperationCanceledException) { throw; } catch { return ""; } } @@ -443,7 +450,7 @@ sealed class Options OPTIONAL: --insecure Skip TLS certificate validation (like curl -k) - --batchSize Files per request (default 0). Use 0 for one giant request. + --batchSize Must be 0. Chunked publication sessions are not supported. --timeoutSeconds Whole-request timeout (default 604,800) --verbose Print each file's relative name -h | --help Show this help @@ -520,7 +527,7 @@ public void ValidateOrThrow() if (string.IsNullOrWhiteSpace(UserIp)) throw new BadOptions("Missing --userIp."); if (string.IsNullOrWhiteSpace(Root)) throw new BadOptions("Missing --root."); if (!Directory.Exists(Root)) throw new BadOptions($"Root does not exist: {Root}"); - if (BatchSize < 0) throw new BadOptions("--batchSize must be >= 0"); + if (BatchSize != 0) throw new BadOptions("--batchSize must be 0: the server publishes each request as a complete site; partial batches are unsafe."); if (TimeoutSeconds <= 0) throw new BadOptions("--timeoutSeconds must be > 0"); } @@ -536,4 +543,4 @@ static string ExtractHost(string httpsUrl) return u.Host; } -} \ No newline at end of file +} diff --git a/README.md b/README.md index d34414d..519e51a 100644 --- a/README.md +++ b/README.md @@ -29,9 +29,9 @@ TruthGate sits at that boundary. Kubo remains responsible for IPFS. TruthGate pr ### Accounts, sessions, and API keys -TruthGate has a login-protected management portal with role-based user accounts. The first boot creates an `admin` account with a unique generated password instead of a shared default credential. Additional users and password changes are managed from the portal. +TruthGate has a login-protected management portal with administrative user accounts. The first boot creates an `admin` account with a unique generated password instead of a shared default credential. Additional users and password changes are managed from the portal. -Applications can use API keys rather than interactive sessions. Keys are shown once when created and stored as hashes. They can be revoked without changing a user's password. +Applications can use API keys rather than interactive sessions. Keys are shown once when created and stored as hashes. They can be revoked without changing a user's password. All current users and keys have node administration access; separate roles and per-domain key scopes are not implemented. ![TruthGate user management](content/images/demo/users-dark.webp) @@ -39,7 +39,7 @@ Applications can use API keys rather than interactive sessions. Keys are shown o TruthGate proxies the native IPFS WebUI through the authenticated portal. Operators keep the interface they already know for browsing files, creating folders, importing content, and managing pins, but the underlying Kubo gateway and RPC API stay bound to loopback inside the appliance. -TruthGate also exposes familiar routes such as `/ipfs/`, `/ipns/`, and the supported `/api/v0/` proxy through its own TLS, authentication, API-key, and rate-protection layers. +The authenticated `/api/v0/` proxy provides administrative Kubo RPC access. Arbitrary `/ipfs/` and `/ipns/` browsing redirects to a separately hosted HTTPS gateway configured with `Gateway:ContentGatewayOrigin`; without that setting it returns `409`. The local node's identified WebUI is the trusted exception. Published websites continue to use their mapped domains. See [security boundaries](docs/concepts/security-boundaries.md) and the [audit remediation guide](docs/developer/audit-remediation.md). ### CID and IPNS pinning diff --git a/Test.TruthGate/Test.TruthGate.csproj b/Test.TruthGate/Test.TruthGate.csproj index a396ab3..3fee0a5 100644 --- a/Test.TruthGate/Test.TruthGate.csproj +++ b/Test.TruthGate/Test.TruthGate.csproj @@ -1,4 +1,4 @@ - + net10.0 @@ -12,9 +12,9 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Test.TruthGate/Tests/AdminProtectedTests.cs b/Test.TruthGate/Tests/AdminProtectedTests.cs index 19f42c0..8455226 100644 --- a/Test.TruthGate/Tests/AdminProtectedTests.cs +++ b/Test.TruthGate/Tests/AdminProtectedTests.cs @@ -1,74 +1,40 @@ -using System; -using System.Collections.Generic; -using System.Linq; using System.Net; -using System.Text; -using System.Threading.Tasks; -namespace Test.TruthGate.Tests +namespace Test.TruthGate.Tests; + +[Collection("TruthGateServerCollection")] +public sealed class AdminProtectedTests(SqliteTestFixture fixture) { - [Collection("TruthGateServerCollection")] - public sealed class AdminProtectedTests : IAsyncLifetime + [Fact] + public async Task ValidKey_Bypasses_Anonymous_Limits() { - private readonly TruthGateWebApplicationFactory _f; - private readonly TestClient _client; - private readonly IServiceProvider _sp; - - public AdminProtectedTests(SqliteTestFixture fx) - { - _f = new TruthGateWebApplicationFactory(fx); - _sp = _f.Services; - _client = new TestClient(_f.CreateClient()); - } - - public Task InitializeAsync() => Task.CompletedTask; - public Task DisposeAsync() { _f.Dispose(); return Task.CompletedTask; } - - [Fact] - public async Task ValidKey_Allows_Unlimited() - { - var ip = "127.0.0.1"; - var resps = await _client.BurstAsync("/admin/secret", count: 4000, ip: ip, apiKey: TruthGateWebApplicationFactory.ValidAdminKey); - Assert.All(resps, r => Assert.Equal(HttpStatusCode.OK, r.StatusCode)); - } - - [Fact] - public async Task InvalidKey_Threshold_Bans() - { - var ip = "127.0.1.1"; - // 3 invalid attempts - for (int i = 0; i < 3; i++) await _client.SendAsync("/admin/secret", ip: ip, apiKey: "NOPE"); - // persist counters - await _client.FlushAsync(); - // Next attempt triggers soft ban → 401 still (oracle-proof) or 403? In current impl: still 401 until ban check fires next time - var r = await _client.SendAsync("/admin/secret", ip: ip, apiKey: "NOPE"); - Assert.Equal(HttpStatusCode.Unauthorized, r.StatusCode); - // subsequent request should hit ban 403 because RecordFailureAsync added ban when threshold reached - HttpResponseMessage? r2 = null; - for (int i = 0; i < 10; i++) - { - r2 = await _client.SendAsync("/admin/secret", ip: ip, apiKey: "NOPE"); - } - Assert.Equal(HttpStatusCode.Forbidden, r2.StatusCode); - } - - [Fact(Skip = "Grace (IP,key) failure exemption not implemented in current limiter")] - public Task GracePair_Success_Suppresses_BadKey_Counts() => Task.CompletedTask; + using var server = new TruthGateWebApplicationFactory(fixture); + var client = new TestClient(server.CreateClient()); + var responses = await client.BurstAsync("/admin/secret", 32, ip: "192.0.2.40", apiKey: TruthGateWebApplicationFactory.ValidAdminKey); + Assert.All(responses, response => Assert.Equal(HttpStatusCode.OK, response.StatusCode)); + } - [Fact(Skip = "Admin 4x/10x escalation not implemented in current limiter")] - public Task Admin_Escalation_To_TrueBan() => Task.CompletedTask; + [Fact] + public async Task InvalidKey_Threshold_Bans() + { + using var server = new TruthGateWebApplicationFactory(fixture); + var client = new TestClient(server.CreateClient()); + for (var i = 0; i < 2; i++) + Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync("/admin/secret", "192.0.2.41", apiKey: "invalid")).StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync("/admin/secret", "192.0.2.41", apiKey: "invalid")).StatusCode); + await client.FlushAsync(); + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync("/admin/secret", "192.0.2.41", apiKey: "invalid")).StatusCode); + } - [Fact] - public async Task Oracle_Proof_Bodies_Are_Identical() - { - var ip = "127.0.2.3"; - var missing = await _client.SendAsync("/admin/secret", ip: ip); - var invalid = await _client.SendAsync("/admin/secret", ip: ip, apiKey: "WRONG"); - var b1 = await missing.Content.ReadAsStringAsync(); - var b2 = await invalid.Content.ReadAsStringAsync(); - Assert.Equal(HttpStatusCode.Unauthorized, missing.StatusCode); - Assert.Equal(HttpStatusCode.Unauthorized, invalid.StatusCode); - Assert.Equal(b1, b2); - } + [Fact] + public async Task Missing_And_Invalid_Keys_Have_Identical_Unauthorized_Bodies() + { + using var server = new TruthGateWebApplicationFactory(fixture); + var client = new TestClient(server.CreateClient()); + using var missing = await client.SendAsync("/admin/secret", "192.0.2.42"); + using var invalid = await client.SendAsync("/admin/secret", "192.0.2.42", apiKey: "invalid"); + Assert.Equal(HttpStatusCode.Unauthorized, missing.StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, invalid.StatusCode); + Assert.Equal(await missing.Content.ReadAsStringAsync(), await invalid.Content.ReadAsStringAsync()); } } diff --git a/Test.TruthGate/Tests/ApiKeyPipelineTests.cs b/Test.TruthGate/Tests/ApiKeyPipelineTests.cs new file mode 100644 index 0000000..8320faf --- /dev/null +++ b/Test.TruthGate/Tests/ApiKeyPipelineTests.cs @@ -0,0 +1,187 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System.Net; +using TruthGate_Web.Models; +using TruthGate_Web.Security; +using TruthGate_Web.Services; +using TruthGate_Web.Utils; + +namespace Test.TruthGate.Tests; + +[Collection("TruthGateServerCollection")] +public sealed class ApiKeyPipelineTests(SqliteTestFixture fixture) +{ + [Theory] + [InlineData("X-Admin-Key")] + [InlineData("X-API-Key")] + [InlineData("Bearer")] + [InlineData("api_key")] + [InlineData("key")] + public async Task Every_supported_transport_is_validated_once_before_gateway_decisions(string transport) + { + using var server = new TruthGateWebApplicationFactory(fixture, configure: options => + { + options.Gateway.AutoWhitelistOnAuthOrValidKey = false; + options.Gateway.FreePerMinute = 0; + options.Gateway.HourlyOverage = 0; + }); + using var client = server.CreateClient(); + using var request = Request("/admin/secret", transport, TruthGateWebApplicationFactory.ValidAdminKey); + using var response = await client.SendAsync(request); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(1, server.Keys.ValidationCount); + var limiter = (RateLimiterService)server.Services.GetRequiredService(); + await limiter.FlushAsync(); + await using var db = server.Services.GetRequiredService>().CreateDbContext(); + var usage = await db.IpMinuteCounters.SingleAsync(); + Assert.Equal(0, usage.AdminBadKeyCalls); + Assert.Equal(1, usage.AdminGoodKeyCalls); + Assert.Equal(0, usage.GatewayCalls); + Assert.Equal(1, (await db.GlobalMinuteCounters.SingleAsync()).TotalCalls); + } + + [Fact] + public async Task Existing_hashed_keys_remain_accepted_without_changing_the_token_format() + { + using var server = new TruthGateWebApplicationFactory(fixture); + var config = server.Services.GetRequiredService(); + await config.UpdateAsync(value => value.ApiKeys.Add(new ApiKey + { Name = "legacy", KeyHashed = StringHasher.HashString("legacy-secret") })); + using var client = server.CreateClient(); + using var response = await client.SendAsync(Request("/admin/secret", "X-API-Key", "legacy-secret")); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(1, server.Keys.ValidationCount); + } + + [Fact] + public async Task Invalid_key_is_counted_once_across_gateway_and_protected_route_middleware() + { + using var server = new TruthGateWebApplicationFactory(fixture); + using var client = server.CreateClient(); + using var response = await client.SendAsync(Request("/admin/secret", "X-API-Key", "invalid")); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal(1, server.Keys.ValidationCount); + var limiter = (RateLimiterService)server.Services.GetRequiredService(); + await limiter.FlushAsync(); + await using var db = server.Services.GetRequiredService>().CreateDbContext(); + var usage = await db.IpMinuteCounters.SingleAsync(); + Assert.Equal(1, usage.AdminBadKeyCalls); + Assert.Equal(1, (await db.GlobalMinuteCounters.SingleAsync()).TotalCalls); + } + + [Fact] + public async Task Optional_authentication_does_not_reject_anonymous_gateway_or_login_requests() + { + using var server = new TruthGateWebApplicationFactory(fixture); + using var client = server.CreateClient(); + using var gateway = await client.SendAsync(Request("/ipfs/cat")); + using var login = await client.SendAsync(Request("/auth/login", method: HttpMethod.Post)); + Assert.Equal(HttpStatusCode.OK, gateway.StatusCode); + Assert.Equal(HttpStatusCode.OK, login.StatusCode); + Assert.Equal(0, server.Keys.ValidationCount); + var limiter = (RateLimiterService)server.Services.GetRequiredService(); + Assert.Equal(0, limiter.GetAdminBadKeyCalls("192.0.2.100", DateTimeOffset.UtcNow)); + } + + [Fact] + public async Task Optional_route_with_invalid_key_remains_anonymous_but_records_one_failure() + { + using var server = new TruthGateWebApplicationFactory(fixture); + using var client = server.CreateClient(); + using var response = await client.SendAsync(Request("/ipfs/cat", "Bearer", "invalid")); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var limiter = (RateLimiterService)server.Services.GetRequiredService(); + Assert.Equal(1, limiter.GetAdminBadKeyCalls("192.0.2.100", DateTimeOffset.UtcNow)); + } + + [Fact] + public async Task An_invalid_explicit_key_cannot_fall_back_to_cookie_identity() + { + using var server = new TruthGateWebApplicationFactory(fixture); + using var client = server.CreateClient(); + using var request = Request("/admin/secret", "Bearer", "invalid"); + request.Headers.Add("X-Test-User-Authenticated", "1"); + using var response = await client.SendAsync(request); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.False(await server.Services.GetRequiredService().IsWhitelistedAsync("192.0.2.100")); + } + + [Fact] + public async Task Cookie_identity_is_available_to_gateway_before_it_applies_anonymous_limits() + { + using var server = new TruthGateWebApplicationFactory(fixture, configure: options => + { + options.Gateway.FreePerMinute = 0; + options.Gateway.HourlyOverage = 0; + options.Gateway.AutoWhitelistOnAuthOrValidKey = false; + }); + using var client = server.CreateClient(); + using var request = Request("/admin/secret"); + request.Headers.Add("X-Test-User-Authenticated", "1"); + using var response = await client.SendAsync(request); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task A_whitelist_does_not_authorize_a_protected_endpoint() + { + using var server = new TruthGateWebApplicationFactory(fixture); + await server.Services.GetRequiredService().AddWhitelistIpAsync("192.0.2.100"); + using var client = server.CreateClient(); + using var response = await client.SendAsync(Request("/admin/secret")); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Kubo_operation_key_is_not_misclassified_as_an_API_credential(bool useCookie) + { + using var server = new TruthGateWebApplicationFactory(fixture); + using var client = server.CreateClient(); + using var request = Request("/api/v0/name/publish?key=site-signing-key", + useCookie ? null : "X-API-Key", useCookie ? null : TruthGateWebApplicationFactory.ValidAdminKey, HttpMethod.Post); + if (useCookie) request.Headers.Add("X-Test-User-Authenticated", "1"); + using var response = await client.SendAsync(request); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("site-signing-key", await response.Content.ReadAsStringAsync()); + var limiter = (RateLimiterService)server.Services.GetRequiredService(); + Assert.Equal(0, limiter.GetAdminBadKeyCalls("192.0.2.100", DateTimeOffset.UtcNow)); + } + + [Fact] + public async Task Legacy_query_key_authentication_still_works_for_anonymous_RPC_clients() + { + using var server = new TruthGateWebApplicationFactory(fixture); + using var client = server.CreateClient(); + using var response = await client.SendAsync(Request("/api/v0/name/publish", "key", + TruthGateWebApplicationFactory.ValidAdminKey, HttpMethod.Post)); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task Conflicting_aliases_are_rejected_and_identical_aliases_use_one_validation() + { + using var server = new TruthGateWebApplicationFactory(fixture); + using var client = server.CreateClient(); + using var conflict = Request("/admin/secret?key=other", "X-API-Key", TruthGateWebApplicationFactory.ValidAdminKey); + using var rejected = await client.SendAsync(conflict); + Assert.Equal(HttpStatusCode.Unauthorized, rejected.StatusCode); + Assert.Equal(0, server.Keys.ValidationCount); + using var matching = Request("/admin/secret?key=" + TruthGateWebApplicationFactory.ValidAdminKey, + "X-API-Key", TruthGateWebApplicationFactory.ValidAdminKey); + using var accepted = await client.SendAsync(matching); + Assert.Equal(HttpStatusCode.OK, accepted.StatusCode); + Assert.Equal(1, server.Keys.ValidationCount); + } + + private static HttpRequestMessage Request(string path, string? transport = null, string? key = null, HttpMethod? method = null) + { + if (transport is "api_key" or "key") path += (path.Contains('?') ? "&" : "?") + transport + "=" + Uri.EscapeDataString(key!); + var request = new HttpRequestMessage(method ?? HttpMethod.Get, path); + request.Headers.Add("X-Test-IP", "192.0.2.100"); + if (transport == "Bearer") request.Headers.Add("Authorization", "Bearer " + key); + else if (transport is not null && transport is not ("api_key" or "key")) request.Headers.Add(transport, key); + return request; + } +} diff --git a/Test.TruthGate/Tests/FailureModeTests.cs b/Test.TruthGate/Tests/FailureModeTests.cs index 26c0d92..6d39191 100644 --- a/Test.TruthGate/Tests/FailureModeTests.cs +++ b/Test.TruthGate/Tests/FailureModeTests.cs @@ -1,58 +1,20 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using TruthGate_Web.Services; +using Microsoft.EntityFrameworkCore; -namespace Test.TruthGate.Tests -{ +namespace Test.TruthGate.Tests; - [Collection("TruthGateServerCollection")] - public sealed class FailureModeTests : IAsyncLifetime +public sealed class FailureModeTests +{ + [Fact] + public async Task Persistence_failure_does_not_reset_a_full_enforcement_window() { - private readonly TruthGateWebApplicationFactory _f; - private readonly TestClient _client; - private readonly SqliteTestFixture _fx; // <-- keep the fixture - - public FailureModeTests(SqliteTestFixture fx) - { - _fx = fx; // <-- store it - _f = new TruthGateWebApplicationFactory(fx); - _client = new TestClient(_f.CreateClient()); - } - - public Task InitializeAsync() => Task.CompletedTask; - public Task DisposeAsync() { _f.Dispose(); return Task.CompletedTask; } - - [Fact] - public async Task Counter_Flush_Exception_Fails_Open_For_Counters() - { - // Use the fixture (no DI lookup) - var dbPath = Path.Combine(Path.GetDirectoryName(_fx.ConfigPath)!, "ratelimiter.db"); - - var attrs = File.GetAttributes(dbPath); - File.SetAttributes(dbPath, attrs | FileAttributes.ReadOnly); - try - { - // Generate some traffic and flush - var r1 = await _client.SendAsync("/public/ping", ip: "203.0.113.90"); - Assert.Equal(HttpStatusCode.OK, r1.StatusCode); - - // Flush (internal flush may log an error). Endpoint stays 200. - await _client.FlushAsync(); - - // Service should still serve (fail-open for counters) - var r2 = await _client.SendAsync("/public/ping", ip: "203.0.113.90"); - Assert.Equal(HttpStatusCode.OK, r2.StatusCode); - } - finally - { - File.SetAttributes(dbPath, attrs); - } - } + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + for (var i = 0; i < 6; i++) Assert.True(limiter.TryAcquirePublic("192.0.2.49", store.Clock.GetUtcNow())); + store.Interceptor.FailNext = true; + await limiter.FlushAsync(); + Assert.False(limiter.TryAcquirePublic("192.0.2.49", store.Clock.GetUtcNow())); + await limiter.FlushAsync(); + await using var db = store.Factory.CreateDbContext(); + Assert.Equal(6, (await db.IpMinuteCounters.SingleAsync()).PublicCalls); } - } diff --git a/Test.TruthGate/Tests/GatewayOverageTests.cs b/Test.TruthGate/Tests/GatewayOverageTests.cs index e0f28a3..cc9f5a2 100644 --- a/Test.TruthGate/Tests/GatewayOverageTests.cs +++ b/Test.TruthGate/Tests/GatewayOverageTests.cs @@ -1,57 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Linq; using System.Net; -using System.Text; -using System.Threading.Tasks; -namespace Test.TruthGate.Tests -{ +namespace Test.TruthGate.Tests; - [Collection("TruthGateServerCollection")] - public sealed class GatewayOverageTests : IAsyncLifetime +[Collection("TruthGateServerCollection")] +public sealed class GatewayOverageTests(SqliteTestFixture fixture) +{ + [Fact] + public async Task Exact_Overage_Allowance_Survives_A_Flush() { - private readonly TruthGateWebApplicationFactory _f; - private readonly TestClient _client; - - public GatewayOverageTests(SqliteTestFixture fx) + using var server = new TruthGateWebApplicationFactory(fixture); + var client = new TestClient(server.CreateClient()); + for (var i = 0; i < 24; i++) { - _f = new TruthGateWebApplicationFactory(fx); - _client = new TestClient(_f.CreateClient()); - } - - public Task InitializeAsync() => Task.CompletedTask; - public Task DisposeAsync() { _f.Dispose(); return Task.CompletedTask; } - - [Fact] - public async Task Overage_Consumption_Then_Ban_On_Exhaustion() - { - var ip = "172.16.0.5"; - - for (int i = 0; i < 24; i++) - { - var ok = await _client.SendAsync("/ipfs/cat", ip: ip); - Assert.Equal(HttpStatusCode.OK, ok.StatusCode); - } - - HttpResponseMessage? ban = null; - for (int i = 0; i < 277; i++) - { - ban = await _client.SendAsync("/ipfs/cat", ip: ip); - } - Assert.Equal(HttpStatusCode.Forbidden, ban.StatusCode); + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync("/ipfs/cat", "192.0.2.43")).StatusCode); + if (i == 11) await client.FlushAsync(); } + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync("/ipfs/cat", "192.0.2.43")).StatusCode); + } - [Fact] - public async Task ValidKey_AutoWhitelist_Bypasses_Gateway_Limits() - { - var ip = "172.16.0.8"; - // One call with valid key → auto-whitelist (on) and grace refresh - var first = await _client.SendAsync("/ipfs/cat", ip: ip, apiKey: TruthGateWebApplicationFactory.ValidAdminKey); - Assert.Equal(HttpStatusCode.OK, first.StatusCode); - // Now blast beyond limits; should continue OK due to whitelist - var resps = await _client.BurstAsync("/ipfs/cat", 40, ip: ip); - Assert.All(resps, r => Assert.Equal(HttpStatusCode.OK, r.StatusCode)); - } + [Fact] + public async Task ValidKey_AutoWhitelist_Bypasses_Gateway_Limits() + { + using var server = new TruthGateWebApplicationFactory(fixture); + var client = new TestClient(server.CreateClient()); + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync("/ipfs/cat", "192.0.2.44", apiKey: TruthGateWebApplicationFactory.ValidAdminKey)).StatusCode); + var responses = await client.BurstAsync("/ipfs/cat", 32, ip: "192.0.2.44"); + Assert.All(responses, response => Assert.Equal(HttpStatusCode.OK, response.StatusCode)); } } diff --git a/Test.TruthGate/Tests/GatewayRegressionTests.cs b/Test.TruthGate/Tests/GatewayRegressionTests.cs new file mode 100644 index 0000000..bbdf9c9 --- /dev/null +++ b/Test.TruthGate/Tests/GatewayRegressionTests.cs @@ -0,0 +1,492 @@ +using System.Net; +using System.Security.Claims; +using System.Text; +using System.Text.Json; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using TruthGate_Web.Endpoints; +using TruthGate_Web.Extensions; +using TruthGate_Web.Middleware; +using TruthGate_Web.Models; +using TruthGate_Web.Security; +using TruthGate_Web.Services; +using TruthGate_Web.Utils; + +namespace Test.TruthGate.Tests; + +[CollectionDefinition("Gateway regressions", DisableParallelization = true)] +public sealed class GatewayRegressionCollection { } + +[Collection("Gateway regressions")] +public sealed class GatewayRegressionTests +{ + private const string Cid = "QmYwAPJzv5CZsnAzt8auVTLvE6Gg3K7V3PJrJHGhQ7mBeV"; + private const string OtherCid = "QmT78zSuBmuS4z925WZfrqQ1UXMmdWfRf6rF4kBJngQXRc"; + + [Fact] + public async Task RepeatedMissingAssetNeverBecomesTheRoot_AndCaseVariantsStayDistinct() + { + var calls = 0; + var clients = new Clients((request, _) => + { + calls++; + if (request.Method == HttpMethod.Head) + return Reply(request.RequestUri!.AbsolutePath.EndsWith("/Readme.txt") ? 200 : 404); + return Reply(200, "{\"Objects\":[{\"Links\":[]}]}", "application/json"); + }); + using var cache = new MemoryCache(new MemoryCacheOptions()); + var first = await IpfsGateway.PathExistsInIpfsAsync(Cid, "missing.js", 9010, clients, cache, TimeSpan.FromMinutes(1)); + var count = calls; + var second = await IpfsGateway.PathExistsInIpfsAsync(Cid, "missing.js", 9010, clients, cache, TimeSpan.FromMinutes(1)); + Assert.Equal((false, (string?)null), first); + Assert.Equal(first, second); + Assert.Equal(count, calls); + Assert.True((await IpfsGateway.PathExistsInIpfsAsync(Cid, "Readme.txt", 9010, clients, cache, TimeSpan.FromMinutes(1))).exists); + Assert.False((await IpfsGateway.PathExistsInIpfsAsync(Cid, "readme.txt", 9010, clients, cache, TimeSpan.FromMinutes(1))).exists); + } + + [Fact] + public async Task UnknownLengthRequestBodyStreamsToKubo_WithoutForwardingCredentials() + { + var bytes = Encoding.UTF8.GetBytes("streamed body without Content-Length"); + var context = Context("POST", "/api/v0/add"); + context.Request.Body = new NonSeekableReadStream(bytes); + context.Request.ContentLength = null; + context.Request.Headers.Cookie = "session=secret"; + context.Request.Headers.UserAgent = "Mozilla/5.0"; + context.Request.Headers.Authorization = "Bearer secret"; + context.Request.Headers["X-Admin-Key"] = "secret"; + context.Request.Headers["Connection"] = "X-Hop"; + context.Request.Headers["X-Hop"] = "drop"; + byte[]? received = null; + var clients = new Clients(async (request, ct) => + { + Assert.NotNull(request.Content); + Assert.Null(request.Content.Headers.ContentLength); + Assert.Equal("TruthGate", request.Headers.UserAgent.ToString()); + Assert.False(request.Headers.Contains("Cookie")); + Assert.False(request.Headers.Contains("Authorization")); + Assert.False(request.Headers.Contains("X-Admin-Key")); + Assert.False(request.Headers.Contains("X-Hop")); + received = await request.Content.ReadAsByteArrayAsync(ct); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; + }); + await IpfsGateway.Proxy(context, "http://127.0.0.1:5001/api/v0/add", clients); + Assert.Equal(bytes, received); + Assert.Equal("private, no-store", context.Response.Headers.CacheControl); + } + + [Fact] + public async Task StreamingApiAntiforgeryRejectsMissingHeaderBeforeInspectingMultipartBody() + { + var context = Context("POST", "/api/v0/add"); + context.Request.Headers.Origin = "https://admin.example"; + context.Request.ContentType = "multipart/form-data; boundary=example"; + using var body = new MemoryStream(Encoding.UTF8.GetBytes("unread multipart body")); + context.Request.Body = body; + Assert.False(await BrowserRequestSecurity.ValidateAsync(context, requireHeader: true)); + Assert.Equal(400, context.Response.StatusCode); + Assert.Equal(0, body.Position); + } + + [Fact] + public async Task InternalAdapterPassesOriginalContentAndCancellationWithoutPrebuffering() + { + var content = new DeferredContent(); + using var cts = new CancellationTokenSource(); + var clients = new Clients((request, token) => + { + Assert.Same(content, request.Content); + Assert.Equal(0, content.Serializations); + Assert.True(token.CanBeCanceled); + return Reply(200, "result"); + }); + using (var response = await ApiProxyEndpoints.SendProxyApiRequest("/api/v0/add", clients, new Keys(), content, ct: cts.Token)) + Assert.Equal("result", await response.Content.ReadAsStringAsync()); + Assert.False(content.Disposed); + content.Dispose(); + cts.Cancel(); + var cancelled = new Clients(async (_, token) => { await Task.Delay(Timeout.Infinite, token); return new HttpResponseMessage(); }); + await Assert.ThrowsAnyAsync(() => + ApiProxyEndpoints.SendProxyApiRequest("/api/v0/add", cancelled, new Keys(), ct: cts.Token)); + } + + [Fact] + public async Task MutableResponsesRevalidate_AndRewrittenHtmlKeepsStorageAndSupportedAssetPaths() + { + var context = Context(); + using (var upstream = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("asset") }) + { + upstream.Headers.CacheControl = new() { MaxAge = TimeSpan.FromDays(365) }; + await IpfsGateway.WriteResponseAsync(context, upstream); + } + Assert.Equal("no-cache, max-age=0, must-revalidate", context.Response.Headers.CacheControl); + context = Context(); + using (var notModified = new HttpResponseMessage(HttpStatusCode.NotModified)) + await IpfsGateway.WriteResponseAsync(context, notModified); + Assert.Equal("no-cache, max-age=0, must-revalidate", context.Response.Headers.CacheControl); + context = Context(); + using var html = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("", Encoding.UTF8, "text/html") + }; + html.Headers.ETag = new("\"old\""); + await IpfsGateway.WriteResponseAsync(context, html, rewriteIndexForCid: true, basePrefix: "/ipns/docs.example/"); + var output = Encoding.UTF8.GetString(((MemoryStream)context.Response.Body).ToArray()); + Assert.Contains("/ipns/docs.example/app.js", output); + Assert.Contains("/ipns/docs.example/manifest.json", output); + Assert.DoesNotContain("tgcid=", output); + Assert.DoesNotContain("tgipns=", output); + Assert.DoesNotContain("localStorage.clear", output); + Assert.DoesNotContain("indexedDB.deleteDatabase", output); + Assert.DoesNotContain("unregister(", output); + Assert.False(context.Response.Headers.ContainsKey("ETag")); + } + + [Fact] + public async Task HtmlRewriteRequestsAFullDocument_AndRejectsAnUnexpectedPartialResponse() + { + var context = Context("GET", "/ipfs/" + Cid + "/"); + context.Request.Headers.Range = "bytes=0-10"; + context.Request.Headers.IfRange = "etag"; + var clients = new Clients((request, _) => + { + Assert.False(request.Headers.Contains("Range")); + Assert.False(request.Headers.Contains("If-Range")); + var response = new HttpResponseMessage(HttpStatusCode.PartialContent) + { Content = new StringContent("", Encoding.UTF8, "text/html") }; + response.Content.Headers.ContentRange = new(0, 10, 100); + return Task.FromResult(response); + }); + Assert.False(await IpfsGateway.Proxy(context, "http://127.0.0.1:9010/ipfs/" + Cid, clients, + rewriteIndexForCid: true, basePrefix: "/ipfs/" + Cid + "/")); + Assert.Equal(502, context.Response.StatusCode); + Assert.False(context.Response.Headers.ContainsKey("Content-Range")); + } + + [Fact] + public async Task HeadOfRewrittenHtmlDoesNotAdvertiseTheOriginalRepresentation() + { + var context = Context("HEAD", "/ipfs/" + Cid + "/"); + using var response = new HttpResponseMessage(HttpStatusCode.OK) + { Content = new StringContent("", Encoding.UTF8, "text/html") }; + response.Headers.ETag = new("\"original\""); + response.Headers.AcceptRanges.Add("bytes"); + response.Content.Headers.ContentLength = 13; + await IpfsGateway.WriteResponseAsync(context, response, rewriteIndexForCid: true, basePrefix: "/ipfs/" + Cid + "/"); + Assert.False(context.Response.Headers.ContainsKey("ETag")); + Assert.False(context.Response.Headers.ContainsKey("Accept-Ranges")); + Assert.Null(context.Response.ContentLength); + Assert.Equal(0, context.Response.Body.Length); + } + + [Theory] + [InlineData("X-API-Key", "")] + [InlineData("Authorization", "Basic irrelevant")] + public async Task LegacyQueryCredentialIsStrippedEvenWhenAnUnrelatedHeaderExists(string header, string value) + { + var clients = new Clients((request, _) => + { + Assert.DoesNotContain("key=", request.RequestUri!.Query); + Assert.DoesNotContain(Keys.Value, request.RequestUri.Query); + return Reply(200); + }); + await using var host = await Host.Start(clients); + using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v0/id?key=" + Keys.Value); + request.Headers.TryAddWithoutValidation(header, value); + Assert.Equal(HttpStatusCode.OK, (await host.Client.SendAsync(request)).StatusCode); + } + + [Fact] + public async Task MappedGatewayDiscardsStaleResponseBeforeCommittingTheReplacement() + { + var reads = 0; + var requests = 0; + var clients = new Clients((request, _) => + { + var path = request.RequestUri!.AbsolutePath; + if (path.EndsWith("files/stat")) return Reply(200, "{\"Hash\":\"" + (++reads == 1 ? Cid : OtherCid) + "\"}", "application/json"); + if (path.EndsWith("pin/ls")) return Reply(200); + if (request.Method == HttpMethod.Head) return Reply(200); + requests++; + return Reply(requests == 1 ? 404 : 200, requests == 1 ? "STALE-BODY" : "CURRENT-BODY"); + }); + await using var host = await Host.Start(clients, mapped: true); + var response = await host.Client.GetAsync("https://site.example/asset.js"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("CURRENT-BODY", await response.Content.ReadAsStringAsync()); + Assert.Equal(2, requests); + Assert.Equal(2, reads); + Assert.Contains("must-revalidate", response.Headers.CacheControl!.ToString()); + } + + [Fact] + public async Task MappedDirectoryRedirectStaysAtSiteRoot_AndTrailingSlashDoesNotLoop() + { + var clients = new Clients((request, _) => + { + var path = request.RequestUri!.AbsolutePath; + if (path.EndsWith("files/stat")) return Reply(200, "{\"Hash\":\"" + Cid + "\"}", "application/json"); + if (path.EndsWith("pin/ls") || request.Method == HttpMethod.Head) return Reply(200); + if (path.EndsWith("/folder/")) return Reply(200, "directory"); + var response = new HttpResponseMessage(HttpStatusCode.MovedPermanently) { Content = new StringContent("") }; + response.Headers.Location = new Uri("http://127.0.0.1:9010/ipfs/" + Cid + "/folder/"); + return Task.FromResult(response); + }); + await using var host = await Host.Start(clients, mapped: true); + using var response = await host.Client.GetAsync("https://site.example/folder"); + Assert.Equal(HttpStatusCode.MovedPermanently, response.StatusCode); + Assert.Equal("/folder/", response.Headers.Location!.ToString()); + using var followed = await host.Client.GetAsync("https://site.example/folder/"); + Assert.Equal(HttpStatusCode.OK, followed.StatusCode); + Assert.Equal("directory", await followed.Content.ReadAsStringAsync()); + } + + [Theory] + [InlineData("/api/not-a-route?tgcid=" + Cid)] + [InlineData("/_framework/not-a-file?tgcid=" + Cid)] + [InlineData("/auth/not-a-route?tgipns=docs.example")] + public async Task ReservedLookingFallbackPathsRequireAuthentication(string path) + { + var clients = new Clients((_, _) => throw new InvalidOperationException("Anonymous request reached Kubo")); + await using var host = await Host.Start(clients); + var response = await host.Client.GetAsync(path); + Assert.True(response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Found); + } + + [Fact] + public async Task ArbitraryContentUsesSeparateOrigin_AndIpnsMarkerPreservesAssetsWithoutCredentials() + { + var clients = WebUiClients(); + await using var host = await Host.Start(clients, contentOrigin: "https://content.example"); + await host.SignIn(); + var response = await host.Get("/app.js?tgipns=docs.example&api_key=secret&key=secret&version=2"); + Assert.Equal(HttpStatusCode.Found, response.StatusCode); + Assert.Equal("https://content.example/ipns/docs.example/app.js?version=2", response.Headers.Location!.ToString()); + Assert.Equal("no-referrer", response.Headers.GetValues("Referrer-Policy").Single()); + response = await host.Get($"/ipfs/{OtherCid}/index.html"); + Assert.Equal("content.example", response.Headers.Location!.Host); + } + + [Fact] + public async Task RawContentFailsClosedUntilSeparateOriginConfigured_TrustedWebUiStillWorks() + { + await using var host = await Host.Start(WebUiClients()); + await host.SignIn(); + var response = await host.Get($"/ipfs/{OtherCid}/index.html"); + Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); + response = await host.Get("/webui"); + Assert.Equal($"/ipfs/{Cid}/", response.Headers.Location!.ToString()); + response = await host.Get($"/ipfs/{Cid}/"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var html = await response.Content.ReadAsStringAsync(); + Assert.Contains(BrowserRequestSecurity.HeaderName, html); + Assert.DoesNotContain("const token = null", html); + } + + [Fact] + public async Task CookieRpcRequiresSameOriginAndAntiforgery_ButExplicitValidKeyWorks() + { + await using var host = await Host.Start(new Clients((_, _) => Reply(200, "rpc-ok"))); + await host.SignIn(); + Assert.Equal(HttpStatusCode.Forbidden, (await host.Post("/api/v0/files/mkdir", "https://evil.example")).StatusCode); + Assert.Equal(HttpStatusCode.BadRequest, (await host.Post("/api/v0/files/mkdir", "https://admin.example")).StatusCode); + var csrf = await host.Get("/auth/csrf"); + using var doc = JsonDocument.Parse(await csrf.Content.ReadAsStringAsync()); + var token = doc.RootElement.GetProperty("token").GetString()!; + Assert.Equal(HttpStatusCode.OK, (await host.Post("/api/v0/files/mkdir", "https://admin.example", token)).StatusCode); + using var keyRequest = new HttpRequestMessage(HttpMethod.Post, "/api/v0/files/mkdir"); + keyRequest.Headers.Add("X-API-Key", Keys.Value); + Assert.Equal(HttpStatusCode.OK, (await host.Client.SendAsync(keyRequest)).StatusCode); + using var badKey = host.Request(HttpMethod.Post, "/api/v0/files/mkdir"); + badKey.Headers.Add("X-API-Key", "invalid"); + Assert.Equal(HttpStatusCode.Unauthorized, (await host.Client.SendAsync(badKey)).StatusCode); + } + + [Fact] + public async Task LoginRejectsCrossOrigin_AndPasswordChangeRevokesExistingCookie() + { + await using var host = await Host.Start(new Clients((_, _) => Reply(200))); + using var login = new HttpRequestMessage(HttpMethod.Post, "/auth/login") + { + Content = new FormUrlEncodedContent(new Dictionary { ["username"] = "alice", ["password"] = "test-password" }) + }; + login.Headers.Add("Origin", "https://evil.example"); + Assert.Equal(HttpStatusCode.Forbidden, (await host.Client.SendAsync(login)).StatusCode); + await host.SignIn(); + Assert.Equal(HttpStatusCode.OK, (await host.Get("/private")).StatusCode); + host.Config.Value.Users.Single(x => x.UserName == "alice").PasswordHashed = StringHasher.HashString("changed-password"); + var response = await host.Get("/private"); + Assert.True(response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Found); + } + + [Fact] + public async Task MappedContentHostCannotReachManagementRpcOrAuthentication() + { + await using var host = await Host.Start(new Clients((_, _) => throw new InvalidOperationException("Reached Kubo")), mapped: true); + foreach (var path in new[] { "/auth/csrf", "/api/v0/id", "/_blazor/negotiate", "/webui" }) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "https://site.example" + path); + request.Headers.Add("X-API-Key", Keys.Value); + Assert.Equal(HttpStatusCode.NotFound, (await host.Client.SendAsync(request)).StatusCode); + } + } + + [Fact] + public void SessionVersionRejectsDeletedOrRecreatedAccount_AndIdentifiersRejectUrlInjection() + { + var config = new TestConfig(); + var user = config.Value.Users.Single(x => x.UserName == "alice"); + var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.UserName), new Claim(UserSessionValidator.StampClaim, UserSessionValidator.Stamp(user)) }, "test")); + Assert.True(UserSessionValidator.IsCurrent(principal, config)); + config.Value.Users.Remove(user); + Assert.False(UserSessionValidator.IsCurrent(principal, config)); + config.Value.Users.Add(new UserAccount { UserName = "alice", PasswordHashed = user.PasswordHashed }); + Assert.False(UserSessionValidator.IsCurrent(principal, config)); + Assert.True(ContentIdentifier.IsCid(Cid)); + Assert.True(ContentIdentifier.IsIpnsName("docs.example")); + foreach (var bad in new[] { "baf-fake", "Qm../../api", "https://host", "host?arg=x", "user@host.example" }) + { + Assert.False(ContentIdentifier.IsCid(bad)); + Assert.False(ContentIdentifier.IsIpnsName(bad)); + } + foreach (var bad in new[] { "../id", "%2e%2e/id", "%2fapi/v0", "dir\\file", "file?arg=x" }) Assert.False(ContentIdentifier.IsSafePath(bad)); + } + + private static DefaultHttpContext Context(string method = "GET", string path = "/asset.js") + { + var context = new DefaultHttpContext(); + context.Request.Method = method; context.Request.Path = path; + context.Request.Scheme = "https"; context.Request.Host = new HostString("admin.example"); + context.Response.Body = new MemoryStream(); + return context; + } + private static Task Reply(int status, string body = "", string type = "text/plain") => + Task.FromResult(new HttpResponseMessage((HttpStatusCode)status) { Content = new StringContent(body, Encoding.UTF8, type) }); + private static Clients WebUiClients() => new((request, _) => + { + if (request.RequestUri!.AbsolutePath == "/webui/") + { + var response = new HttpResponseMessage(HttpStatusCode.Found) { Content = new StringContent("") }; + response.Headers.Location = new Uri($"/ipfs/{Cid}/", UriKind.Relative); + return Task.FromResult(response); + } + return Reply(200, "trusted UI", "text/html"); + }); + + private sealed class Clients(Func> send) : IHttpClientFactory + { + public HttpClient CreateClient(string name) => new(new Handler(send)); + } + private sealed class Handler(Func> send) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => send(request, cancellationToken); + } + private sealed class Keys : IApiKeyProvider + { + public const string Value = "test-administrative-key"; + public string GetCurrentKey() => Value; + public bool IsValid(string? key) => key == Value; + public DateTimeOffset CreatedAt => DateTimeOffset.MinValue; + public DateTimeOffset ExpiresAt => DateTimeOffset.MaxValue; + } + private sealed class TestConfig : IConfigService + { + public Config Value = new() { Users = [new UserAccount { UserName = "alice", PasswordHashed = StringHasher.HashString("test-password") }] }; + public Config Get() => Value; + public string ConfigPath => "/unused/config.json"; + public Task SaveAsync(Config config, CancellationToken ct = default) { Value = config; return Task.CompletedTask; } + public Task UpdateAsync(Action update, CancellationToken ct = default) { update(Value); return Task.CompletedTask; } + } + // The rate limiter has its own SQLite/middleware integration suite; these tests isolate gateway boundaries. + public class NoopRate : System.Reflection.DispatchProxy + { + protected override object? Invoke(System.Reflection.MethodInfo? method, object?[]? args) => method!.ReturnType == typeof(Task) + ? Task.CompletedTask : throw new NotSupportedException(method.Name); + } + private sealed class Host(WebApplication app, HttpClient client, TestConfig config) : IAsyncDisposable + { + public HttpClient Client => client; + public TestConfig Config => config; + private readonly CookieContainer _cookies = new(); + public static async Task Start(Clients clients, bool mapped = false, string? contentOrigin = null) + { + var builder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = "Testing" }); + builder.WebHost.UseTestServer(); + if (contentOrigin is not null) builder.Configuration["Gateway:ContentGatewayOrigin"] = contentOrigin; + builder.Services.AddTruthGateCore(builder.Configuration); + var config = new TestConfig(); + if (mapped) config.Value.Domains.Add(new EdgeDomain { Domain = "site.example", SiteFolderLeaf = "site.example" }); + builder.Services.AddSingleton(config); + builder.Services.AddSingleton(new Keys()); + builder.Services.AddSingleton(System.Reflection.DispatchProxy.Create()); + builder.Services.AddSingleton(clients); + var app = builder.Build(); + app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseApiKeyAuthentication(); + app.UseManagementBoundary(); app.UseDomainGateway(); app.UseAuthorization(); app.UseAntiforgery(); app.UseNonMappedDomainAuthGuard(); + app.MapGet("/login", (HttpContext ctx, IAntiforgery af) => Results.Json(new { token = af.GetAndStoreTokens(ctx).RequestToken })).AllowAnonymous(); + app.MapGet("/private", () => Results.Ok()).RequireAuthorization(); + app.MapTruthGateAuthEndpoints(); app.MapTruthGateApiProxyEndpoints(); app.MapTruthGateIpfsEndpoints(); + await app.StartAsync(); + var client = app.GetTestClient(); client.BaseAddress = new Uri("https://admin.example"); + return new Host(app, client, config); + } + public HttpRequestMessage Request(HttpMethod method, string path) + { + var request = new HttpRequestMessage(method, path); + var cookies = _cookies.GetCookieHeader(new Uri(Client.BaseAddress!, path)); + if (cookies.Length > 0) request.Headers.Add("Cookie", cookies); + return request; + } + private void Remember(HttpResponseMessage response) + { + if (response.Headers.TryGetValues("Set-Cookie", out var headers)) + foreach (var cookie in headers) _cookies.SetCookies(Client.BaseAddress!, cookie); + } + public async Task Get(string path) + { + using var request = Request(HttpMethod.Get, path); + var response = await Client.SendAsync(request); Remember(response); return response; + } + public async Task Post(string path, string origin, string? token = null) + { + using var request = Request(HttpMethod.Post, path); + request.Headers.Add("Origin", origin); + if (token is not null) request.Headers.Add(BrowserRequestSecurity.HeaderName, token); + var response = await Client.SendAsync(request); Remember(response); return response; + } + public async Task SignIn() + { + using var seed = await Get("/login"); + using var json = JsonDocument.Parse(await seed.Content.ReadAsStringAsync()); + using var request = Request(HttpMethod.Post, "/auth/login"); + request.Headers.Add("Origin", Client.BaseAddress!.GetLeftPart(UriPartial.Authority)); + request.Content = new FormUrlEncodedContent(new Dictionary + { + ["username"] = "alice", ["password"] = "test-password", ["__RequestVerificationToken"] = json.RootElement.GetProperty("token").GetString()! + }); + using var response = await Client.SendAsync(request); Remember(response); + Assert.Equal(HttpStatusCode.Found, response.StatusCode); + Assert.Equal("/", response.Headers.Location!.ToString()); + } + public async ValueTask DisposeAsync() { Client.Dispose(); await app.DisposeAsync(); } + } + private sealed class NonSeekableReadStream(byte[] bytes) : MemoryStream(bytes) + { + public override bool CanSeek => false; + public override long Length => throw new NotSupportedException(); + } + private sealed class DeferredContent : HttpContent + { + public int Serializations; public bool Disposed; + protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) { Serializations++; return stream.WriteAsync(new byte[] { 1, 2, 3 }).AsTask(); } + protected override bool TryComputeLength(out long length) { length = 0; return false; } + protected override void Dispose(bool disposing) { Disposed = true; base.Dispose(disposing); } + } +} diff --git a/Test.TruthGate/Tests/Ipv6GraylistTests.cs b/Test.TruthGate/Tests/Ipv6GraylistTests.cs index a7febca..4a9636e 100644 --- a/Test.TruthGate/Tests/Ipv6GraylistTests.cs +++ b/Test.TruthGate/Tests/Ipv6GraylistTests.cs @@ -1,47 +1,21 @@ -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; using System.Net; -using System.Text; -using System.Threading.Tasks; -using TruthGate_Web.Security; using TruthGate_Web.Services; -namespace Test.TruthGate.Tests -{ +namespace Test.TruthGate.Tests; - [Collection("TruthGateServerCollection")] - public sealed class Ipv6GraylistTests : IAsyncLifetime +[Collection("TruthGateServerCollection")] +public sealed class Ipv6GraylistTests(SqliteTestFixture fixture) +{ + [Fact] + public async Task ManualPrefixBan_Applies_To_All_Addresses_In_That_Prefix() { - private readonly TruthGateWebApplicationFactory _f; - private readonly TestClient _client; - - public Ipv6GraylistTests(SqliteTestFixture fx) - { - _f = new TruthGateWebApplicationFactory(fx); - _client = new TestClient(_f.CreateClient()); - } - - public Task InitializeAsync() => Task.CompletedTask; - public Task DisposeAsync() { _f.Dispose(); return Task.CompletedTask; } - - [Fact(Skip = "Automatic /64 aggregation not present; test demonstrates manual prefix ban application")] - public async Task ManualPrefixBan_Applies_To_All_In_Prefix() - { - // Example of how to add a prefix ban via reflection if you need to validate behavior now - var ipv6a = "2001:db8:1:2::1"; var ipv6b = "2001:db8:1:2::2"; - using var scope = _f.Services.CreateScope(); - var rl = (RateLimiterService)scope.ServiceProvider.GetRequiredService(); - var dbf = (IDbContextFactory)typeof(RateLimiterService).GetProperty("DbFactory", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(rl)!; - await using var db = await dbf.CreateDbContextAsync(); - var prefix = "2001:db8:1:2::/64"; - var addBan = typeof(RateLimiterService).GetMethod("AddBanAsync", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!; - await (Task)addBan.Invoke(rl, new object?[] { db, new Ban { IpV6Prefix = prefix, Scope = RateScope.Gateway, Type = BanType.True, IsTrueBan = true, ReasonCode = "TEST", CreatedUtc = DateTimeOffset.UtcNow, ExpiresUtc = DateTimeOffset.UtcNow.AddHours(1) }, false })!; - // Requests from any IP in /64 should now be 403 - Assert.Equal(HttpStatusCode.Forbidden, (await _client.SendAsync("/ipfs/cat", ipv6: ipv6a)).StatusCode); - Assert.Equal(HttpStatusCode.Forbidden, (await _client.SendAsync("/ipfs/cat", ipv6: ipv6b)).StatusCode); - } + using var server = new TruthGateWebApplicationFactory(fixture); + var service = server.Services.GetRequiredService(); + var client = new TestClient(server.CreateClient()); + Assert.True(await service.BanIpv6PrefixAsync("2001:db8:1:2::/64", TimeSpan.FromHours(1))); + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync("/ipfs/cat", ipv6: "2001:db8:1:2::1")).StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync("/ipfs/cat", ipv6: "2001:db8:1:2::2")).StatusCode); + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync("/ipfs/cat", ipv6: "2001:db8:1:3::1")).StatusCode); } } diff --git a/Test.TruthGate/Tests/PersistenceWriteBehindTests.cs b/Test.TruthGate/Tests/PersistenceWriteBehindTests.cs index c740495..c9a4cce 100644 --- a/Test.TruthGate/Tests/PersistenceWriteBehindTests.cs +++ b/Test.TruthGate/Tests/PersistenceWriteBehindTests.cs @@ -1,64 +1,37 @@ -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; using System.Net; -using System.Text; -using System.Threading.Tasks; using TruthGate_Web.Security; -namespace Test.TruthGate.Tests -{ +namespace Test.TruthGate.Tests; - [Collection("TruthGateServerCollection")] - public sealed class PersistenceWriteBehindTests : IAsyncLifetime +[Collection("TruthGateServerCollection")] +public sealed class PersistenceWriteBehindTests(SqliteTestFixture fixture) +{ + [Fact] + public async Task Flush_Persists_Counters() { - private TruthGateWebApplicationFactory _f; - private readonly SqliteTestFixture _fx; - private TestClient _client; - - public PersistenceWriteBehindTests(SqliteTestFixture fx) - { - _fx = fx; - _f = new TruthGateWebApplicationFactory(fx); - _client = new TestClient(_f.CreateClient()); - } - - public Task InitializeAsync() => Task.CompletedTask; - public Task DisposeAsync() { _f.Dispose(); return Task.CompletedTask; } - - [Fact] - public async Task Flush_Persists_Counters() - { - var ip = "203.0.113.77"; - // Generate a bit of public traffic - for (int i = 0; i < 3; i++) await _client.SendAsync("/public/ping", ip: ip); - await _client.FlushAsync(); - // Inspect DB directly - using var scope = _f.Services.CreateScope(); - var dbf = scope.ServiceProvider.GetRequiredService>(); - await using var db = await dbf.CreateDbContextAsync(); - var nowBucket = DateTimeOffset.UtcNow.ToString("yyyyMMddHHmm"); - var row = await db.IpMinuteCounters.FirstOrDefaultAsync(x => x.Ip == ip && x.MinuteBucket == nowBucket); - Assert.NotNull(row); - Assert.True(row!.PublicCalls >= 3); - } + using var server = new TruthGateWebApplicationFactory(fixture); + var client = new TestClient(server.CreateClient()); + for (var i = 0; i < 3; i++) await client.SendAsync("/public/ping", "192.0.2.47"); + await client.FlushAsync(); + await using var db = server.Services.GetRequiredService>().CreateDbContext(); + Assert.Equal(3, await db.IpMinuteCounters.Where(x => x.Ip == "192.0.2.47").SumAsync(x => x.PublicCalls)); + } - [Fact(Skip = "Bans are not reloaded from DB on startup in current limiter")] - public async Task Ban_Persists_And_Is_Enforced_After_Restart() + [Fact] + public async Task Ban_Persists_And_Is_Enforced_After_Restart() + { + string databasePath; + using (var server = new TruthGateWebApplicationFactory(fixture)) { - var ip = "198.51.100.200"; - for (int i = 0; i < 25; i++) await _client.SendAsync("/ipfs/cat", ip: ip); - Assert.Equal(HttpStatusCode.Forbidden, (await _client.SendAsync("/ipfs/cat", ip: ip)).StatusCode); - // restart server - _f.Dispose(); - _f = new TruthGateWebApplicationFactory(_fx); - _client = new TestClient(_f.CreateClient()); - // Currently: caches are empty after restart, so this would pass (OK) - var r = await _client.SendAsync("/ipfs/cat", ip: ip); - Assert.Equal(HttpStatusCode.Forbidden, r.StatusCode); + databasePath = server.DatabasePath; + var client = new TestClient(server.CreateClient()); + for (var i = 0; i < 24; i++) Assert.Equal(HttpStatusCode.OK, (await client.SendAsync("/ipfs/cat", "192.0.2.48")).StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync("/ipfs/cat", "192.0.2.48")).StatusCode); } + using var restarted = new TruthGateWebApplicationFactory(fixture, databasePath); + var restartedClient = new TestClient(restarted.CreateClient()); + Assert.Equal(HttpStatusCode.Forbidden, (await restartedClient.SendAsync("/ipfs/cat", "192.0.2.48")).StatusCode); } - } diff --git a/Test.TruthGate/Tests/PublicLimitedTests.cs b/Test.TruthGate/Tests/PublicLimitedTests.cs index 8709ee3..a3fa951 100644 --- a/Test.TruthGate/Tests/PublicLimitedTests.cs +++ b/Test.TruthGate/Tests/PublicLimitedTests.cs @@ -1,88 +1,31 @@ -using System; -using System.Collections.Generic; -using System.Linq; using System.Net; -using System.Text; -using System.Threading.Tasks; -namespace Test.TruthGate.Tests -{ +namespace Test.TruthGate.Tests; - [Collection("TruthGateServerCollection")] - public sealed class PublicLimitedTests : IAsyncLifetime +[Collection("TruthGateServerCollection")] +public sealed class PublicLimitedTests(SqliteTestFixture fixture) +{ + [Fact] + public async Task Exceed_PerMinute_Triggers_429_And_Then_The_Soft_Ban() { - private readonly TruthGateWebApplicationFactory _f; - private readonly TestClient _client; - - public PublicLimitedTests(SqliteTestFixture fx) - { - _f = new TruthGateWebApplicationFactory(fx); - _client = new TestClient(_f.CreateClient()); - } - - public Task InitializeAsync() => Task.CompletedTask; - public Task DisposeAsync() { _f.Dispose(); return Task.CompletedTask; } - - /* [Fact] - public async Task Exceed_PerMinute_Triggers_429() - { - var ip = "10.0.0.1"; - // Per test config: 6/min → send 7 - for (int i = 0; i < 300; i++) - { - var ok = await _client.SendAsync("/public/ping", ip: ip); - Assert.Equal(HttpStatusCode.OK, ok.StatusCode); - } - HttpResponseMessage? r = null; - - for (int i = 0; i < 4000; i++) - { - r = await _client.SendAsync("/public/ping", ip: ip); - } - Assert.Equal((HttpStatusCode)429, r.StatusCode); - Assert.True(r.Headers.TryGetValues("Retry-After", out var vals)); - }*/ - - [Fact] - public async Task Tier_Tightens_When_Global_Load_High() - { - // Cross threshold 10 by generating global calls from other IPs - for (int i = 0; i < 10000; i++) - { - // Start at 10.0.99.1 and increment across octets - int a = 10; - int b = 0; - int c = 99 + (i / 255); // roll into next octet after 255 - int d = (i % 255) + 1; // 1–255 range - - // Wrap c if it goes over 255 (you can also expand into 'b' if needed) - if (c > 255) - { - b += (c / 256); - c = c % 256; - } - - var ipOther = $"{a}.{b}.{c}.{d}"; - await _client.SendAsync("/public/ping", ip: ipOther); - } - - // For this IP, per-minute should now be 4 (scaled). Send 5 → last should 429 - var ip = "10.0.0.2"; - for (int i = 0; i < 4; i++) - { - var ok = await _client.SendAsync("/public/ping", ip: ip); - Assert.Equal(HttpStatusCode.OK, ok.StatusCode); - } - - HttpResponseMessage? r = null; - for (int i = 0; i < 30; i++) - { - r = await _client.SendAsync("/public/ping", ip: ip); - } - Assert.Equal(HttpStatusCode.Forbidden, r.StatusCode); - } + using var server = new TruthGateWebApplicationFactory(fixture, configure: options => options.Public.GlobalTiers = []); + var client = new TestClient(server.CreateClient()); + for (var i = 0; i < 6; i++) Assert.Equal(HttpStatusCode.OK, (await client.SendAsync("/public/ping", "192.0.2.45")).StatusCode); + using var denied = await client.SendAsync("/public/ping", "192.0.2.45"); + Assert.Equal(HttpStatusCode.TooManyRequests, denied.StatusCode); + Assert.Equal(TimeSpan.FromSeconds(60), denied.Headers.RetryAfter!.Delta); + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync("/public/ping", "192.0.2.45")).StatusCode); + } - [Fact(Skip = "Public 4x/10x escalation not implemented in current limiter")] - public Task Escalation_During_SoftBan() => Task.CompletedTask; + [Fact] + public async Task Tier_Tightens_When_Global_Load_High_And_Persists_Across_Flush() + { + using var server = new TruthGateWebApplicationFactory(fixture); + var client = new TestClient(server.CreateClient()); + for (var i = 1; i <= 10; i++) + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync("/public/ping", $"198.51.100.{i}")).StatusCode); + await client.FlushAsync(); + for (var i = 0; i < 4; i++) Assert.Equal(HttpStatusCode.OK, (await client.SendAsync("/public/ping", "192.0.2.46")).StatusCode); + Assert.Equal(HttpStatusCode.TooManyRequests, (await client.SendAsync("/public/ping", "192.0.2.46")).StatusCode); } } diff --git a/Test.TruthGate/Tests/RateLimiterLifecycleTests.cs b/Test.TruthGate/Tests/RateLimiterLifecycleTests.cs new file mode 100644 index 0000000..f9691d7 --- /dev/null +++ b/Test.TruthGate/Tests/RateLimiterLifecycleTests.cs @@ -0,0 +1,365 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using System.Net; +using TruthGate_Web.Security; +using TruthGate_Web.Services; +using TruthGate_Web.Utils; + +namespace Test.TruthGate.Tests; + +public sealed class RateLimiterLifecycleTests +{ + [Fact] + public async Task Successful_flush_preserves_live_windows_and_does_not_persist_twice() + { + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + for (var i = 0; i < 12; i++) Assert.True(limiter.TryAcquireGateway("192.0.2.10", store.Clock.GetUtcNow(), 10, 2)); + Assert.Equal((12, 2), limiter.GetGatewayUsage("192.0.2.10", store.Clock.GetUtcNow(), 10)); + await limiter.FlushAsync(); + await limiter.FlushAsync(); + Assert.Equal((12, 2), limiter.GetGatewayUsage("192.0.2.10", store.Clock.GetUtcNow(), 10)); + Assert.Equal(12, limiter.GetGlobalLastHourTotal(store.Clock.GetUtcNow())); + Assert.False(limiter.TryAcquireGateway("192.0.2.10", store.Clock.GetUtcNow(), 10, 2)); + await using var db = store.Factory.CreateDbContext(); + var row = await db.IpMinuteCounters.SingleAsync(); + Assert.Equal(12, row.GatewayCalls); + Assert.Equal(2, row.GatewayOverageUsed); + Assert.Equal(12, (await db.GlobalMinuteCounters.SingleAsync()).TotalCalls); + + var restarted = await store.NewServiceAsync(); + Assert.Equal((12, 2), restarted.GetGatewayUsage("::ffff:192.0.2.10", store.Clock.GetUtcNow(), 10)); + Assert.False(restarted.TryAcquireGateway("192.0.2.10", store.Clock.GetUtcNow(), 10, 2)); + } + + [Fact] + public async Task Failed_flush_keeps_pending_usage_until_recovery() + { + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + for (var i = 0; i < 3; i++) await limiter.RecordFailureAsync(Request("192.0.2.11")); + store.Interceptor.FailNext = true; + await limiter.FlushAsync(); + Assert.Equal(3, limiter.GetGlobalLastHourTotal(store.Clock.GetUtcNow())); + await using (var db = store.Factory.CreateDbContext()) Assert.Empty(await db.IpMinuteCounters.ToListAsync()); + await limiter.FlushAsync(); + await limiter.FlushAsync(); + await using (var db = store.Factory.CreateDbContext()) Assert.Equal(3, (await db.IpMinuteCounters.SingleAsync()).PublicCalls); + for (var i = 0; i < 3; i++) Assert.True(limiter.TryAcquirePublic("192.0.2.11", store.Clock.GetUtcNow())); + Assert.False(limiter.TryAcquirePublic("192.0.2.11", store.Clock.GetUtcNow())); + } + + [Fact] + public async Task Concurrent_increments_during_a_flush_are_neither_lost_nor_duplicated() + { + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + for (var i = 0; i < 4; i++) Assert.True(limiter.TryAcquireGateway("192.0.2.12", store.Clock.GetUtcNow(), 100, 100)); + store.Interceptor.PauseNext = true; + var firstFlush = limiter.FlushAsync(); + await store.Interceptor.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + Parallel.For(0, 24, _ => Assert.True(limiter.TryAcquireGateway("192.0.2.12", store.Clock.GetUtcNow(), 100, 100))); + store.Interceptor.Release.TrySetResult(); + await firstFlush; + await Task.WhenAll(limiter.FlushAsync(), limiter.FlushAsync()); + Assert.Equal((28, 0), limiter.GetGatewayUsage("192.0.2.12", store.Clock.GetUtcNow(), 100)); + await using var db = store.Factory.CreateDbContext(); + Assert.Equal(28, (await db.IpMinuteCounters.SingleAsync()).GatewayCalls); + Assert.Equal(28, (await db.GlobalMinuteCounters.SingleAsync()).TotalCalls); + } + + [Fact] + public async Task Concurrent_admission_respects_the_exact_gateway_and_public_allowances() + { + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + var gatewayAllowed = 0; + Parallel.For(0, 32, _ => + { + if (limiter.TryAcquireGateway("192.0.2.13", store.Clock.GetUtcNow(), 4, 8)) Interlocked.Increment(ref gatewayAllowed); + }); + Assert.Equal(12, gatewayAllowed); + Assert.Equal((12, 8), limiter.GetGatewayUsage("192.0.2.13", store.Clock.GetUtcNow(), 4)); + var publicAllowed = 0; + Parallel.For(0, 24, _ => + { + if (limiter.TryAcquirePublic("192.0.2.14", store.Clock.GetUtcNow())) Interlocked.Increment(ref publicAllowed); + }); + Assert.Equal(6, publicAllowed); + await limiter.FlushAsync(); + Assert.False(limiter.TryAcquireGateway("192.0.2.13", store.Clock.GetUtcNow(), 4, 8)); + Assert.False(limiter.TryAcquirePublic("192.0.2.14", store.Clock.GetUtcNow())); + } + + [Fact] + public async Task Overage_is_consumed_once_and_expires_after_the_rolling_hour() + { + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + for (var i = 0; i < 5; i++) Assert.True(limiter.TryAcquireGateway("192.0.2.15", store.Clock.GetUtcNow(), 2, 3)); + Assert.False(limiter.TryAcquireGateway("192.0.2.15", store.Clock.GetUtcNow(), 2, 3)); + await limiter.FlushAsync(); + store.Clock.Advance(TimeSpan.FromMinutes(1)); + Assert.True(limiter.TryAcquireGateway("192.0.2.15", store.Clock.GetUtcNow(), 2, 3)); + Assert.True(limiter.TryAcquireGateway("192.0.2.15", store.Clock.GetUtcNow(), 2, 3)); + Assert.False(limiter.TryAcquireGateway("192.0.2.15", store.Clock.GetUtcNow(), 2, 3)); + store.Clock.Advance(TimeSpan.FromMinutes(59)); + for (var i = 0; i < 5; i++) Assert.True(limiter.TryAcquireGateway("192.0.2.15", store.Clock.GetUtcNow(), 2, 3)); + Assert.False(limiter.TryAcquireGateway("192.0.2.15", store.Clock.GetUtcNow(), 2, 3)); + } + + [Fact] + public async Task Bad_key_history_spans_unflushed_minutes_and_is_not_double_counted_after_flush() + { + await using var store = await LimiterStore.CreateAsync(); + store.Options.Admin.MaxBadKeyPerIpPer24h = 3; + var limiter = await store.NewServiceAsync(); + var firstRequest = Request("192.0.2.16"); + await limiter.RecordFailureAsync(firstRequest, "invalid", true); + await limiter.RecordFailureAsync(firstRequest, "invalid", true); + await limiter.FlushAsync(); + Assert.Equal(1, limiter.GetAdminBadKeyCalls("192.0.2.16", store.Clock.GetUtcNow())); + store.Clock.Advance(TimeSpan.FromMinutes(1)); + await limiter.RecordFailureAsync(Request("192.0.2.16"), "invalid", true); + Assert.False(limiter.IsBanned("192.0.2.16")); + store.Clock.Advance(TimeSpan.FromMinutes(1)); + await limiter.RecordFailureAsync(Request("192.0.2.16"), "invalid", true); + Assert.Equal(3, limiter.GetAdminBadKeyCalls("192.0.2.16", store.Clock.GetUtcNow())); + Assert.True(limiter.IsBanned("192.0.2.16")); + await limiter.FlushAsync(); + var restarted = await store.NewServiceAsync(); + Assert.True(restarted.IsBanned("192.0.2.16")); + Assert.Equal(3, restarted.GetAdminBadKeyCalls("192.0.2.16", store.Clock.GetUtcNow())); + } + + [Fact] + public async Task Active_bans_and_whitelists_are_restored_with_the_same_decisions() + { + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + await limiter.BanIpAsync("2001:db8::10", TimeSpan.FromHours(1)); + await limiter.AddWhitelistIpAsync("192.0.2.17", expiresUtc: store.Clock.GetUtcNow().AddHours(1)); + await limiter.BanIpv6PrefixAsync("2001:db8:1:2::99/64", TimeSpan.FromHours(1)); + await limiter.AddWhitelistIpv6PrefixAsync("2001:db8:3:4::/64"); + var restarted = await store.NewServiceAsync(); + Assert.True(restarted.IsBanned("2001:db8::10")); + Assert.True(restarted.IsBanned("2001:db8:1:2::1234")); + Assert.True(await restarted.IsWhitelistedAsync("::ffff:192.0.2.17")); + Assert.True(await restarted.IsWhitelistedPrefixAsync("2001:db8:3:4::ffff/64")); + } + + [Fact] + public async Task Whitelist_expiry_is_enforced_during_lookup_and_after_restart() + { + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + await limiter.BanIpAsync("192.0.2.18", TimeSpan.FromHours(2)); + await limiter.AddWhitelistIpAsync("192.0.2.18", expiresUtc: store.Clock.GetUtcNow().AddMinutes(1)); + await limiter.AddWhitelistIpv6PrefixAsync("2001:db8:5:6::/64", expiresUtc: store.Clock.GetUtcNow().AddMinutes(-1)); + Assert.False(limiter.IsBanned("192.0.2.18")); + Assert.False(await limiter.IsWhitelistedPrefixAsync("2001:db8:5:6::/64")); + store.Clock.Advance(TimeSpan.FromMinutes(1)); + Assert.False(await limiter.IsWhitelistedAsync("192.0.2.18")); + Assert.True(limiter.IsBanned("192.0.2.18")); + var restarted = await store.NewServiceAsync(); + Assert.False(await restarted.IsWhitelistedAsync("192.0.2.18")); + Assert.True(restarted.IsBanned("192.0.2.18")); + } + + [Fact] + public async Task Plain_and_mapped_IPv4_share_policy_and_whitelist_upserts() + { + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + await limiter.BanIpAsync("192.0.2.19", TimeSpan.FromHours(1)); + Assert.True(limiter.IsBanned("192.0.2.19")); + Assert.True(limiter.IsBanned("::ffff:192.0.2.19")); + Assert.True(await limiter.UnbanIpAsync("::ffff:192.0.2.19")); + Assert.False(limiter.IsBanned("192.0.2.19")); + await limiter.AddWhitelistIpAsync("::ffff:192.0.2.19"); + await limiter.AddWhitelistIpAsync("192.0.2.19", reason: "updated"); + await using (var db = store.Factory.CreateDbContext()) + { + var whitelist = await db.Whitelists.SingleAsync(); + Assert.Equal("192.0.2.19", whitelist.Ip); + Assert.Equal("updated", whitelist.Reason); + } + Assert.True(await limiter.RemoveWhitelistIpAsync("::ffff:192.0.2.19")); + Assert.False(await limiter.IsWhitelistedAsync("192.0.2.19")); + Assert.False(await limiter.BanIpv6PrefixAsync("::ffff:192.0.2.19/64", TimeSpan.FromHours(1))); + Assert.False(await limiter.AddWhitelistIpv6PrefixAsync("2001:db8::/48")); + } + + [Fact] + public async Task Legacy_mapped_policy_rows_are_hydrated_and_removable() + { + await using var store = await LimiterStore.CreateAsync(); + await using (var db = store.Factory.CreateDbContext()) + { + db.Bans.Add(new Ban { Ip = "::ffff:192.0.2.20", CreatedUtc = store.Clock.GetUtcNow(), ExpiresUtc = store.Clock.GetUtcNow().AddHours(1) }); + db.Whitelists.Add(new Whitelist { Ip = "::ffff:192.0.2.21", CreatedUtc = store.Clock.GetUtcNow() }); + await db.SaveChangesAsync(); + } + var limiter = await store.NewServiceAsync(); + Assert.True(limiter.IsBanned("192.0.2.20")); + Assert.True(await limiter.IsWhitelistedAsync("192.0.2.21")); + Assert.True(await limiter.UnbanIpAsync("192.0.2.20")); + Assert.True(await limiter.RemoveWhitelistIpAsync("192.0.2.21")); + } + + [Fact] + public async Task Removing_one_ban_preserves_other_active_bans_for_the_address() + { + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + await limiter.BanIpAsync("192.0.2.22", TimeSpan.FromHours(1)); + await limiter.BanIpAsync("192.0.2.22", TimeSpan.FromHours(2)); + var (bans, _) = await limiter.GetBansAsync(1, 10); + Assert.True(await limiter.UnbanByIdAsync(bans.Single(x => x.ExpiresUtc == store.Clock.GetUtcNow().AddHours(2)).Id)); + Assert.True(limiter.IsBanned("192.0.2.22")); + store.Clock.Advance(TimeSpan.FromHours(1)); + Assert.False(limiter.IsBanned("192.0.2.22")); + } + + [Fact] + public async Task Purge_removes_only_expired_policy_and_preserves_future_and_permanent_rows() + { + await using var store = await LimiterStore.CreateAsync(); + store.Options.Retention.PurgeExpiredBanAfterDays = 0; + var now = store.Clock.GetUtcNow(); + await using (var db = store.Factory.CreateDbContext()) + { + db.Bans.AddRange(new Ban { Ip = "192.0.2.23", CreatedUtc = now, ExpiresUtc = now.AddHours(-1) }, + new Ban { Ip = "192.0.2.24", CreatedUtc = now, ExpiresUtc = now.AddYears(3) }); + db.Whitelists.AddRange(new Whitelist { Ip = "192.0.2.25", CreatedUtc = now, ExpiresUtc = now.AddHours(-1) }, + new Whitelist { Ip = "192.0.2.26", CreatedUtc = now, ExpiresUtc = now.AddYears(3) }, + new Whitelist { Ip = "192.0.2.27", CreatedUtc = now }); + db.GracePairs.AddRange(new GracePair { Ip = "192.0.2.28", KeyHash = "expired", ExpiresUtc = now.AddHours(-1) }, + new GracePair { Ip = "192.0.2.28", KeyHash = "future", ExpiresUtc = now.AddYears(3) }); + await db.SaveChangesAsync(); + } + var worker = new RateLimiterPurgeWorker(store.Factory, Options.Create(store.Options), + NullLogger.Instance, store.Clock); + await worker.PurgeOnceAsync(); + await using var check = store.Factory.CreateDbContext(); + Assert.Equal("192.0.2.24", (await check.Bans.SingleAsync()).Ip); + Assert.Equal(new[] { "192.0.2.26", "192.0.2.27" }, await check.Whitelists.OrderBy(x => x.Ip).Select(x => x.Ip).ToArrayAsync()); + Assert.Equal("future", (await check.GracePairs.SingleAsync()).KeyHash); + } + + [Fact] + public async Task Expired_clean_windows_are_evicted_but_failed_deltas_remain_retryable() + { + await using var store = await LimiterStore.CreateAsync(); + var limiter = await store.NewServiceAsync(); + Assert.True(limiter.TryAcquireGateway("192.0.2.29", store.Clock.GetUtcNow(), 10, 10)); + await limiter.FlushAsync(); + store.Clock.Advance(TimeSpan.FromHours(2)); + await limiter.FlushAsync(); + Assert.Equal(0, limiter.GetGlobalLastHourTotal(store.Clock.GetUtcNow())); + Assert.Equal(0, CounterBucketCount(limiter)); + Assert.True(limiter.TryAcquireGateway("192.0.2.29", store.Clock.GetUtcNow(), 10, 10)); + store.Interceptor.FailNext = true; + await limiter.FlushAsync(); + store.Clock.Advance(TimeSpan.FromHours(2)); + await limiter.FlushAsync(); + Assert.Equal(0, CounterBucketCount(limiter)); + await using var db = store.Factory.CreateDbContext(); + Assert.Equal(2, await db.IpMinuteCounters.SumAsync(x => x.GatewayCalls)); + } + + private static int CounterBucketCount(RateLimiterService limiter) + { + var field = typeof(RateLimiterService).GetField("_ipMinute", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!; + return ((System.Collections.IDictionary)field.GetValue(limiter)!).Count; + } + + internal static DefaultHttpContext Request(string ip) + { + var context = new DefaultHttpContext(); + context.Connection.RemoteIpAddress = IPAddress.Parse(ip); + return context; + } +} + +internal sealed class LimiterStore : IAsyncDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "truthgate-rate-regression", Guid.NewGuid().ToString("N")); + private readonly MemoryCache _cache = new(new MemoryCacheOptions()); + public ManualClock Clock { get; } = new(); + public RateLimiterOptions Options { get; } = new(); + public FlushInterceptor Interceptor { get; } = new(); + public TestRateDbFactory Factory { get; private set; } = default!; + + public static async Task CreateAsync() + { + var store = new LimiterStore(); + Directory.CreateDirectory(store._directory); + store.Options.Public.PerIpPerMinute = 6; + store.Options.Public.GlobalTiers = []; + store.Options.TlsChurn.Enabled = false; + var options = new DbContextOptionsBuilder() + .UseSqlite($"Data Source={Path.Combine(store._directory, "rate.db")};Pooling=False") + .AddInterceptors(store.Interceptor).Options; + store.Factory = new TestRateDbFactory(options); + await using var db = store.Factory.CreateDbContext(); + await db.Database.EnsureCreatedAsync(); + return store; + } + + public async Task NewServiceAsync() + { + var service = new RateLimiterService(_cache, Factory, Microsoft.Extensions.Options.Options.Create(Options), + NullLogger.Instance, Clock); + await service.InitializeAsync(); + return service; + } + + public ValueTask DisposeAsync() + { + _cache.Dispose(); + Directory.Delete(_directory, true); + return ValueTask.CompletedTask; + } +} + +internal sealed class TestRateDbFactory(DbContextOptions options) : IDbContextFactory +{ + public RateLimiterDbContext CreateDbContext() => new(options); + public Task CreateDbContextAsync(CancellationToken cancellationToken = default) => Task.FromResult(CreateDbContext()); +} + +internal sealed class ManualClock : TimeProvider +{ + private DateTimeOffset _now = new(2027, 1, 1, 12, 0, 0, TimeSpan.Zero); + public override DateTimeOffset GetUtcNow() => _now; + public void Advance(TimeSpan amount) => _now += amount; +} + +internal sealed class FlushInterceptor : SaveChangesInterceptor +{ + public bool FailNext { get; set; } + public bool PauseNext { get; set; } + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public override async ValueTask> SavingChangesAsync(DbContextEventData eventData, + InterceptionResult result, CancellationToken cancellationToken = default) + { + if (FailNext) + { + FailNext = false; + throw new IOException("Injected local persistence failure."); + } + if (PauseNext) + { + PauseNext = false; + Entered.TrySetResult(); + await Release.Task.WaitAsync(cancellationToken); + } + return result; + } +} diff --git a/Test.TruthGate/Tests/TlsChurnTests.cs b/Test.TruthGate/Tests/TlsChurnTests.cs index 6e872a7..d1b8264 100644 --- a/Test.TruthGate/Tests/TlsChurnTests.cs +++ b/Test.TruthGate/Tests/TlsChurnTests.cs @@ -1,37 +1,33 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using Microsoft.AspNetCore.Http; using System.Net; -using System.Text; -using System.Threading.Tasks; -namespace Test.TruthGate.Tests -{ +namespace Test.TruthGate.Tests; - [Collection("TruthGateServerCollection")] - public sealed class TlsChurnTests : IAsyncLifetime +public sealed class TlsChurnTests +{ + [Fact] + public async Task New_connections_trigger_a_persisted_ban_but_reused_connections_do_not() { - private readonly TruthGateWebApplicationFactory _f; - private readonly TestClient _client; - - public TlsChurnTests(SqliteTestFixture fx) + await using var store = await LimiterStore.CreateAsync(); + store.Options.TlsChurn.Enabled = true; + store.Options.TlsChurn.NewConnectionsPerSec = 3; + store.Options.TlsChurn.ObserveSeconds = 3; + var limiter = await store.NewServiceAsync(); + for (var i = 0; i < 12; i++) { - _f = new TruthGateWebApplicationFactory(fx); - _client = new TestClient(_f.CreateClient()); + var context = RateLimiterLifecycleTests.Request("192.0.2.51"); + context.Connection.Id = "same-connection"; + await limiter.TrackTlsChurnAsync(context); } - - public Task InitializeAsync() => Task.CompletedTask; - public Task DisposeAsync() { _f.Dispose(); return Task.CompletedTask; } - - [Fact] - public async Task NewConn_Burst_Triggers_SoftBan() + Assert.False(limiter.IsBanned("192.0.2.51")); + for (var i = 0; i < 10; i++) { - var ip = "192.168.1.20"; - // 10 requests as new connections (threshold ~9 over 3s window) - var resps = await _client.BurstAsync("/ipfs/cat", 2000, ip: ip, newConn: true); - // Last may already be banned, but ensure next request is - var next = await _client.SendAsync("/ipfs/cat", ip: ip); - Assert.Equal(HttpStatusCode.Forbidden, next.StatusCode); + var context = RateLimiterLifecycleTests.Request("192.0.2.52"); + context.Connection.Id = "connection-" + i; + await limiter.TrackTlsChurnAsync(context); } + Assert.True(limiter.IsBanned("192.0.2.52")); + var restarted = await store.NewServiceAsync(); + Assert.True(restarted.IsBanned("192.0.2.52")); } } diff --git a/Test.TruthGate/Tests/WhitelistUnbanTests.cs b/Test.TruthGate/Tests/WhitelistUnbanTests.cs index 9310782..4c98166 100644 --- a/Test.TruthGate/Tests/WhitelistUnbanTests.cs +++ b/Test.TruthGate/Tests/WhitelistUnbanTests.cs @@ -1,94 +1,40 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; +using Microsoft.Extensions.DependencyInjection; using System.Net; -using System.Text; -using System.Threading.Tasks; using TruthGate_Web.Services; -namespace Test.TruthGate.Tests -{ +namespace Test.TruthGate.Tests; - [Collection("TruthGateServerCollection")] - public sealed class WhitelistUnbanTests : IAsyncLifetime +[Collection("TruthGateServerCollection")] +public sealed class WhitelistUnbanTests(SqliteTestFixture fixture) +{ + [Fact] + public async Task ManualWhitelist_Bypasses_Then_Removal_Reenables_Limits() { - private readonly TruthGateWebApplicationFactory _f; - private readonly TestClient _client; - - public WhitelistUnbanTests(SqliteTestFixture fx) - { - _f = new TruthGateWebApplicationFactory(fx); - _client = new TestClient(_f.CreateClient()); - } - - public Task InitializeAsync() => Task.CompletedTask; - public Task DisposeAsync() { _f.Dispose(); return Task.CompletedTask; } - - [Fact] - public async Task ManualWhitelist_Bypasses_Then_Removal_Reenables_Limits() - { - var ip = "203.0.113.55"; - // Add whitelist via DI - using var scope = _f.Services.CreateScope(); - var svc = scope.ServiceProvider.GetRequiredService(); - await svc.AddWhitelistIpAsync(ip, reason: "test"); - - // Should be allowed even if we exceed limits - var resps = await _client.BurstAsync("/public/ping", 8000, ip: ip); - Assert.All(resps, r => Assert.Equal(HttpStatusCode.OK, r.StatusCode)); - - // Remove whitelist and trigger 429 quickly - await svc.RemoveWhitelistIpAsync(ip); - for (int i = 0; i < 300; i++) Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync("/public/ping", ip: ip)).StatusCode); - Assert.Equal(HttpStatusCode.Forbidden, (await _client.SendAsync("/public/ping", ip: ip)).StatusCode); - } - - [Fact] - public async Task Unban_By_Ip_Clears_Forbidden() - { - var ip = "198.51.100.23"; - // Force a gateway ban - for (int i = 0; i < 8000; i++) await _client.SendAsync("/ipfs/cat", ip: ip); - var banned = await _client.SendAsync("/ipfs/cat", ip: ip); - Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode); - // Unban - using var scope = _f.Services.CreateScope(); - var svc = scope.ServiceProvider.GetRequiredService(); - - var isbanned = svc.IsBanned(ip); - Assert.Equal(true, isbanned); - var unbanned = await svc.UnbanIpAsync(ip); - - isbanned = svc.IsBanned(ip); - Assert.Equal(true, unbanned); - - var ok = await _client.SendAsync("/ipfs/cat", ip: ip); - Assert.Equal(HttpStatusCode.OK, ok.StatusCode); - } - - [Fact] - public async Task Unban_By_Ipv6_Clears_Forbidden() - { - var ip = "2001:db8::1234"; // doc-range IPv6 - - // Trip a gateway ban - for (int i = 0; i < 8000; i++) - await _client.SendAsync("/ipfs/cat", ip: ip); - - var banned = await _client.SendAsync("/ipfs/cat", ip: ip); - Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode); - - using var scope = _f.Services.CreateScope(); - var svc = scope.ServiceProvider.GetRequiredService(); - - var okUnban = await svc.UnbanIpAsync(ip, resetWindowMinutes: 60); - Assert.True(okUnban); - - var ok = await _client.SendAsync("/ipfs/cat", ip: ip); - Assert.Equal(HttpStatusCode.OK, ok.StatusCode); - } - + using var server = new TruthGateWebApplicationFactory(fixture, configure: options => options.Public.GlobalTiers = []); + var service = server.Services.GetRequiredService(); + var client = new TestClient(server.CreateClient()); + await service.AddWhitelistIpAsync("192.0.2.50", reason: "test"); + var responses = await client.BurstAsync("/public/ping", 32, ip: "192.0.2.50"); + Assert.All(responses, response => Assert.Equal(HttpStatusCode.OK, response.StatusCode)); + Assert.True(await service.RemoveWhitelistIpAsync("192.0.2.50")); + for (var i = 0; i < 6; i++) Assert.Equal(HttpStatusCode.OK, (await client.SendAsync("/public/ping", "192.0.2.50")).StatusCode); + Assert.Equal(HttpStatusCode.TooManyRequests, (await client.SendAsync("/public/ping", "192.0.2.50")).StatusCode); + } + [Theory] + [InlineData("198.51.100.23")] + [InlineData("2001:db8::1234")] + public async Task Unban_By_Ip_Clears_Forbidden_And_Resets_Recent_Usage(string ip) + { + using var server = new TruthGateWebApplicationFactory(fixture); + var service = server.Services.GetRequiredService(); + var client = new TestClient(server.CreateClient()); + for (var i = 0; i < 24; i++) Assert.Equal(HttpStatusCode.OK, (await client.SendAsync("/ipfs/cat", ip)).StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, (await client.SendAsync("/ipfs/cat", ip)).StatusCode); + await client.FlushAsync(); + Assert.True(service.IsBanned(ip)); + Assert.True(await service.UnbanIpAsync(ip)); + Assert.False(service.IsBanned(ip)); + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync("/ipfs/cat", ip)).StatusCode); } } diff --git a/Test.TruthGate/TruthGateWebApplicationFactory.cs b/Test.TruthGate/TruthGateWebApplicationFactory.cs index d61262d..0de40da 100644 --- a/Test.TruthGate/TruthGateWebApplicationFactory.cs +++ b/Test.TruthGate/TruthGateWebApplicationFactory.cs @@ -1,174 +1,150 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.VisualStudio.TestPlatform.TestHost; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Net; -using System.Net.Http.Headers; -using System.Security.Claims; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using TruthGate_Web.Services; -using TruthGate_Web.Security; +using System.Net; +using System.Security.Claims; +using System.Text.Encodings.Web; using TruthGate_Web.Middleware; using TruthGate_Web.Models; +using TruthGate_Web.Security; +using TruthGate_Web.Services; + +namespace Test.TruthGate; -namespace Test.TruthGate +/// +/// A local TestServer for the real rate/auth middleware. Only identity transport, client +/// address and connection IDs are supplied by fixtures; key validation is production code. +/// Each server has an isolated database unless a restart test explicitly reuses its path. +/// +public sealed class TruthGateWebApplicationFactory : IDisposable { - public sealed class TruthGateWebApplicationFactory : WebApplicationFactory + public const string ValidAdminKey = "VALID-ADMIN-KEY"; + private readonly TestServer _server; + public string DatabasePath { get; } + public IServiceProvider Services => _server.Services; + public TestKeyProvider Keys { get; } = new(); + + public TruthGateWebApplicationFactory(SqliteTestFixture fixture, string? databasePath = null, + Action? configure = null) { - private readonly SqliteTestFixture _fx; - public TruthGateWebApplicationFactory(SqliteTestFixture fx) => _fx = fx; - public const string ValidAdminKey = "VALID-ADMIN-KEY"; - protected override void ConfigureWebHost(IWebHostBuilder builder) - { - // Force the host to treat the web app assembly as the application - var webAsm = typeof(TruthGate_Web.Program).Assembly; - var appName = webAsm.GetName().Name!; - var webAsmDir = Path.GetDirectoryName(webAsm.Location)!; - var manifest = Path.Combine(webAsmDir, $"{appName}.staticwebassets.endpoints.json"); - - // 1) Make the host think the ApplicationName is the web app (not the test project) - builder.UseSetting(WebHostDefaults.ApplicationKey, appName); - - // 2) Provide the manifest path via host setting (this is what MapStaticAssets reads) - builder.UseSetting(WebHostDefaults.StaticWebAssetsKey, manifest); - - // 3) Also set the legacy env var (some code paths still read it) - if (File.Exists(manifest)) - Environment.SetEnvironmentVariable("ASPNETCORE_STATICWEBASSETS", manifest); - - // (optional but nice) make content root the web app’s output dir - builder.UseContentRoot(webAsmDir); - - // If you guard MapStaticAssets in Program, set Testing env: - builder.UseEnvironment("Testing"); - - - builder.ConfigureAppConfiguration((ctx, cfg) => + DatabasePath = databasePath ?? Path.Combine(fixture.TempRoot, Guid.NewGuid().ToString("N"), "ratelimiter.db"); + Directory.CreateDirectory(Path.GetDirectoryName(DatabasePath)!); + var builder = new WebHostBuilder().UseEnvironment("Testing") + .ConfigureServices(services => { - cfg.AddInMemoryCollection(new Dictionary + services.AddLogging(); + services.AddRouting(); + services.AddAuthentication("TestCookie") + .AddScheme("TestCookie", _ => { }); + services.AddSingleton(Keys); + services.AddSingleton(new TestConfigService(Path.ChangeExtension(DatabasePath, ".json"))); + services.AddMemoryCache(); + services.Configure(options => { - ["RateLimiterOptions:Admin:MaxBadKeyPerIpPer24h"] = "3", - ["RateLimiterOptions:Admin:GraceDays"] = "7", - ["RateLimiterOptions:Public:PerIpPerMinute"] = "6", - ["RateLimiterOptions:Public:GlobalTiers:0:Threshold"] = "10", - ["RateLimiterOptions:Public:GlobalTiers:0:NewPerMinute"] = "4", - ["RateLimiterOptions:Public:GlobalTiers:1:Threshold"] = "20", - ["RateLimiterOptions:Public:GlobalTiers:1:NewPerMinute"] = "3", - ["RateLimiterOptions:Public:GlobalTiers:2:Threshold"] = "30", - ["RateLimiterOptions:Public:GlobalTiers:2:NewPerMinute"] = "2", - ["RateLimiterOptions:Gateway:FreePerMinute"] = "8", - ["RateLimiterOptions:Gateway:HourlyOverage"] = "16", - ["RateLimiterOptions:Gateway:BanOnExhaustion"] = "00:00:06", - ["RateLimiterOptions:TlsChurn:Enabled"] = "true", - ["RateLimiterOptions:TlsChurn:NewConnectionsPerSec"] = "3", - ["RateLimiterOptions:TlsChurn:MinReqPerConn"] = "1.2", - ["RateLimiterOptions:TlsChurn:ObserveSeconds"] = "3", + options.Admin.MaxBadKeyPerIpPer24h = 3; + options.Public.PerIpPerMinute = 6; + options.Public.GlobalTiers = [(10, 4), (20, 3), (30, 2)]; + options.Gateway.FreePerMinute = 8; + options.Gateway.HourlyOverage = 16; + options.Gateway.BanOnExhaustion = TimeSpan.FromMinutes(1); + options.TlsChurn.Enabled = false; + options.TlsChurn.NewConnectionsPerSec = 3; + options.TlsChurn.ObserveSeconds = 3; + options.TlsChurn.MinReqPerConn = 1.2; + configure?.Invoke(options); }); - }); - - builder.ConfigureServices(services => + services.AddTruthGateRateLimiter($"Data Source={DatabasePath};Pooling=False"); + // These tests control flushing explicitly. Worker scheduling is covered + // separately and must not make enforcement assertions timing-dependent. + foreach (var descriptor in services.Where(x => x.ServiceType == typeof(IHostedService) + && (x.ImplementationType == typeof(RateLimiterFlushWorker) + || x.ImplementationType == typeof(RateLimiterPurgeWorker))).ToArray()) + services.Remove(descriptor); + }) + .Configure(app => { - services.AddSingleton(new TestConfigService(_fx.ConfigPath)); - services.AddMemoryCache(); - - - - // New signature: no cfg param - services.AddTruthGateRateLimiter(); - - - // Apply EF migrations once - using var sp = services.BuildServiceProvider(); - using var scope = sp.CreateScope(); - var dbf = scope.ServiceProvider.GetRequiredService>(); - using var db = dbf.CreateDbContext(); - db.Database.Migrate(); - }); + var database = app.ApplicationServices.GetRequiredService>(); + using (var db = database.CreateDbContext()) db.Database.Migrate(); + ((RateLimiterService)app.ApplicationServices.GetRequiredService()) + .InitializeAsync().GetAwaiter().GetResult(); - builder.Configure(app => - { - app.Use(async (ctx, next) => + app.Use(async (context, next) => { - // spoof IP / auth (optional) - if (ctx.Request.Headers.TryGetValue("X-Test-IP", out var ip)) - ctx.Connection.RemoteIpAddress = IPAddress.Parse(ip!); - - // resolve admin key result for this request - var res = KeyValidationResult.Missing; - if (ctx.Request.Headers.TryGetValue("X-Admin-Key", out var key)) - res = key == TruthGateWebApplicationFactory.ValidAdminKey - ? KeyValidationResult.Valid - : KeyValidationResult.Invalid; - - ctx.Items[RateLimiterConstants.KeyValidationResultItem] = res; - + var supplied = context.Request.Headers["X-Test-IP"].FirstOrDefault() + ?? context.Request.Headers["X-Test-IPv6"].FirstOrDefault(); + context.Connection.RemoteIpAddress = IPAddress.Parse(supplied ?? "192.0.2.254"); + context.Connection.Id = context.Request.Headers.ContainsKey("X-Test-Conn-Close") + ? Guid.NewGuid().ToString("N") : "reused-test-connection"; await next(); }); - - - app.UseGatewayRateProtection(); + // Keep the same relative ordering as the production entry point. app.UseRouting(); + app.UseAuthentication(); + app.UseApiKeyAuthentication(); + app.UseGatewayRateProtection(); app.UseTruthGateRateLimiter(); - app.UseEndpoints(endpoints => { endpoints.MapGet("/admin/secret", () => Results.Ok("ok")) - .WithMetadata(new AdminProtectedAttribute()); - - endpoints.MapGet("/public/ping", () => Results.Ok("pong")) - .WithMetadata(new PublicLimitedAttribute()); - - endpoints.MapGet("/ipfs/{**rest}", (string rest) => Results.Ok($"ipfs:{rest}")); - + .WithMetadata(new AdminProtectedAttribute()); + endpoints.MapGet("/public/ping", () => Results.Ok("ok")) + .WithMetadata(new PublicLimitedAttribute()).AllowAnonymous(); + endpoints.MapGet("/ipfs/cat", () => Results.Ok("ok")).AllowAnonymous(); + endpoints.MapPost("/auth/login", () => Results.Ok("login fixture")).AllowAnonymous(); + endpoints.MapPost("/api/v0/name/publish", (HttpContext context) => Results.Text(context.Request.Query["key"].ToString())) + .WithMetadata(new AdminProtectedAttribute()); endpoints.MapPost("/_test/flush", async context => { - var svc = (RateLimiterService)context.RequestServices.GetRequiredService(); - var mi = typeof(RateLimiterService).GetMethod("FlushAsync", - System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!; - await (Task)mi.Invoke(svc, null)!; + await ((RateLimiterService)context.RequestServices.GetRequiredService()).FlushAsync(); await Results.Ok().ExecuteAsync(context); - }); - - endpoints.MapGet("/_test/bans", async context => - { - var svc = context.RequestServices.GetRequiredService(); - var (items, total) = await svc.GetBansAsync(1, 100); - await Results.Json(new { total, items }).ExecuteAsync(context); - }); + }).AllowAnonymous(); }); }); - } + _server = new TestServer(builder); + } + public HttpClient CreateClient() => _server.CreateClient(); + public void Dispose() => _server.Dispose(); - private sealed class TestConfigService : IConfigService + public sealed class TestKeyProvider : IApiKeyProvider + { + private int _validations; + public int ValidationCount => Volatile.Read(ref _validations); + public string GetCurrentKey() => ValidAdminKey; + public bool IsValid(string? apiKey) { - public string ConfigPath { get; } - public TestConfigService(string path) => ConfigPath = path; - - public Task SaveAsync(Config newConfig, CancellationToken ct = default) - { - return Task.Delay(1); - } + Interlocked.Increment(ref _validations); + return apiKey == ValidAdminKey; + } + public DateTimeOffset CreatedAt => DateTimeOffset.UtcNow; + public DateTimeOffset ExpiresAt => DateTimeOffset.UtcNow.AddDays(1); + } - public Task UpdateAsync(Action mutator, CancellationToken ct = default) - { - return Task.Delay(1); - } + private sealed class TestConfigService(string path) : IConfigService + { + private Config _config = new(); + public string ConfigPath => path; + public Config Get() => _config; + public Task SaveAsync(Config newConfig, CancellationToken ct = default) { _config = newConfig; return Task.CompletedTask; } + public Task UpdateAsync(Action mutator, CancellationToken ct = default) { mutator(_config); return Task.CompletedTask; } + } - public Config Get() => new Config(); + private sealed class TestCookieHandler(IOptionsMonitor options, + ILoggerFactory logger, UrlEncoder encoder) : AuthenticationHandler(options, logger, encoder) + { + protected override Task HandleAuthenticateAsync() + { + if (Request.Headers["X-Test-User-Authenticated"] != "1") + return Task.FromResult(AuthenticateResult.NoResult()); + var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "test-user")], Scheme.Name); + return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name))); } } } diff --git a/TruthGate-IPFS.sln b/TruthGate-IPFS.sln index 1aa55bd..5fab0b1 100644 --- a/TruthGate-IPFS.sln +++ b/TruthGate-IPFS.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.13.35919.96 @@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Publish.CLI", "Publish.CLI\ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test.TruthGate", "Test.TruthGate\Test.TruthGate.csproj", "{ADAAD087-3264-4DDC-AA8E-EBE9A676C25B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TruthGate-Web.Tests", "TruthGate-Web\TruthGate-Web.Tests\TruthGate-Web.Tests.csproj", "{39588E44-AB22-4A32-A149-5D7A39818370}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -33,6 +35,10 @@ Global {ADAAD087-3264-4DDC-AA8E-EBE9A676C25B}.Debug|Any CPU.Build.0 = Debug|Any CPU {ADAAD087-3264-4DDC-AA8E-EBE9A676C25B}.Release|Any CPU.ActiveCfg = Release|Any CPU {ADAAD087-3264-4DDC-AA8E-EBE9A676C25B}.Release|Any CPU.Build.0 = Release|Any CPU + {39588E44-AB22-4A32-A149-5D7A39818370}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {39588E44-AB22-4A32-A149-5D7A39818370}.Debug|Any CPU.Build.0 = Debug|Any CPU + {39588E44-AB22-4A32-A149-5D7A39818370}.Release|Any CPU.ActiveCfg = Release|Any CPU + {39588E44-AB22-4A32-A149-5D7A39818370}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/TruthGate-Web/TruthGate-Web.Client/TruthGate-Web.Client.csproj b/TruthGate-Web/TruthGate-Web.Client/TruthGate-Web.Client.csproj index 01abcaf..452cb9b 100644 --- a/TruthGate-Web/TruthGate-Web.Client/TruthGate-Web.Client.csproj +++ b/TruthGate-Web/TruthGate-Web.Client/TruthGate-Web.Client.csproj @@ -1,4 +1,4 @@ - + net10.0 @@ -12,7 +12,7 @@ - + diff --git a/TruthGate-Web/TruthGate-Web.Tests/CertificateAdmissionTests.cs b/TruthGate-Web/TruthGate-Web.Tests/CertificateAdmissionTests.cs new file mode 100644 index 0000000..36a848f --- /dev/null +++ b/TruthGate-Web/TruthGate-Web.Tests/CertificateAdmissionTests.cs @@ -0,0 +1,183 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography.X509Certificates; +using TruthGate_Web.Configuration; +using TruthGate_Web.Models; +using Xunit; + +namespace TruthGate_Web.Tests; + +public sealed class CertificateAdmissionTests : IDisposable +{ + private readonly TlsTestDirectory _files = new(); + + [Fact] + public async Task ExplicitManagementHost_IsIssuedWithoutCreatingAContentMapping() + { + const string host = "admin.example"; + using var chain = TestCertificateChain.Create(host); + var config = MutableTlsConfig.ForHosts(); + var issuer = new TestBundleIssuer((_, _) => Task.FromResult(chain.Bundle)); + var live = _files.CreateProvider(config, new FileCertStore(_files.Path), issuer, + managementHosts: ["ADMIN.EXAMPLE."]); + + Assert.Equal(SslDecisionKind.RealIfPresent, live.DecideForHostIncludingStarish(host).Kind); + Assert.Equal([host], live.EnumerateDesiredHosts()); + Assert.Equal(SslDecisionKind.SelfSigned, live.DecideForHostIncludingStarish("unconfigured.admin.example").Kind); + Assert.False(live.TryQueueIssueIfMissing("unconfigured.admin.example")); + await live.ReconcileAsync(host); + + Assert.Equal(1, issuer.CallCount); + Assert.Equal(chain.Bundle.Certificate.Thumbprint, live.GetServerCertificateContext(host).TargetCertificate.Thumbprint); + Assert.Empty(config.Get().Domains); + } + + [Fact] + public async Task NestedAndDisabledIpnsNames_DoNotAllocateIssuanceState() + { + var config = new MutableTlsConfig(new Config + { + IpnsWildCardSubDomain = new IpnsWildCardSubDomain { WildCardSubDomain = "ipns.example", UseSSL = "true" }, + Domains = + [ + new EdgeDomain { Domain = "site.example", UseSSL = "true", IpnsKeyName = "site-key", IpnsPeerId = "k51authorized" }, + new EdgeDomain { Domain = "disabled.example", UseSSL = "false", IpnsKeyName = "disabled-key" } + ] + }); + var issuer = new TestBundleIssuer((_, _) => Task.FromResult(null)); + var live = _files.CreateProvider(config, new EmptyCertificateStore(), issuer); + + Assert.Equal(SslDecisionKind.RealIfPresent, live.DecideForHostIncludingStarish("site-key.IPNS.EXAMPLE.").Kind); + Assert.Equal(SslDecisionKind.RealIfPresent, live.DecideForHostIncludingStarish("k51authorized.ipns.example").Kind); + Assert.Equal(SslDecisionKind.SelfSigned, live.DecideForHostIncludingStarish("disabled-key.ipns.example").Kind); + Assert.Equal(SslDecisionKind.NoneFailTls, live.DecideForHostIncludingStarish("disabled.example").Kind); + for (var index = 0; index < 1000; index++) + { + var nested = $"site-key.unconfigured-{index}.ipns.example"; + Assert.Equal(SslDecisionKind.SelfSigned, live.DecideForHostIncludingStarish(nested).Kind); + Assert.False(live.TryQueueIssueIfMissing(nested)); + Assert.Equal(live.GetSelfSigned().Thumbprint, live.GetServerCertificateContext(nested).TargetCertificate.Thumbprint); + } + Assert.Equal(0, issuer.CallCount); + Assert.Equal(0, live.PendingIssuanceCount); + Assert.Empty(live.GetStatusSnapshot()); + Assert.Equal(1, config.ReadCount); + + // A new committed configuration invalidates the index once, including + // canonical IPNS names derived from a domain whose TLS was disabled. + await config.UpdateAsync(value => value.Domains[0].UseSSL = "false"); + Assert.False(live.TryQueueIssueIfMissing("site-key.ipns.example")); + Assert.Empty(live.EnumerateDesiredHosts()); + Assert.Equal(2, config.ReadCount); + } + + [Fact] + public async Task PendingAndRunningWork_IsBoundedUnderConcurrentAdmission() + { + var hosts = Enumerable.Range(0, 100).Select(index => $"site-{index}.example").ToArray(); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var active = 0; + var peak = 0; + var issuer = new TestBundleIssuer(async (_, ct) => + { + var running = Interlocked.Increment(ref active); + int observed; + do { observed = Volatile.Read(ref peak); } + while (running > observed && Interlocked.CompareExchange(ref peak, running, observed) != observed); + try { await release.Task.WaitAsync(ct); return null; } + finally { Interlocked.Decrement(ref active); } + }); + var live = _files.CreateProvider(MutableTlsConfig.ForHosts(hosts), new EmptyCertificateStore(), issuer, maxPending: 8); + var accepted = 0; + Task[] completions; + try + { + Parallel.ForEach(hosts, host => + { + if (live.TryQueueIssueIfMissing(host)) + Interlocked.Increment(ref accepted); + }); + Assert.Equal(8, accepted); + Assert.Equal(8, live.PendingIssuanceCount); + Assert.Equal(2, issuer.CallCount); + completions = hosts.Select(host => live.ReconcileAsync(host)).ToArray(); + Assert.Equal(8, live.PendingIssuanceCount); + } + finally { release.TrySetResult(); } + await Task.WhenAll(completions).WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal(0, live.PendingIssuanceCount); + Assert.InRange(peak, 1, 2); + Assert.Equal(8, issuer.CallCount); + } + + [Fact] + public async Task RemovedQueuedHost_IsCancelledBeforeAnAcmeOrderStarts() + { + var config = MutableTlsConfig.ForHosts("one.example", "two.example", "removed.example"); + var started = new ConcurrentBag(); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var issuer = new TestBundleIssuer(async (host, ct) => + { + started.Add(host); + await release.Task.WaitAsync(ct); + return null; + }); + var live = _files.CreateProvider(config, new EmptyCertificateStore(), issuer, maxPending: 4); + var first = live.ReconcileAsync("one.example"); + var second = live.ReconcileAsync("two.example"); + var queued = live.ReconcileAsync("removed.example"); + try + { + Assert.Equal(3, live.PendingIssuanceCount); + Assert.Equal(2, issuer.CallCount); + await config.UpdateAsync(value => value.Domains.RemoveAll(domain => domain.Domain == "removed.example")); + Assert.DoesNotContain("removed.example", live.EnumerateDesiredHosts()); + await queued.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal(2, live.PendingIssuanceCount); + Assert.DoesNotContain("removed.example", started); + Assert.DoesNotContain(live.GetStatusSnapshot(), status => status.Host == "removed.example"); + } + finally { release.TrySetResult(); } + await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal(2, issuer.CallCount); + } + + [Fact] + public async Task RemovedActiveHost_CannotInstallALateIssuerResult() + { + const string host = "removed.example"; + using var chain = TestCertificateChain.Create(host); + var config = MutableTlsConfig.ForHosts(host); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var issuer = new TestBundleIssuer(async (_, _) => + { + entered.TrySetResult(); + // Simulate a CA request that has already been sent and ignores cancellation. + await release.Task; + return chain.Bundle; + }); + var store = new FileCertStore(_files.Path); + var live = _files.CreateProvider(config, store, issuer); + var issuing = live.ReconcileAsync(host); + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + try + { + await config.UpdateAsync(value => value.Domains.Clear()); + Assert.Empty(live.EnumerateDesiredHosts()); + } + finally { release.TrySetResult(); } + await issuing.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Null(await store.LoadBundleAsync(host, CancellationToken.None)); + Assert.Null(live.TryLoadIssuedBundle(host)); + Assert.Empty(live.GetStatusSnapshot()); + Assert.Equal(0, live.PendingIssuanceCount); + } + + private sealed class EmptyCertificateStore : ICertificateStore + { + public Task LoadAsync(string host, CancellationToken ct) => Task.FromResult(null); + public Task SaveAsync(string host, X509Certificate2 certificate, CancellationToken ct) => Task.CompletedTask; + } + + public void Dispose() => _files.Dispose(); +} diff --git a/TruthGate-Web/TruthGate-Web.Tests/CertificateChainTests.cs b/TruthGate-Web/TruthGate-Web.Tests/CertificateChainTests.cs new file mode 100644 index 0000000..dd5f70e --- /dev/null +++ b/TruthGate-Web/TruthGate-Web.Tests/CertificateChainTests.cs @@ -0,0 +1,370 @@ +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text.Json; +using Certes; +using Certes.Acme; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Server.Kestrel.Https; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using TruthGate_Web.Configuration; +using TruthGate_Web.Models; +using TruthGate_Web.Services; +using Xunit; + +namespace TruthGate_Web.Tests; + +public sealed class CertificateChainTests : IDisposable +{ + private readonly TlsTestDirectory _files = new(); + + [Fact] + public async Task CertesBundle_PreservesBothIssuersAndPrivateKeyThroughFileStore() + { + using var chain = TestCertificateChain.Create("site.example"); + Assert.Equal(2, chain.Bundle.Issuers.Count); + Assert.True(chain.Bundle.Certificate.HasPrivateKey); + Assert.True(chain.Bundle.HasCompleteChain); + + var store = new FileCertStore(_files.Path); + await store.SaveBundleAsync("site.example", chain.Bundle, CancellationToken.None); + using var loaded = await store.LoadBundleAsync("site.example", CancellationToken.None); + Assert.NotNull(loaded); + Assert.Equal(chain.Bundle.Certificate.Thumbprint, loaded.Certificate.Thumbprint); + Assert.Equal(chain.Bundle.Issuers.Select(issuer => issuer.Thumbprint).Order(), loaded.Issuers.Select(issuer => issuer.Thumbprint).Order()); + Assert.True(loaded.Certificate.HasPrivateKey); + Assert.True(loaded.HasCompleteChain); + Assert.Contains(loaded.Context.IntermediateCertificates, certificate => certificate.Thumbprint == chain.Intermediate.Thumbprint); + Assert.Empty(Directory.EnumerateFiles(_files.Path, "*.tmp")); + } + + [Fact] + public async Task DynamicSni_SendsEachHostsOwnIntermediateToRootOnlyClients() + { + using var first = TestCertificateChain.Create("first.example"); + using var second = TestCertificateChain.Create("second.example"); + AssertMissingIntermediateFails(first); + AssertMissingIntermediateFails(second); + var store = new FileCertStore(_files.Path); + await store.SaveBundleAsync("first.example", first.Bundle, CancellationToken.None); + await store.SaveBundleAsync("second.example", second.Bundle, CancellationToken.None); + var config = new MutableTlsConfig(new Config + { + Domains = [new EdgeDomain { Domain = "first.example", UseSSL = "true" }, new EdgeDomain { Domain = "second.example", UseSSL = "true" }] + }); + var live = _files.CreateProvider(config, store, new TestBundleIssuer((_, _) => throw new InvalidOperationException("Fresh certificates must not be reissued."))); + await live.WarmCacheAsync("first.example"); + await live.WarmCacheAsync("second.example"); + + await WithServer(live, async port => + { + await VerifyHandshake(port, "first.example", first); + await VerifyHandshake(port, "second.example", second); + }); + } + + [Fact] + public async Task AcmeChainWithoutRoot_IsServableWhenServerDoesNotTrustThePrivateRoot() + { + const string host = "staging.example"; + using var material = TestCertificateChain.Create(host, includeRoot: false); + Assert.Single(material.Bundle.Issuers); + Assert.True(material.Bundle.HasCompleteChain); + var store = new FileCertStore(_files.Path, staging: true); + await store.SaveBundleAsync(host, material.Bundle, CancellationToken.None); + var live = _files.CreateProvider(MutableTlsConfig.ForHosts(host), store, + new TestBundleIssuer((_, _) => throw new InvalidOperationException("A supplied intermediate must not require a trusted root on the server."))); + await live.WarmCacheAsync(host); + await WithServer(live, port => VerifyHandshake(port, host, material)); + } + + [Fact] + public async Task RenewalAndRestart_KeepCompletePerHostContexts() + { + const string host = "renew.example"; + using var oldChain = TestCertificateChain.Create(host, daysRemaining: 10); + using var replacement = TestCertificateChain.Create(host); + var store = new FileCertStore(_files.Path); + await store.SaveBundleAsync(host, oldChain.Bundle, CancellationToken.None); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var issuer = new TestBundleIssuer(async (_, ct) => + { + entered.TrySetResult(); + await release.Task.WaitAsync(ct); + return replacement.Bundle; + }); + var config = MutableTlsConfig.ForHosts(host); + var live = _files.CreateProvider(config, store, issuer); + await live.WarmCacheAsync(host); + await WithServer(live, async port => + { + var renewing = live.ReconcileAsync(host); + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + try { await VerifyHandshake(port, host, oldChain); } + finally { release.TrySetResult(); } + await renewing; + await VerifyHandshake(port, host, replacement); + }); + + var restarted = _files.CreateProvider(config, store, issuer); + await restarted.WarmCacheAsync(host); + await WithServer(restarted, port => VerifyHandshake(port, host, replacement)); + Assert.Equal(1, issuer.CallCount); + } + + [Fact] + public async Task LegacyLeafOnlyPfx_IsRepairedEvenWhenLeafIsFresh() + { + const string host = "legacy.example"; + using var chain = TestCertificateChain.Create(host); + var store = new FileCertStore(_files.Path); + await store.SaveAsync(host, chain.Bundle.Certificate, CancellationToken.None); + using (var legacy = await store.LoadBundleAsync(host, CancellationToken.None)) + { + Assert.NotNull(legacy); + Assert.Equal(CertificateState.IncompleteChain, + CertificateInspector.InspectBundle(legacy, host, DateTimeOffset.UtcNow, TimeSpan.FromDays(30)).State); + } + var issuer = new TestBundleIssuer((_, _) => Task.FromResult(chain.Bundle)); + var live = _files.CreateProvider(MutableTlsConfig.ForHosts(host), store, issuer); + await live.ReconcileAsync(host); + Assert.Equal(1, issuer.CallCount); + Assert.Equal(2, live.TryLoadIssuedBundle(host)!.Issuers.Count); + await WithServer(live, port => VerifyHandshake(port, host, chain)); + } + + [Fact] + public async Task FailedRenewal_KeepsServingTheExistingCompleteChain() + { + const string host = "retry.example"; + using var chain = TestCertificateChain.Create(host, daysRemaining: 10); + var store = new FileCertStore(_files.Path); + await store.SaveBundleAsync(host, chain.Bundle, CancellationToken.None); + var issuer = new TestBundleIssuer((_, _) => throw new IOException("Injected CA outage")); + var live = _files.CreateProvider(MutableTlsConfig.ForHosts(host), store, issuer); + await live.WarmCacheAsync(host); + var context = live.GetServerCertificateContext(host); + await live.ReconcileAsync(host); + Assert.Same(context, live.GetServerCertificateContext(host)); + Assert.Equal(1, issuer.CallCount); + await WithServer(live, port => VerifyHandshake(port, host, chain)); + } + + [Fact] + public async Task UnchangedPfx_ReusesBundleAndExternalReplacementInvalidatesCache() + { + const string host = "cache.example"; + using var first = TestCertificateChain.Create(host); + using var second = TestCertificateChain.Create(host); + var disk = new FileCertStore(_files.Path); + var store = new CountingCertificateStore(disk); + await disk.SaveBundleAsync(host, first.Bundle, CancellationToken.None); + var live = _files.CreateProvider(MutableTlsConfig.ForHosts(host), store, new TestBundleIssuer((_, _) => throw new InvalidOperationException("Fresh certificates must not be reissued."))); + await live.WarmCacheAsync(host); + var context = live.GetServerCertificateContext(host); + await live.ReconcileAsync(host); + await live.ReconcileAsync(host); + Assert.Equal(1, store.LoadCount); + Assert.Same(context, live.GetServerCertificateContext(host)); + + await disk.SaveBundleAsync(host, second.Bundle, CancellationToken.None); + File.SetLastWriteTimeUtc(System.IO.Path.Combine(_files.Path, $"{host}.pfx"), DateTime.UtcNow.AddSeconds(2)); + await live.ReconcileAsync(host); + Assert.Equal(2, store.LoadCount); + Assert.Equal(second.Bundle.Certificate.Thumbprint, live.GetServerCertificateContext(host).TargetCertificate.Thumbprint); + Assert.NotSame(context, live.GetServerCertificateContext(host)); + } + + private static void AssertMissingIntermediateFails(TestCertificateChain material) + { + using var incomplete = new X509Chain(); + incomplete.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + incomplete.ChainPolicy.CustomTrustStore.Add(material.Root); + incomplete.ChainPolicy.DisableCertificateDownloads = true; + incomplete.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + Assert.False(incomplete.Build(material.Bundle.Certificate)); + Assert.Contains(incomplete.ChainStatus, status => status.Status.HasFlag(X509ChainStatusFlags.PartialChain)); + } + + private static async Task WithServer(LiveCertProvider live, Func test) + { + var builder = WebApplication.CreateBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0, listen => + listen.UseHttps(new TlsHandshakeCallbackOptions + { + OnConnection = context => new ValueTask(new SslServerAuthenticationOptions + { + ServerCertificateContext = live.GetServerCertificateContext(context.ClientHelloInfo.ServerName), + ApplicationProtocols = [SslApplicationProtocol.Http2, SslApplicationProtocol.Http11] + }) + }))); + await using var app = builder.Build(); + app.MapGet("/", () => "ok"); + await app.StartAsync(); + try { await test(new Uri(app.Urls.Single()).Port); } + finally { await app.StopAsync(); } + } + + private static async Task VerifyHandshake(int port, string host, TestCertificateChain expected) + { + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + using var connection = new TcpClient(); + await connection.ConnectAsync(IPAddress.Loopback, port, deadline.Token); + using var stream = new SslStream(connection.GetStream()); + var policy = new X509ChainPolicy + { + TrustMode = X509ChainTrustMode.CustomRootTrust, + RevocationMode = X509RevocationMode.NoCheck, + DisableCertificateDownloads = true + }; + // The client receives no intermediate through policy or the machine store. + // The server must send it through the dynamically selected TLS context. + policy.CustomTrustStore.Add(expected.Root); + await stream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions + { + TargetHost = host, + CertificateChainPolicy = policy, + ApplicationProtocols = [SslApplicationProtocol.Http11] + }, deadline.Token); + Assert.Equal(expected.Bundle.Certificate.Thumbprint, stream.RemoteCertificate?.GetCertHashString()); + Assert.Equal(SslApplicationProtocol.Http11, stream.NegotiatedApplicationProtocol); + } + + private sealed class CountingCertificateStore(FileCertStore inner) : ICertificateStore, IVersionedCertificateStore + { + public int LoadCount { get; private set; } + public string? GetVersion(string host) => inner.GetVersion(host); + public Task LoadAsync(string host, CancellationToken ct) => inner.LoadAsync(host, ct); + public Task SaveAsync(string host, X509Certificate2 certificate, CancellationToken ct) => inner.SaveAsync(host, certificate, ct); + public async Task LoadBundleAsync(string host, CancellationToken ct) + { + LoadCount++; + return await inner.LoadBundleAsync(host, ct); + } + public Task SaveBundleAsync(string host, CertificateBundle bundle, CancellationToken ct) => inner.SaveBundleAsync(host, bundle, ct); + } + + public void Dispose() => _files.Dispose(); +} + +internal sealed class TestCertificateChain : IDisposable +{ + public required X509Certificate2 Root { get; init; } + public required X509Certificate2 Intermediate { get; init; } + public required CertificateBundle Bundle { get; init; } + + public static TestCertificateChain Create(string host, int daysRemaining = 90, bool includeRoot = true) + { + var now = DateTimeOffset.UtcNow; + var unique = Guid.NewGuid().ToString("N"); + using var rootKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); + using var root = Request($"root-{unique}", rootKey, ca: true).CreateSelfSigned(now.AddDays(-1), now.AddDays(365)); + using var intermediateKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); + using var intermediatePublic = Request($"issuer-{unique}", intermediateKey, ca: true) + .Create(root, now.AddDays(-1), now.AddDays(180), RandomNumberGenerator.GetBytes(16)); + using var intermediate = intermediatePublic.CopyWithPrivateKey(intermediateKey); + using var leafKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var leafRequest = Request(host, leafKey, ca: false); + var san = new SubjectAlternativeNameBuilder(); + san.AddDnsName(host); + leafRequest.CertificateExtensions.Add(san.Build()); + leafRequest.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.1") }, false)); + using var leafPublic = leafRequest.Create(intermediate, now.AddMinutes(-5), now.AddDays(daysRemaining), RandomNumberGenerator.GetBytes(16)); + var pem = string.Join('\n', leafPublic.ExportCertificatePem(), intermediatePublic.ExportCertificatePem()); + if (includeRoot) + pem += "\n" + root.ExportCertificatePem(); + var downloadedShape = new CertificateChain(pem); + var bundle = CertesAcmeIssuer.BuildCertificateBundle(downloadedShape, KeyFactory.FromPem(leafKey.ExportPkcs8PrivateKeyPem())); + return new TestCertificateChain + { + Root = X509CertificateLoader.LoadCertificate(root.RawData), + Intermediate = X509CertificateLoader.LoadCertificate(intermediatePublic.RawData), + Bundle = bundle + }; + } + + private static CertificateRequest Request(string name, ECDsa key, bool ca) + { + var request = new CertificateRequest($"CN={name}", key, HashAlgorithmName.SHA256); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(ca, false, 0, true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension(ca ? X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign : X509KeyUsageFlags.DigitalSignature, true)); + request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false)); + return request; + } + + public void Dispose() { Bundle.Dispose(); Intermediate.Dispose(); Root.Dispose(); } +} + +internal sealed class TlsTestDirectory : IDisposable +{ + private readonly List _fallbacks = []; + public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"truthgate-chain-tests-{Guid.NewGuid():N}"); + + public TlsTestDirectory() => Directory.CreateDirectory(Path); + + public LiveCertProvider CreateProvider(IConfigService config, ICertificateStore store, IAcmeIssuer issuer, + int maxPending = 64, IReadOnlyCollection? managementHosts = null) + { + var fallback = KestrelExtensions.CreateSelfSignedServerCert(["localhost"]); + _fallbacks.Add(fallback); + return new LiveCertProvider(new SelfSignedCertCache(fallback, System.IO.Path.Combine(Path, $"fallback-{Guid.NewGuid():N}.pfx")), + store, issuer, config, NullLogger.Instance, maxPendingIssuance: maxPending, + managementHosts: managementHosts); + } + + public void Dispose() + { + foreach (var fallback in _fallbacks) + fallback.Dispose(); + Directory.Delete(Path, recursive: true); + } +} + +internal sealed class MutableTlsConfig(Config initial) : IConfigService, IConfigVersionSource +{ + private Config _config = initial; + private long _version = 1; + private readonly object _lock = new(); + private int _reads; + public long Version => Interlocked.Read(ref _version); + public int ReadCount => Volatile.Read(ref _reads); + public string ConfigPath => string.Empty; + public static MutableTlsConfig ForHosts(params string[] hosts) => new(new Config + { + Domains = hosts.Select(host => new EdgeDomain { Domain = host, UseSSL = "true" }).ToList() + }); + public Config Get() + { + Interlocked.Increment(ref _reads); + lock (_lock) return JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(_config))!; + } + public Task SaveAsync(Config config, CancellationToken ct = default) + { + lock (_lock) { _config = config; Interlocked.Increment(ref _version); } + return Task.CompletedTask; + } + public Task UpdateAsync(Action mutator, CancellationToken ct = default) + { + lock (_lock) { mutator(_config); Interlocked.Increment(ref _version); } + return Task.CompletedTask; + } +} + +internal sealed class TestBundleIssuer(Func> handler) : IAcmeIssuer +{ + private int _calls; + public int CallCount => Volatile.Read(ref _calls); + public Task IssueOrRenewAsync(string host, CancellationToken ct = default) + => throw new InvalidOperationException("The provider must request the whole bundle."); + public Task IssueOrRenewBundleAsync(string host, CancellationToken ct = default) + { + Interlocked.Increment(ref _calls); + return handler(host, ct); + } +} diff --git a/TruthGate-Web/TruthGate-Web.Tests/ConfigPersistenceTests.cs b/TruthGate-Web/TruthGate-Web.Tests/ConfigPersistenceTests.cs new file mode 100644 index 0000000..0ce9bf2 --- /dev/null +++ b/TruthGate-Web/TruthGate-Web.Tests/ConfigPersistenceTests.cs @@ -0,0 +1,158 @@ +using System.Text.Json; +using Microsoft.Extensions.Logging.Abstractions; +using TruthGate_Web.Models; +using TruthGate_Web.Services; +using Xunit; + +namespace TruthGate_Web.Tests; + +public sealed class ConfigPersistenceTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), $"truthgate-config-tests-{Guid.NewGuid():N}"); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task FailedSaveOrUpdate_PreservesMemoryDiskAndVersion(bool update) + { + var persistence = new ControlledPersistence(); + var service = await CreateService(persistence); + await service.SaveAsync(ConfigWithDomain("original.example")); + var originalBytes = await File.ReadAllBytesAsync(service.ConfigPath); + var originalVersion = service.Version; + persistence.Failure = new IOException("Injected storage failure"); + + await Assert.ThrowsAsync(() => update + ? service.UpdateAsync(config => config.Domains[0].Domain = "failed.example") + : service.SaveAsync(ConfigWithDomain("failed.example"))); + + Assert.Equal("original.example", service.Get().Domains[0].Domain); + Assert.Equal(originalBytes, await File.ReadAllBytesAsync(service.ConfigPath)); + Assert.Equal(originalVersion, service.Version); + + persistence.Failure = null; + await service.UpdateAsync(config => config.Domains[0].UseSSL = "true"); + var restarted = await CreateService(new AtomicConfigPersistence()); + Assert.Equal("original.example", restarted.Get().Domains[0].Domain); + Assert.Equal("true", restarted.Get().Domains[0].UseSSL); + } + + [Fact] + public async Task CancelledWrite_DoesNotPublishAndReadersKeepSeeingCommittedSnapshot() + { + var persistence = new ControlledPersistence(); + var service = await CreateService(persistence); + await service.SaveAsync(ConfigWithDomain("original.example")); + var originalVersion = service.Version; + persistence.Block = true; + using var cancellation = new CancellationTokenSource(); + var saving = service.UpdateAsync(config => config.Domains[0].Domain = "cancelled.example", cancellation.Token); + await persistence.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + // A pending filesystem write must not block HTTP/TLS configuration readers. + var snapshot = await Task.Run(service.Get).WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal("original.example", snapshot.Domains[0].Domain); + cancellation.Cancel(); + await Assert.ThrowsAnyAsync(() => saving); + Assert.Equal(originalVersion, service.Version); + Assert.Equal("original.example", service.Get().Domains[0].Domain); + Assert.Equal("original.example", ReadDisk(service).Domains[0].Domain); + } + + [Fact] + public async Task CallerOwnedObjects_CannotMutateCommittedState() + { + var service = await CreateService(new AtomicConfigPersistence()); + var input = ConfigWithDomain("saved.example"); + await service.SaveAsync(input); + input.Domains[0].Domain = "changed-outside-service.example"; + Assert.Equal("saved.example", service.Get().Domains[0].Domain); + + Config? escapedWorking = null; + await service.UpdateAsync(config => + { + escapedWorking = config; + config.Domains[0].Domain = "updated.example"; + }); + escapedWorking!.Domains.Clear(); + service.Get().Domains.Clear(); + Assert.Equal("updated.example", service.Get().Domains[0].Domain); + Assert.Equal("updated.example", ReadDisk(service).Domains[0].Domain); + } + + [Fact] + public async Task ConcurrentUpdates_AreSerializedWithoutLosingChanges() + { + var service = await CreateService(new AtomicConfigPersistence()); + await service.SaveAsync(new Config()); + await Task.WhenAll(Enumerable.Range(0, 20).Select(index => service.UpdateAsync(config => + config.Domains.Add(new EdgeDomain { Domain = $"site-{index}.example" })))); + + Assert.Equal(20, service.Get().Domains.Select(domain => domain.Domain).Distinct().Count()); + Assert.Equal(20, ReadDisk(service).Domains.Count); + Assert.Empty(Directory.EnumerateFiles(_directory, "*.tmp")); + if (!OperatingSystem.IsWindows()) + Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(service.ConfigPath)); + } + + [Fact] + public async Task AtomicWriter_CancellationAndRenameFailureCleanTemporaryFiles() + { + Directory.CreateDirectory(_directory); + var path = Path.Combine(_directory, "config.json"); + var persistence = new AtomicConfigPersistence(); + var original = "{\"committed\":true}"u8.ToArray(); + await persistence.WriteAsync(path, original, CancellationToken.None); + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + await Assert.ThrowsAnyAsync(() => persistence.WriteAsync(path, "{}"u8.ToArray(), cancelled.Token)); + Assert.Equal(original, await File.ReadAllBytesAsync(path)); + + var directoryDestination = Path.Combine(_directory, "is-a-directory"); + Directory.CreateDirectory(directoryDestination); + await Assert.ThrowsAnyAsync(() => persistence.WriteAsync(directoryDestination, "{}"u8.ToArray(), CancellationToken.None)); + Assert.True(Directory.Exists(directoryDestination)); + Assert.Empty(Directory.EnumerateFiles(_directory, "*.tmp")); + } + + private async Task CreateService(IConfigPersistence persistence) + { + var service = new ConfigService(NullLogger.Instance, persistence, Path.Combine(_directory, "config.json")); + await service.StartAsync(CancellationToken.None); + return service; + } + + private static Config ConfigWithDomain(string host) => new() + { + Domains = [new EdgeDomain { Domain = host }] + }; + + private static Config ReadDisk(ConfigService service) + => JsonSerializer.Deserialize(File.ReadAllBytes(service.ConfigPath))!; + + private sealed class ControlledPersistence : IConfigPersistence + { + private readonly AtomicConfigPersistence _inner = new(); + public Exception? Failure { get; set; } + public bool Block { get; set; } + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public async Task WriteAsync(string path, ReadOnlyMemory json, CancellationToken ct) + { + if (Failure is not null) + throw Failure; + if (Block) + { + Entered.TrySetResult(true); + await Task.Delay(Timeout.Infinite, ct); + } + await _inner.WriteAsync(path, json, ct); + } + } + + public void Dispose() + { + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } +} diff --git a/TruthGate-Web/TruthGate-Web.Tests/IpnsUpdateRecoveryTests.cs b/TruthGate-Web/TruthGate-Web.Tests/IpnsUpdateRecoveryTests.cs new file mode 100644 index 0000000..3bc24b6 --- /dev/null +++ b/TruthGate-Web/TruthGate-Web.Tests/IpnsUpdateRecoveryTests.cs @@ -0,0 +1,133 @@ +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using TruthGate_Web.Models; +using TruthGate_Web.Services; +using Xunit; + +namespace TruthGate_Web.Tests; + +public sealed class IpnsUpdateRecoveryTests +{ + [Theory] + [InlineData("copy")] + [InlineData("pin")] + public async Task ConnectedAcquisitionFailureDoesNotCommitAndTheSamePointerIsRetried(string failureKind) + { + using var kubo = CreateKubo(); + using var cache = new MemoryCache(new MemoryCacheOptions()); + var config = Config(keepOld: false); + var failures = 1; + kubo.Fail = request => ((failureKind == "copy" && request.Command == "/api/v0/files/cp" && request.Args[0] == "/ipfs/target1") || + (failureKind == "pin" && request.Command == "/api/v0/pin/add" && request.Args[0] == "target1")) && failures-- > 0 + ? "connected DAG temporarily unavailable" : null; + var firstWorker = Worker(kubo, config, cache); + + await Assert.ThrowsAsync(() => firstWorker.RunOnceForAsync("watch")); + + Assert.Equal("old-pointer", config.Get().IpnsKeys[0].CurrentCID); + Assert.Contains("/production/pinned/watch-v001", kubo.Directories); + Assert.Contains("/production/pinned/watch-v001-connected", kubo.Directories); + Assert.DoesNotContain("/production/pinned/watch-v002", kubo.Directories); + Assert.Contains("old-target", kubo.Pins); + + // A fresh worker resolves exactly the same pointer after the transient target failure. + await Worker(kubo, config, cache).RunOnceForAsync("watch"); + + Assert.Equal("pointer1", config.Get().IpnsKeys[0].CurrentCID); + Assert.Equal("pointer1", kubo.Hash("/production/pinned/watch-v002")); + Assert.Equal("target1", kubo.Hash("/production/pinned/watch-v002-connected")); + Assert.Contains("target1", kubo.Pins); + Assert.DoesNotContain("/production/pinned/watch-v001", kubo.Directories); + Assert.DoesNotContain("/production/pinned/watch-v001-connected", kubo.Directories); + } + + [Fact] + public async Task ExistingPointerWithoutConnectedFolderIsRepairedEvenWhenConfigAlreadyMatches() + { + using var kubo = CreateKubo(); + using var cache = new MemoryCache(new MemoryCacheOptions()); + var config = Config(keepOld: true); + await config.UpdateAsync(value => value.IpnsKeys[0].CurrentCID = "pointer1"); + kubo.Mount("pointer1", "/production/pinned/watch-v002"); + kubo.Pins.Add("pointer1"); + + await Worker(kubo, config, cache).RunOnceForAsync("watch"); + + Assert.Equal("target1", kubo.Hash("/production/pinned/watch-v002-connected")); + Assert.Contains("target1", kubo.Pins); + Assert.Contains("/production/pinned/watch-v001-connected", kubo.Directories); + } + + [Fact] + public async Task IncompleteNewerPairNeverPrunesPreviousCompletePair() + { + using var kubo = CreateKubo(); + using var cache = new MemoryCache(new MemoryCacheOptions()); + var config = Config(keepOld: false); + kubo.Mount("pointer1", "/production/pinned/watch-v002"); + kubo.Pins.Add("pointer1"); + + await Worker(kubo, config, cache).EnsureKeepOldPolicyAsync("watch"); + + Assert.Contains("/production/pinned/watch-v001", kubo.Directories); + Assert.Contains("/production/pinned/watch-v001-connected", kubo.Directories); + Assert.Contains("/production/pinned/watch-v002", kubo.Directories); + Assert.Contains("old-target", kubo.Pins); + Assert.DoesNotContain(kubo.Requests, r => r.Command == "/api/v0/pin/rm"); + } + + [Fact] + public async Task ConnectedFolderWithoutRecursivePinCannotTriggerPruning() + { + using var kubo = CreateKubo(); + using var cache = new MemoryCache(new MemoryCacheOptions()); + var config = Config(keepOld: false); + kubo.Mount("pointer1", "/production/pinned/watch-v002"); + kubo.Mount("target1", "/production/pinned/watch-v002-connected"); + kubo.Pins.Add("pointer1"); + + await Worker(kubo, config, cache).EnsureKeepOldPolicyAsync("watch"); + + Assert.Contains("/production/pinned/watch-v001", kubo.Directories); + Assert.Contains("old-target", kubo.Pins); + Assert.DoesNotContain(kubo.Requests, r => r.Command == "/api/v0/pin/rm"); + } + + [Fact] + public async Task MetadataReadFailureCannotCommitAnApparentlyNonTgpPointer() + { + using var kubo = CreateKubo(); + using var cache = new MemoryCache(new MemoryCacheOptions()); + var config = Config(keepOld: false); + kubo.Fail = request => request.Command == "/api/v0/cat" ? "routing timed out" : null; + + await Assert.ThrowsAsync(() => Worker(kubo, config, cache).RunOnceForAsync("watch")); + + Assert.Equal("old-pointer", config.Get().IpnsKeys[0].CurrentCID); + Assert.Contains("/production/pinned/watch-v001-connected", kubo.Directories); + Assert.DoesNotContain(kubo.Requests, r => r.Command == "/api/v0/pin/rm"); + } + + private static PublishingKubo CreateKubo() + { + var kubo = new PublishingKubo(); + kubo.Ipfs["pointer1"] = new() { ["tgp.json"] = "{\"tgp\":1,\"current\":\"target1\"}", ["index.html"] = "new pointer" }; + kubo.Ipfs["target1"] = new() { ["index.html"] = "new app" }; + kubo.Ipfs["old-pointer"] = new() { ["tgp.json"] = "{\"tgp\":1,\"current\":\"old-target\"}", ["index.html"] = "old pointer" }; + kubo.Ipfs["old-target"] = new() { ["index.html"] = "old app" }; + kubo.Mount("old-pointer", "/production/pinned/watch-v001"); + kubo.Mount("old-target", "/production/pinned/watch-v001-connected"); + kubo.Pins.UnionWith(["old-pointer", "old-target"]); + return kubo; + } + + private static PublishingConfig Config(bool keepOld) => new(new Config + { + IpnsKeys = [new IpnsKey { Name = "watch", Key = "peer-watch", AutoUpdateToPin = true, + CurrentCID = "old-pointer", KeepOldCidPinned = keepOld }] + }, "/unused/config.json"); + + private static IpnsUpdateWorker Worker(PublishingKubo kubo, PublishingConfig config, IMemoryCache cache) + => new(kubo, config, cache, NullLogger.Instance, new PublishingKeys(), Options.Create(new IpnsUpdateOptions())); +} diff --git a/TruthGate-Web/TruthGate-Web.Tests/IpnsVersionRetentionTests.cs b/TruthGate-Web/TruthGate-Web.Tests/IpnsVersionRetentionTests.cs new file mode 100644 index 0000000..179a923 --- /dev/null +++ b/TruthGate-Web/TruthGate-Web.Tests/IpnsVersionRetentionTests.cs @@ -0,0 +1,146 @@ +using TruthGate_Web.Services; +using Xunit; + +namespace TruthGate_Web.Tests; + +public sealed class IpnsVersionRetentionTests +{ + [Theory] + [InlineData("site", "site-v001", 1, false)] + [InlineData("site", "site-v001-connected", 1, true)] + [InlineData("My-Site", "my-site-v042-CONNECTED", 42, true)] + public void TryParseEntryName_RecognizesPointerAndConnectedNames( + string trackedName, + string entryName, + int expectedVersion, + bool expectedConnected) + { + var parsed = IpnsVersionRetention.TryParseEntryName( + trackedName, + entryName, + out var version, + out var connected); + + Assert.True(parsed); + Assert.Equal(expectedVersion, version); + Assert.Equal(expectedConnected, connected); + } + + [Theory] + [InlineData("site", "site-v")] + [InlineData("site", "site-v001-extra")] + [InlineData("site", "other-v001")] + [InlineData("site", "site-v001-connected-extra")] + public void TryParseEntryName_RejectsUnmanagedNames(string trackedName, string entryName) + => Assert.False(IpnsVersionRetention.TryParseEntryName(trackedName, entryName, out _, out _)); + + [Fact] + public void GroupVersions_PairsPointerAndConnectedFolders() + { + var children = Children( + ("site-v001", "pointer-1"), + ("site-v001-connected", "target-1"), + ("site-v002", "pointer-2"), + ("site-v002-connected", "target-2")); + + var pairs = IpnsVersionRetention.GroupVersions("site", children); + + Assert.Equal(2, pairs.Count); + Assert.Equal("pointer-1", pairs[0].Pointer?.Cid); + Assert.Equal("target-1", pairs[0].Connected?.Cid); + Assert.Equal("pointer-2", pairs[1].Pointer?.Cid); + Assert.Equal("target-2", pairs[1].Connected?.Cid); + Assert.Equal(3, IpnsVersionRetention.ComputeNextVersion("site", children.Keys)); + } + + [Fact] + public void BuildPrunePlan_RemovesOldPointerAndConnectedPair() + { + var pairs = IpnsVersionRetention.GroupVersions( + "site", + Children( + ("site-v001", "pointer-1"), + ("site-v001-connected", "target-1"), + ("site-v002", "pointer-2"), + ("site-v002-connected", "target-2"))); + + var plan = IpnsVersionRetention.BuildPrunePlan( + pairs, + retainedVersion: 2, + new Dictionary { [1] = "target-1", [2] = "target-2" }); + + Assert.Contains("/production/pinned/site-v001", plan.PathsToRemove); + Assert.Contains("/production/pinned/site-v001-connected", plan.PathsToRemove); + Assert.DoesNotContain("/production/pinned/site-v002", plan.PathsToRemove); + Assert.Contains("pointer-1", plan.CidsToUnpin); + Assert.Contains("target-1", plan.CidsToUnpin); + Assert.DoesNotContain("pointer-2", plan.CidsToUnpin); + Assert.DoesNotContain("target-2", plan.CidsToUnpin); + } + + [Fact] + public void BuildPrunePlan_DoesNotUnpinTargetSharedWithRetainedVersion() + { + var pairs = IpnsVersionRetention.GroupVersions( + "site", + Children( + ("site-v001", "pointer-1"), + ("site-v001-connected", "shared-target"), + ("site-v002", "pointer-2"), + ("site-v002-connected", "shared-target"))); + + var plan = IpnsVersionRetention.BuildPrunePlan( + pairs, + retainedVersion: 2, + new Dictionary { [1] = "shared-target", [2] = "shared-target" }); + + Assert.Contains("pointer-1", plan.CidsToUnpin); + Assert.DoesNotContain("shared-target", plan.CidsToUnpin); + } + + [Fact] + public void BuildPrunePlan_RemovesOrphanConnectedFolderOutsideRetainedVersion() + { + var pairs = IpnsVersionRetention.GroupVersions( + "site", + Children( + ("site-v002", "pointer-2"), + ("site-v002-connected", "target-2"), + ("site-v003-connected", "orphan-target"))); + + var latest = IpnsVersionRetention.GetLatestPointerPair(pairs); + Assert.NotNull(latest); + Assert.Equal(2, latest.Version); + + var plan = IpnsVersionRetention.BuildPrunePlan( + pairs, + latest.Version, + new Dictionary { [2] = "target-2", [3] = "orphan-target" }); + + Assert.Contains("/production/pinned/site-v003-connected", plan.PathsToRemove); + Assert.Contains("orphan-target", plan.CidsToUnpin); + } + + [Theory] + [InlineData("""{"tgp":1,"current":"bafy-current"}""", "bafy-current")] + [InlineData("""{"tgp":1,"current":"/ipfs/bafy-current"}""", "bafy-current")] + [InlineData("""{"tgp":2,"current":"bafy-current"}""", null)] + [InlineData("[]", null)] + [InlineData("not-json", null)] + public void TryReadTgpCurrentCid_ParsesVersionOnePointer(string json, string? expected) + => Assert.Equal(expected, IpnsVersionRetention.TryReadTgpCurrentCid(json)); + + [Fact] + public void TryReadLegacyTargetCid_PreservesSidecarCompatibility() + { + const string json = """{"Kind":"tgp-meta","PointerCid":"pointer","TargetCid":"/ipfs/legacy-target"}"""; + Assert.Equal("legacy-target", IpnsVersionRetention.TryReadLegacyTargetCid(json)); + } + + private static Dictionary Children( + params (string Name, string Cid)[] entries) + => entries.ToDictionary( + entry => entry.Name, + entry => (entry.Cid, $"/production/pinned/{entry.Name}"), + StringComparer.OrdinalIgnoreCase); +} diff --git a/TruthGate-Web/TruthGate-Web.Tests/PublicationRecoveryTests.cs b/TruthGate-Web/TruthGate-Web.Tests/PublicationRecoveryTests.cs new file mode 100644 index 0000000..615fa58 --- /dev/null +++ b/TruthGate-Web/TruthGate-Web.Tests/PublicationRecoveryTests.cs @@ -0,0 +1,259 @@ +using System.Text.Json; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using TruthGate_Web.Models; +using TruthGate_Web.Services; +using TruthGate_Web.Utils; +using Xunit; + +namespace TruthGate_Web.Tests; + +public sealed class PublicationRecoveryTests +{ + [Fact] + public async Task AcceptedJobSurvivesStoreAndWorkerRecreationAndReportsTheFinalCid() + { + using var fixture = new Fixture(); + fixture.Kubo.Put(fixture.Stage + "/index.html", "first deployment"); + var jobId = await fixture.Queue().EnqueueAsync(fixture.Job); + var restarted = fixture.Queue(); + Assert.Equal(PublishJobState.Queued, (await restarted.GetStatusAsync(jobId))!.State); + + await restarted.RecoverInterruptedAsync(CancellationToken.None); + await restarted.ProcessAvailableOnceAsync(CancellationToken.None); + + var status = await restarted.GetStatusAsync(jobId); + Assert.NotNull(status); + Assert.Equal(PublishJobState.Succeeded, status.State); + var actualCid = fixture.Kubo.Hash(fixture.Site); + Assert.Equal(actualCid, status.ResultCid); + Assert.Equal(actualCid, fixture.Config.Get().Domains[0].LastPublishedCid); + using var pointer = JsonDocument.Parse(fixture.Kubo.Files[fixture.Pointer + "/tgp.json"]); + Assert.Equal(actualCid, pointer.RootElement.GetProperty("current").GetString()); + Assert.Contains(actualCid, fixture.Kubo.Pins); + Assert.Equal(status.TgpCid, Assert.Single(fixture.Kubo.Published)); + Assert.True(fixture.Kubo.Files.ContainsKey(fixture.Site + "/ipns-key.json")); + Assert.DoesNotContain(fixture.Stage, fixture.Kubo.Directories); + Assert.DoesNotContain("/staging/pointers/" + jobId, fixture.Kubo.Directories); + } + + [Fact] + public async Task FailedSitePromotionRestoresBothPreviousRootsBeforeReportingFailure() + { + using var fixture = new Fixture(); + fixture.Kubo.Put(fixture.Site + "/index.html", "working old site"); + fixture.Kubo.Put(fixture.Pointer + "/tgp.json", "old pointer"); + var oldSite = fixture.Kubo.Hash(fixture.Site); + var oldPointer = fixture.Kubo.Hash(fixture.Pointer); + fixture.Kubo.Put(fixture.Stage + "/index.html", "new upload"); + var failures = 1; + fixture.Kubo.Fail = request => request.Command == "/api/v0/files/cp" && request.Args[1] == fixture.Site && failures-- > 0 + ? "injected new site copy failure" : null; + var queue = fixture.Queue(); + var jobId = await queue.EnqueueAsync(fixture.Job); + + await queue.ProcessAvailableOnceAsync(CancellationToken.None); + + Assert.Equal(PublishJobState.Failed, (await queue.GetStatusAsync(jobId))!.State); + Assert.Equal(oldSite, fixture.Kubo.Hash(fixture.Site)); + Assert.Equal(oldPointer, fixture.Kubo.Hash(fixture.Pointer)); + Assert.Contains(oldSite, fixture.Kubo.Pins); + Assert.Contains(oldPointer, fixture.Kubo.Pins); + Assert.Empty(fixture.Kubo.Published); + Assert.DoesNotContain(fixture.Stage, fixture.Kubo.Directories); + } + + [Fact] + public async Task FailedPointerPromotionRestoresAlreadyReplacedSite() + { + using var fixture = new Fixture(); + fixture.Kubo.Put(fixture.Site + "/index.html", "old site"); + fixture.Kubo.Put(fixture.Pointer + "/tgp.json", "old pointer"); + var oldSite = fixture.Kubo.Hash(fixture.Site); + var oldPointer = fixture.Kubo.Hash(fixture.Pointer); + fixture.Kubo.Put(fixture.Stage + "/index.html", "new site"); + var failures = 1; + fixture.Kubo.Fail = request => request.Command == "/api/v0/files/cp" && request.Args[1] == fixture.Pointer && failures-- > 0 + ? "injected pointer copy failure" : null; + var queue = fixture.Queue(); + var jobId = await queue.EnqueueAsync(fixture.Job); + + await queue.ProcessAvailableOnceAsync(CancellationToken.None); + + Assert.Equal(PublishJobState.Failed, (await queue.GetStatusAsync(jobId))!.State); + Assert.Equal(oldSite, fixture.Kubo.Hash(fixture.Site)); + Assert.Equal(oldPointer, fixture.Kubo.Hash(fixture.Pointer)); + Assert.Empty(fixture.Kubo.Published); + } + + [Fact] + public async Task UncertainIpnsPublishIsJournaledAndRestartReplaysTheExactPreparedRelease() + { + using var fixture = new Fixture(); + fixture.Kubo.Put(fixture.Site + "/index.html", "old site"); + fixture.Kubo.Put(fixture.Pointer + "/tgp.json", "old pointer"); + fixture.Kubo.Put(fixture.Stage + "/index.html", "new site"); + fixture.Kubo.Fail = request => request.Command == "/api/v0/name/publish" ? "response unavailable" : null; + var queue = fixture.Queue(); + var jobId = await queue.EnqueueAsync(fixture.Job); + + await queue.ProcessAvailableOnceAsync(CancellationToken.None); + var interrupted = await fixture.Store().GetAsync(jobId); + Assert.NotNull(interrupted); + Assert.Equal(PublishJobState.RecoveryRequired, interrupted.State); + Assert.True(interrupted.PublishAttempted); + Assert.True(interrupted.Prepared); + Assert.Contains(fixture.Stage, fixture.Kubo.Directories); + var preparedSite = interrupted.SiteCid; + var preparedPointer = interrupted.TgpCid; + + // Restart uses immutable checkpoint CIDs, even if staging contents subsequently change. + fixture.Kubo.Put(fixture.Stage + "/index.html", "must not replace the prepared release"); + fixture.Kubo.Fail = null; + var restarted = fixture.Queue(); + await restarted.RecoverInterruptedAsync(CancellationToken.None); + await restarted.ProcessAvailableOnceAsync(CancellationToken.None); + + var completed = await restarted.GetStatusAsync(jobId); + Assert.Equal(PublishJobState.Succeeded, completed!.State); + Assert.Equal(2, completed.Attempts); + Assert.Equal(preparedSite, completed.ResultCid); + Assert.Equal(preparedSite, fixture.Kubo.Hash(fixture.Site)); + Assert.Equal(preparedPointer, fixture.Kubo.Hash(fixture.Pointer)); + Assert.Equal(preparedPointer, Assert.Single(fixture.Kubo.Published)); + } + + [Fact] + public async Task InterruptedRemovalResumesFromJournalWithoutOriginalStaging() + { + using var fixture = new Fixture(); + fixture.Kubo.Ipfs["new-site"] = new() { ["index.html"] = "new site", ["ipns-key.json"] = "{}" }; + fixture.Kubo.Ipfs["new-pointer"] = new() { ["tgp.json"] = "{\"tgp\":1,\"current\":\"new-site\"}" }; + fixture.Kubo.Put(fixture.Site + "/index.html", "old site"); + fixture.Kubo.Put(fixture.Pointer + "/tgp.json", "old pointer"); + var record = await fixture.Store().CreateAsync(fixture.Job); + record = record with + { + State = PublishJobState.Running, Attempts = 1, Prepared = true, + SiteTarget = fixture.Site, TgpTarget = fixture.Pointer, + SiteCid = "new-site", TgpCid = "new-pointer", + PreviousSiteCid = fixture.Kubo.Hash(fixture.Site), PreviousTgpCid = fixture.Kubo.Hash(fixture.Pointer), + KeyName = "known-key", PeerId = "known-peer" + }; + await fixture.Store().SaveAsync(record); + fixture.Kubo.Remove(fixture.Site); // Simulates a crash immediately after live-path removal. + + var restarted = fixture.Queue(); + await restarted.RecoverInterruptedAsync(CancellationToken.None); + await restarted.ProcessAvailableOnceAsync(CancellationToken.None); + + Assert.Equal(PublishJobState.Succeeded, (await restarted.GetStatusAsync(record.JobId))!.State); + Assert.Equal("new-site", fixture.Kubo.Hash(fixture.Site)); + Assert.Equal("new-pointer", fixture.Kubo.Hash(fixture.Pointer)); + Assert.Equal("new-site", fixture.Config.Get().Domains[0].LastPublishedCid); + } + + [Fact] + public async Task FailedRollbackRemainsRecoverableAndBlocksLaterJobsForThatDomain() + { + using var fixture = new Fixture(); + fixture.Kubo.Put(fixture.Site + "/index.html", "old site"); + fixture.Kubo.Put(fixture.Pointer + "/tgp.json", "old pointer"); + fixture.Kubo.Put(fixture.Stage + "/index.html", "new site"); + fixture.Kubo.Fail = request => request.Command == "/api/v0/files/cp" && request.Args[1] == fixture.Site ? "copies unavailable" : null; + var queue = fixture.Queue(); + var first = await queue.EnqueueAsync(fixture.Job); + var second = await queue.EnqueueAsync(fixture.Job with { StagingRoot = fixture.Stage + "-second" }); + + await queue.ProcessAvailableOnceAsync(CancellationToken.None); + + Assert.Equal(PublishJobState.RecoveryRequired, (await queue.GetStatusAsync(first))!.State); + Assert.Equal(PublishJobState.Queued, (await queue.GetStatusAsync(second))!.State); + Assert.Contains(fixture.Stage, fixture.Kubo.Directories); + Assert.Empty(fixture.Kubo.Published); + fixture.Kubo.Fail = null; + await queue.RetryAsync(first); + await queue.ProcessAvailableOnceAsync(CancellationToken.None); + Assert.Equal(PublishJobState.Succeeded, (await queue.GetStatusAsync(first))!.State); + } + + [Fact] + public async Task SuccessfulPublicationInvalidatesPreviouslyCachedSiteCid() + { + using var fixture = new Fixture(); + using var cache = new MemoryCache(new MemoryCacheOptions()); + fixture.Kubo.Put(fixture.Site + "/index.html", "old cached site"); + var oldCid = await IpfsGateway.ResolveMfsFolderToCidCachedAsync(fixture.Site, fixture.Kubo, cache, TimeSpan.FromMinutes(10)); + fixture.Kubo.Put(fixture.Stage + "/index.html", "new site"); + var queue = fixture.Queue(); + var jobId = await queue.EnqueueAsync(fixture.Job); + + await queue.ProcessAvailableOnceAsync(CancellationToken.None); + + Assert.Equal(PublishJobState.Succeeded, (await queue.GetStatusAsync(jobId))!.State); + var current = await IpfsGateway.ResolveMfsFolderToCidCachedAsync(fixture.Site, fixture.Kubo, cache, TimeSpan.FromMinutes(10)); + Assert.NotEqual(oldCid, current); + Assert.Equal(fixture.Kubo.Hash(fixture.Site), current); + } + + [Fact] + public async Task DurableStoreBoundsPendingJobsAndCompletedHistory() + { + using var fixture = new Fixture(new PublishQueueOptions { MaxPendingJobs = 1, MaxRetainedJobs = 1 }); + var first = await fixture.Store().CreateAsync(fixture.Job); + await Assert.ThrowsAsync(() => fixture.Store().CreateAsync(fixture.Job)); + await fixture.Store().SaveAsync(first with { State = PublishJobState.Failed, CleanupCompleted = false }); + await Assert.ThrowsAsync(() => fixture.Store().CreateAsync(fixture.Job)); + await fixture.Store().SaveAsync(first with { State = PublishJobState.Failed, CleanupCompleted = true }); + var second = await fixture.Store().CreateAsync(fixture.Job); + await fixture.Store().SaveAsync(second with { State = PublishJobState.Succeeded, CleanupCompleted = true }); + + Assert.Equal(second.JobId, Assert.Single(await fixture.Store().ListAsync()).JobId); + Assert.Null(await fixture.Store().GetAsync("../../config")); + } + + [Fact] + public async Task IncompleteCheckpointFailsClosedWithoutPreventingApplicationStartup() + { + using var fixture = new Fixture(); + var record = await fixture.Store().CreateAsync(fixture.Job); + await fixture.Store().SaveAsync(record with { State = PublishJobState.Running, Prepared = true }); + + await Assert.ThrowsAsync(() => fixture.Store().ListAsync()); + using var queue = fixture.Queue(); + await queue.StartAsync(CancellationToken.None); + await queue.StopAsync(CancellationToken.None); + Assert.Empty(fixture.Kubo.Requests); + } + + private sealed class Fixture : IDisposable + { + private readonly string _directory = Path.Combine(Path.GetTempPath(), "truthgate-publication-tests-" + Guid.NewGuid().ToString("N")); + private readonly PublishQueueOptions _options; + public readonly PublishingKubo Kubo = new(); + public readonly PublishingConfig Config; + public readonly IConfiguration Configuration = new ConfigurationBuilder().Build(); + public readonly string Leaf = "test-" + Guid.NewGuid().ToString("N") + ".example"; + public string Stage => $"/staging/sites/{Leaf}/upload"; + public string Site => $"/production/sites/{Leaf}"; + public string Pointer => $"/production/pinned/tgp-{Leaf}"; + public PublishJob Job => new(Leaf, Leaf, "tgp-" + Leaf, Stage, "test"); + + public Fixture(PublishQueueOptions? options = null) + { + _options = options ?? new(); + _options.StorePath = _directory; + Config = new(new Config { Domains = [new EdgeDomain { Domain = Leaf, SiteFolderLeaf = Leaf, TgpFolderLeaf = "tgp-" + Leaf }] }, Path.Combine(_directory, "config.json")); + } + public FilePublishJobStore Store() => new(Config, Options.Create(_options)); + public PublishQueue Queue() => new(Kubo, new PublishingKeys(), Config, NullLogger.Instance, + Store(), Options.Create(_options), Configuration); + public void Dispose() + { + Kubo.Dispose(); + if (Directory.Exists(_directory)) Directory.Delete(_directory, recursive: true); + } + } +} diff --git a/TruthGate-Web/TruthGate-Web.Tests/PublishUploadTests.cs b/TruthGate-Web/TruthGate-Web.Tests/PublishUploadTests.cs new file mode 100644 index 0000000..d915959 --- /dev/null +++ b/TruthGate-Web/TruthGate-Web.Tests/PublishUploadTests.cs @@ -0,0 +1,104 @@ +using System.Text; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using TruthGate_Web.Models; +using TruthGate_Web.Services; +using Xunit; + +namespace TruthGate_Web.Tests; + +public sealed class PublishUploadTests +{ + [Fact] + public async Task QuotedMultipartNamesAndRawAssetFolderSurvivePublication() + { + using var fixture = new Fixture(); + const string boundary = "truthgate-upload-test"; + var body = string.Join("", new[] + { + $"--{boundary}\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"index.html\"\r\nContent-Type: text/html\r\n\r\nsite\r\n", + $"--{boundary}\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"raw/asset.txt\"\r\nContent-Type: text/plain\r\n\r\nasset\r\n", + $"--{boundary}--\r\n" + }); + await using var stream = new MemoryStream(Encoding.UTF8.GetBytes(body)); + var (jobId, count) = await fixture.Service.PublishFromMultipartStreamAsync(fixture.Domain, new MultipartReader(boundary, stream), CancellationToken.None); + + await fixture.Queue.ProcessAvailableOnceAsync(CancellationToken.None); + + Assert.Equal(2, count); + Assert.Equal(PublishJobState.Succeeded, (await fixture.Queue.GetStatusAsync(jobId))!.State); + Assert.Equal("asset", fixture.Kubo.Files[$"/production/sites/{fixture.Domain}/raw/asset.txt"]); + Assert.DoesNotContain(fixture.Kubo.Directories, path => path.StartsWith($"/staging/uploads/{fixture.Domain}/", StringComparison.Ordinal)); + } + + [Fact] + public async Task InvalidStreamedUploadCleansBothStagingTreesAndIsNeverAccepted() + { + using var fixture = new Fixture(); + const string boundary = "truthgate-upload-test"; + var body = $"--{boundary}\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"readme.txt\"\r\n\r\nno index\r\n--{boundary}--\r\n"; + await using var stream = new MemoryStream(Encoding.UTF8.GetBytes(body)); + + await Assert.ThrowsAsync(() => fixture.Service.PublishFromMultipartStreamAsync( + fixture.Domain, new MultipartReader(boundary, stream), CancellationToken.None)); + + Assert.Empty(await fixture.Queue.GetRecentAsync(fixture.Domain)); + Assert.DoesNotContain(fixture.Kubo.Directories, path => path.StartsWith($"/staging/uploads/{fixture.Domain}/", StringComparison.Ordinal)); + Assert.DoesNotContain(fixture.Kubo.Directories, path => path.StartsWith($"/staging/sites/{fixture.Domain}/", StringComparison.Ordinal)); + } + + [Fact] + public async Task BrowserAdapterPreservesZeroLengthFiles() + { + using var fixture = new Fixture(); + var files = new (IBrowserFile File, string RelPath)[] + { + (new BrowserFile("index.html", "site"), "index.html"), + (new BrowserFile("empty.txt", ""), "empty.txt") + }; + var (jobId, count) = await fixture.Service.PublishFromBrowserFilesAsync(fixture.Domain, files, CancellationToken.None); + + await fixture.Queue.ProcessAvailableOnceAsync(CancellationToken.None); + + Assert.Equal(2, count); + Assert.Equal(PublishJobState.Succeeded, (await fixture.Queue.GetStatusAsync(jobId))!.State); + Assert.Equal("", fixture.Kubo.Files[$"/production/sites/{fixture.Domain}/empty.txt"]); + } + + private sealed class BrowserFile(string name, string content) : IBrowserFile + { + public string Name => name; + public long Size => Encoding.UTF8.GetByteCount(content); + public DateTimeOffset LastModified => DateTimeOffset.UtcNow; + public string ContentType => "application/octet-stream"; + public Stream OpenReadStream(long maxAllowedSize = 512000, CancellationToken cancellationToken = default) + => new MemoryStream(Encoding.UTF8.GetBytes(content)); + } + + private sealed class Fixture : IDisposable + { + private readonly string _directory = Path.Combine(Path.GetTempPath(), "truthgate-upload-tests-" + Guid.NewGuid().ToString("N")); + public string Domain { get; } = "upload-" + Guid.NewGuid().ToString("N") + ".example"; + public PublishingKubo Kubo { get; } = new(); + public PublishQueue Queue { get; } + public TruthGatePublishService Service { get; } + public Fixture() + { + var config = new PublishingConfig(new Config { Domains = [new EdgeDomain { Domain = Domain }] }, Path.Combine(_directory, "config.json")); + var keys = new PublishingKeys(); + var options = Options.Create(new PublishQueueOptions { StorePath = _directory }); + var configuration = new ConfigurationBuilder().Build(); + Queue = new(Kubo, keys, config, NullLogger.Instance, new FilePublishJobStore(config, options), options, configuration); + Service = new(config, Queue, Kubo, keys, configuration); + } + public void Dispose() + { + Queue.Dispose(); + Kubo.Dispose(); + if (Directory.Exists(_directory)) Directory.Delete(_directory, recursive: true); + } + } +} diff --git a/TruthGate-Web/TruthGate-Web.Tests/PublishingPresentationTests.cs b/TruthGate-Web/TruthGate-Web.Tests/PublishingPresentationTests.cs new file mode 100644 index 0000000..ed2bb2d --- /dev/null +++ b/TruthGate-Web/TruthGate-Web.Tests/PublishingPresentationTests.cs @@ -0,0 +1,123 @@ +using System.Diagnostics; +using System.Text.Json; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using TruthGate_Web.Models; +using TruthGate_Web.Services; +using TruthGate_Web.Utils; +using Xunit; + +namespace TruthGate_Web.Tests; + +public sealed class PublishingPresentationTests +{ + [Theory] + [InlineData("renamed.example")] + [InlineData("peer1.ipns.example")] + public void RenamedAndWildcardHostsUseTheSamePersistedLeafAndConfiguredRoot(string host) + { + var domain = new EdgeDomain { Domain = "renamed.example", SiteFolderLeaf = "original.example", IpnsPeerId = "peer1" }; + var config = new PublishingConfig(new Config + { + Domains = [domain], IpnsWildCardSubDomain = new() { WildCardSubDomain = "ipns.example" } + }, "/unused/config.json"); + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { ["SitesRootBasePath"] = "custom/websites" }).Build(); + using var services = new ServiceCollection().AddSingleton(config) + .AddSingleton(configuration) + .AddSingleton(new PublishingHostEnvironment()).BuildServiceProvider(); + var context = new DefaultHttpContext { RequestServices = services }; + context.Request.Host = new HostString(host); + + Assert.Equal("/custom/websites/original.example", DomainHelpers.GetMappedDomain(context)); + } + + [Theory] + [InlineData("https://app.example/", false)] + [InlineData("https://peer1.ipns.example/", false)] + [InlineData("https://app.example/?name='quoted'", false)] + [InlineData("https://app.example/", true)] + public async Task GeneratedTgpScriptProbesConfiguredOriginOrUsesCompanion(string origin, bool companion) + { + // Run the actual generated JavaScript. A missing helper was swallowed by its inner catch, + // so string matching or a C# template compilation test cannot detect the broken branch. + const string script = """ + const vm = require('node:vm'); + const assert = require('node:assert/strict'); + let input = ''; + process.stdin.setEncoding('utf8'); + process.stdin.on('data', value => input += value); + process.stdin.on('end', async () => { + try { + const { html, origin, companion } = JSON.parse(input); + const calls = [], mounted = [], navigated = []; + const location = { + hostname: 'public-gateway.example', origin: 'https://public-gateway.example', + pathname: '/ipns/peer/index.html', href: 'https://public-gateway.example/ipns/peer/index.html', + replace: url => navigated.push(url) + }; + const document = { + body: { replaceChildren: child => mounted.push(child) }, + createTextNode: value => ({ text: value }), + createElement: tag => ({ tag, style: {}, setAttribute() {}, addEventListener() {} }) + }; + const context = { + location, document, window: companion ? { ipfsCompanion: {} } : {}, + URL, URLSearchParams, AbortController, + setTimeout: () => 1, clearTimeout() {}, + fetch: async (url, options = {}) => { + calls.push({ url, method: options.method || 'GET' }); + return { ok: true, json: async () => ({ tgp: 1, current: 'bafy-application' }) }; + } + }; + const js = html.match(/"; - - - static string RuntimePrefixScript(string basePrefix) - { - return $@" -"; + +"""; } - - - - } - } diff --git a/TruthGate-Web/TruthGate-Web/Utils/IpfsIntrospection.cs b/TruthGate-Web/TruthGate-Web/Utils/IpfsIntrospection.cs index 648104f..32d4529 100644 --- a/TruthGate-Web/TruthGate-Web/Utils/IpfsIntrospection.cs +++ b/TruthGate-Web/TruthGate-Web/Utils/IpfsIntrospection.cs @@ -1,51 +1,37 @@ -namespace TruthGate_Web.Utils +namespace TruthGate_Web.Utils; + +public static class IpfsIntrospection { - public static class IpfsIntrospection + public static async Task TryGetWebUiCidAsync(string webUiUrl, IHttpClientFactory clientFactory, CancellationToken ct) { - public static async Task TryGetWebUiCidAsync( - string webUiUrl, - IHttpClientFactory clientFactory, - CancellationToken ct) + // Only the local node may identify the trusted Web UI. Do not follow redirects. + var client = clientFactory.CreateClient("TruthGate.Gateway"); + using var request = new HttpRequestMessage(HttpMethod.Head, webUiUrl); + request.Headers.CacheControl = new() { NoCache = true }; + using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct); + var status = (int)response.StatusCode; + if (!response.IsSuccessStatusCode && status is not (301 or 302 or 303 or 307 or 308)) return null; + if (response.Headers.Location is { } location) { - var client = clientFactory.CreateClient(); - - using var req = new HttpRequestMessage(HttpMethod.Head, webUiUrl); - // Avoid conditional caching so we always get the canonical headers - req.Headers.TryAddWithoutValidation("Cache-Control", "no-cache"); - req.Headers.TryAddWithoutValidation("Pragma", "no-cache"); - - using var res = await client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct); - if (!res.IsSuccessStatusCode) return null; - - // 1) Prefer X-Ipfs-Roots (cleanest) - if (res.Headers.TryGetValues("X-Ipfs-Roots", out var roots)) - { - var cid = roots.FirstOrDefault()?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).FirstOrDefault(); - if (!string.IsNullOrWhiteSpace(cid)) return cid; - } - - // 2) Fallback: X-Ipfs-Path: /ipfs//... - if (res.Headers.TryGetValues("X-Ipfs-Path", out var paths)) - { - var p = paths.FirstOrDefault(); - // Expected form: /ipfs//... - if (!string.IsNullOrWhiteSpace(p)) - { - var parts = p.Split('/', StringSplitOptions.RemoveEmptyEntries); - if (parts.Length >= 2 && parts[0].Equals("ipfs", StringComparison.OrdinalIgnoreCase)) - return parts[1]; - } - } - - // 3) Last resort: ETag often equals the root CID for immutable assets - if (res.Headers.ETag is { Tag: { } etag }) - { - var trimmed = etag.Trim('"'); - if (!string.IsNullOrWhiteSpace(trimmed)) return trimmed; - } - - return null; + var path = location.IsAbsoluteUri ? location.AbsolutePath : location.OriginalString.Split('?', '#')[0]; + var cid = FromPath(path); + if (cid is not null) return cid; + } + if (response.Headers.TryGetValues("X-Ipfs-Roots", out var roots)) + { + var cid = roots.SelectMany(x => x.Split(',', StringSplitOptions.TrimEntries)).FirstOrDefault(ContentIdentifier.IsCid); + if (cid is not null) return cid; } + if (response.Headers.TryGetValues("X-Ipfs-Path", out var paths)) + foreach (var path in paths) + if (FromPath(path) is { } cid) return cid; + var etag = response.Headers.ETag?.Tag.Trim('"'); + return ContentIdentifier.IsCid(etag) ? etag : null; } + private static string? FromPath(string path) + { + var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries); + return parts.Length >= 2 && parts[0] == "ipfs" && ContentIdentifier.IsCid(parts[1]) ? parts[1] : null; + } } diff --git a/TruthGate-Web/TruthGate-Web/Utils/RequestHelpers.cs b/TruthGate-Web/TruthGate-Web/Utils/RequestHelpers.cs index be43e38..91e5d21 100644 --- a/TruthGate-Web/TruthGate-Web/Utils/RequestHelpers.cs +++ b/TruthGate-Web/TruthGate-Web/Utils/RequestHelpers.cs @@ -1,17 +1,11 @@ -using System.Security.Cryptography; +using System.Security.Cryptography; using System.Text; namespace TruthGate_Web.Utils { public static class RequestHelpers { - static bool LooksLikeCid(string seg) - { - if (string.IsNullOrWhiteSpace(seg)) return false; - // very lightweight check: CIDv0 starts with Qm, CIDv1 (base32) starts with baf... - return seg.StartsWith("Qm", StringComparison.Ordinal) - || seg.StartsWith("baf", StringComparison.OrdinalIgnoreCase); - } + static bool LooksLikeCid(string seg) => ContentIdentifier.IsCid(seg); public static string? ExtractCidFromReferer(HttpRequest req) { @@ -71,15 +65,23 @@ public static bool IsApiRequest(HttpRequest req) public static string CombineTarget(string prefix, string rest, HttpContext ctx) { - var q = ctx.Request.QueryString.HasValue ? ctx.Request.QueryString.Value : ""; - return $"http://127.0.0.1:5001/{prefix}/{rest}{q}"; + var legacyQueryCredential = TruthGate_Web.Security.ApiKeyAuthentication.Authenticate(ctx).UsesLegacyQueryKey; + // Use the same parsed credential decision as admission. Blank/irrelevant + // headers must not turn a legacy query credential into a forwarded Kubo argument. + var query = QueryString.Create(ctx.Request.Query.Where(pair => + !pair.Key.Equals("api_key", StringComparison.OrdinalIgnoreCase) && + (!legacyQueryCredential || !pair.Key.Equals("key", StringComparison.OrdinalIgnoreCase)))); + return $"http://127.0.0.1:5001/{prefix}/{rest}{query}"; } public static string CombineTargetHttp(string prefix, string rest, HttpContext ctx, int httpPort) - { - var q = ctx.Request.QueryString.HasValue ? ctx.Request.QueryString.Value : ""; - return $"http://127.0.0.1:{httpPort}/{prefix}/{rest}{q}"; - } + => $"http://127.0.0.1:{httpPort}/{prefix}/{rest}{ContentQuery(ctx.Request)}"; + + public static QueryString ContentQuery(HttpRequest request) => QueryString.Create(request.Query.Where(pair => + !pair.Key.Equals("api_key", StringComparison.OrdinalIgnoreCase) && + !pair.Key.Equals("key", StringComparison.OrdinalIgnoreCase) && + !pair.Key.Equals("tgcid", StringComparison.OrdinalIgnoreCase) && + !pair.Key.Equals("tgipns", StringComparison.OrdinalIgnoreCase))); /// /// If the incoming request path is missing the IPNS name, try to recover it diff --git a/TruthGate-Web/TruthGate-Web/Utils/TgpTemplates.cs b/TruthGate-Web/TruthGate-Web/Utils/TgpTemplates.cs index 5b52556..fb05850 100644 --- a/TruthGate-Web/TruthGate-Web/Utils/TgpTemplates.cs +++ b/TruthGate-Web/TruthGate-Web/Utils/TgpTemplates.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using System.Text.Json; namespace TruthGate_Web.Utils { @@ -22,7 +22,7 @@ public static string IndexHtml(string? overrideUrl = null) => $@"