Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 17 additions & 19 deletions .github/workflows/tls-lifecycle.yml
Original file line number Diff line number Diff line change
@@ -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:

Expand All @@ -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
31 changes: 19 additions & 12 deletions Publish.CLI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Net;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Net.Sockets;
Expand Down Expand Up @@ -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.");

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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;
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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 ""; }
}

Expand Down Expand Up @@ -443,7 +450,7 @@ sealed class Options

OPTIONAL:
--insecure Skip TLS certificate validation (like curl -k)
--batchSize <int> Files per request (default 0). Use 0 for one giant request.
--batchSize <int> Must be 0. Chunked publication sessions are not supported.
--timeoutSeconds <n> Whole-request timeout (default 604,800)
--verbose Print each file's relative name
-h | --help Show this help
Expand Down Expand Up @@ -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");
}

Expand All @@ -536,4 +543,4 @@ static string ExtractHost(string httpsUrl)
return u.Host;
}

}
}
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ 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)

### Native IPFS WebUI behind authentication

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

Expand Down
8 changes: 4 additions & 4 deletions Test.TruthGate/Test.TruthGate.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
Expand All @@ -12,9 +12,9 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.10">
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
98 changes: 32 additions & 66 deletions Test.TruthGate/Tests/AdminProtectedTests.cs
Original file line number Diff line number Diff line change
@@ -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());
}
}
Loading
Loading