From 61aa1f851d38ae92cadf999801722554ce1b8977 Mon Sep 17 00:00:00 2001 From: Magic <131926685+magiccodingman@users.noreply.github.com> Date: Sat, 25 Jul 2026 18:09:18 -0400 Subject: [PATCH 1/3] Fix connected IPNS version pruning --- .../IpnsVersionRetentionTests.cs | 144 ++++++++++++ .../TruthGate-Web/Properties/AssemblyInfo.cs | 3 + .../Services/IpnsUpdateWorker.cs | 125 ++++------ .../Services/IpnsVersionRetention.cs | 218 ++++++++++++++++++ 4 files changed, 410 insertions(+), 80 deletions(-) create mode 100644 TruthGate-Web/TruthGate-Web.Tests/IpnsVersionRetentionTests.cs create mode 100644 TruthGate-Web/TruthGate-Web/Properties/AssemblyInfo.cs create mode 100644 TruthGate-Web/TruthGate-Web/Services/IpnsVersionRetention.cs diff --git a/TruthGate-Web/TruthGate-Web.Tests/IpnsVersionRetentionTests.cs b/TruthGate-Web/TruthGate-Web.Tests/IpnsVersionRetentionTests.cs new file mode 100644 index 0000000..60f7445 --- /dev/null +++ b/TruthGate-Web/TruthGate-Web.Tests/IpnsVersionRetentionTests.cs @@ -0,0 +1,144 @@ +using TruthGate_Web.Services; + +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("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/Properties/AssemblyInfo.cs b/TruthGate-Web/TruthGate-Web/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..6872647 --- /dev/null +++ b/TruthGate-Web/TruthGate-Web/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("TruthGate-Web.Tests")] diff --git a/TruthGate-Web/TruthGate-Web/Services/IpnsUpdateWorker.cs b/TruthGate-Web/TruthGate-Web/Services/IpnsUpdateWorker.cs index 634f914..f933114 100644 --- a/TruthGate-Web/TruthGate-Web/Services/IpnsUpdateWorker.cs +++ b/TruthGate-Web/TruthGate-Web/Services/IpnsUpdateWorker.cs @@ -1,9 +1,8 @@ -using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; using System.Collections.Concurrent; using System.Text; using System.Text.Json; -using System.Text.RegularExpressions; using TruthGate_Web.Endpoints; using TruthGate_Web.Models; using TruthGate_Web.Utils; @@ -43,11 +42,10 @@ public sealed class IpnsUpdateWorker : BackgroundService, IIpnsUpdateService private readonly IpnsUpdateOptions _opts; private readonly IApiKeyProvider _keys; - private static readonly Regex VersionRx = new(@"-v(?\d+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); - private const string ManagedRoot = "/production/pinned"; private const string StagingRoot = "/production/.staging/ipns"; - private const string TgpMetaFile = "tgp.json"; // lives in each version folder + private const string TgpPointerFile = "tgp.json"; + private const string LegacyTgpMetaFile = ".tgp-meta.json"; // concurrency private readonly SemaphoreSlim _globalSlots; @@ -79,34 +77,13 @@ public IpnsUpdateWorker( _globalSlots = new SemaphoreSlim(_opts.MaxConcurrency, _opts.MaxConcurrency); } - private sealed record VersionEntry(int N, string Name, string Path, string Cid, bool IsConnected); - - private async Task<(VersionEntry? Pointer, VersionEntry? Connected)> GetLatestVersionPairAsync(string name, CancellationToken ct) + private async Task<(IpnsVersionRetention.VersionEntry? Pointer, IpnsVersionRetention.VersionEntry? Connected)> GetLatestVersionPairAsync( + string name, + CancellationToken ct) { var children = await ListMfsChildrenAsync(ManagedRoot, ct); - var prefix = $"{name}-v"; - VersionEntry? latestPointer = null; - VersionEntry? latestConnected = null; - - foreach (var kv in children) - { - if (!kv.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue; - var m = VersionRx.Match(kv.Key); - if (!m.Success || !int.TryParse(m.Groups["n"].Value, out var n)) continue; - - var isConnected = kv.Key.EndsWith("-connected", StringComparison.OrdinalIgnoreCase); - var entry = new VersionEntry(n, kv.Key, kv.Value.Path, kv.Value.Cid, isConnected); - - if (isConnected) - { - if (latestConnected is null || n > latestConnected.N) latestConnected = entry; - } - else - { - if (latestPointer is null || n > latestPointer.N) latestPointer = entry; - } - } - return (latestPointer, latestConnected); + var latest = IpnsVersionRetention.GetLatestPointerPair(name, children); + return (latest?.Pointer, latest?.Connected); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) @@ -338,13 +315,6 @@ private SemaphoreSlim GetKeyLock(string name) => _perKeyLocks.GetOrAdd(name ?? string.Empty, _ => new SemaphoreSlim(1, 1)); // ---------- TGP helpers ---------- - private sealed class TgpMeta - { - public string Kind { get; set; } = "tgp"; - public string? PointerCid { get; set; } - public string? TargetCid { get; set; } - } - private async Task TryReadTgpTargetCidAsync(string pointerCid, CancellationToken ct) { try @@ -484,16 +454,7 @@ private async Task PinRmRecursiveAsync(string cid, CancellationToken ct) private async Task ComputeNextVersionAsync(string name, CancellationToken ct) { var children = await ListMfsChildrenAsync(ManagedRoot, ct); - var prefix = $"{name}-v"; - var max = 0; - foreach (var k in children.Keys) - { - if (!k.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue; - var m = VersionRx.Match(k); - if (m.Success && int.TryParse(m.Groups["n"].Value, out var n)) - max = Math.Max(max, n); - } - return max + 1; + return IpnsVersionRetention.ComputeNextVersion(name, children.Keys); } private async Task FilesWriteTextAsync(string mfsPath, string text, CancellationToken ct) { @@ -513,48 +474,52 @@ private async Task FilesWriteTextAsync(string mfsPath, string text, Cancellation private async Task RemoveAllButLatestAsync(string name, CancellationToken ct) { var children = await ListMfsChildrenAsync(ManagedRoot, ct); - var prefix = $"{name}-v"; - var versions = new List<(int n, string path, string cid)>(); - foreach (var kv in children) + var pairs = IpnsVersionRetention.GroupVersions(name, children); + var latest = IpnsVersionRetention.GetLatestPointerPair(pairs); + if (latest is null) return; + + var targetCidsByVersion = new Dictionary(); + foreach (var pair in pairs) { - if (!kv.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue; - var m = VersionRx.Match(kv.Key); - if (!m.Success || !int.TryParse(m.Groups["n"].Value, out var n)) continue; - versions.Add((n, kv.Value.Path, kv.Value.Cid)); + string? targetCid = pair.Connected?.Cid; + if (string.IsNullOrWhiteSpace(targetCid) && pair.Pointer is not null) + { + var tgpJson = await FilesReadAllTextAsync($"{pair.Pointer.Path}/{TgpPointerFile}", ct); + targetCid = IpnsVersionRetention.TryReadTgpCurrentCid(tgpJson); + + if (string.IsNullOrWhiteSpace(targetCid)) + { + var legacyJson = await FilesReadAllTextAsync($"{pair.Pointer.Path}/{LegacyTgpMetaFile}", ct); + targetCid = IpnsVersionRetention.TryReadLegacyTargetCid(legacyJson); + } + } + + targetCidsByVersion[pair.Version] = targetCid; } - if (versions.Count <= 1) return; - var latest = versions.OrderByDescending(v => v.n).First(); - foreach (var v in versions.Where(v => v.n != latest.n)) + var plan = IpnsVersionRetention.BuildPrunePlan(pairs, latest.Version, targetCidsByVersion); + + foreach (var path in plan.PathsToRemove) { try { - // Read sidecar to learn any extra CIDs (TGP target) to unpin - string? metaJson = await FilesReadAllTextAsync($"{v.path}/{TgpMetaFile}", ct); - string? tgpTarget = null; - if (!string.IsNullOrWhiteSpace(metaJson)) - { - try - { - var m = JsonSerializer.Deserialize(metaJson); - if (m?.TargetCid is string s && !string.IsNullOrWhiteSpace(s)) - tgpTarget = s.Trim(); - } - catch { /* ignore */ } - } + await FilesRmRecursiveAsync(path, ct); + } + catch (Exception ex) + { + _log.LogWarning(ex, "Failed to remove old IPNS version path {Path} for {Name}.", path, name); + } + } - // Remove folder then unpin both pointer and (if present) target - await FilesRmRecursiveAsync(v.path, ct); - await PinRmRecursiveAsync(v.cid, ct); - if (!string.IsNullOrWhiteSpace(tgpTarget)) - { - try { await PinRmRecursiveAsync(tgpTarget!, ct); } - catch (Exception ex) { _log.LogWarning(ex, "Failed to unpin TGP target for {Name}-v{Version}", name, v.n); } - } + foreach (var cid in plan.CidsToUnpin) + { + try + { + await PinRmRecursiveAsync(cid, ct); } catch (Exception ex) { - _log.LogWarning(ex, "Failed to remove old version {Name}-v{Version}.", name, v.n); + _log.LogWarning(ex, "Failed to unpin old IPNS version CID {Cid} for {Name}.", cid, name); } } } diff --git a/TruthGate-Web/TruthGate-Web/Services/IpnsVersionRetention.cs b/TruthGate-Web/TruthGate-Web/Services/IpnsVersionRetention.cs new file mode 100644 index 0000000..cbca38b --- /dev/null +++ b/TruthGate-Web/TruthGate-Web/Services/IpnsVersionRetention.cs @@ -0,0 +1,218 @@ +using System.Globalization; +using System.Text.Json; + +namespace TruthGate_Web.Services; + +internal static class IpnsVersionRetention +{ + private const string ConnectedSuffix = "-connected"; + + internal sealed record VersionEntry( + int Version, + string Name, + string Path, + string Cid, + bool IsConnected); + + internal sealed class VersionPair + { + internal VersionPair(int version) => Version = version; + + internal int Version { get; } + internal VersionEntry? Pointer { get; set; } + internal VersionEntry? Connected { get; set; } + } + + internal sealed record PrunePlan( + IReadOnlyList PathsToRemove, + IReadOnlyList CidsToUnpin); + + internal static bool TryParseEntryName( + string trackedName, + string entryName, + out int version, + out bool isConnected) + { + version = 0; + isConnected = false; + + if (string.IsNullOrWhiteSpace(trackedName) || string.IsNullOrWhiteSpace(entryName)) + return false; + + var prefix = $"{trackedName}-v"; + if (!entryName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + return false; + + var versionText = entryName[prefix.Length..]; + if (versionText.EndsWith(ConnectedSuffix, StringComparison.OrdinalIgnoreCase)) + { + isConnected = true; + versionText = versionText[..^ConnectedSuffix.Length]; + } + + return versionText.Length > 0 + && int.TryParse( + versionText, + NumberStyles.None, + CultureInfo.InvariantCulture, + out version); + } + + internal static IReadOnlyList GroupVersions( + string trackedName, + IReadOnlyDictionary children) + { + var pairs = new SortedDictionary(); + + foreach (var child in children) + { + if (!TryParseEntryName(trackedName, child.Key, out var version, out var isConnected)) + continue; + + if (!pairs.TryGetValue(version, out var pair)) + { + pair = new VersionPair(version); + pairs.Add(version, pair); + } + + var entry = new VersionEntry( + version, + child.Key, + child.Value.Path, + child.Value.Cid, + isConnected); + + if (isConnected) + pair.Connected = entry; + else + pair.Pointer = entry; + } + + return pairs.Values.ToArray(); + } + + internal static VersionPair? GetLatestPointerPair( + string trackedName, + IReadOnlyDictionary children) + => GetLatestPointerPair(GroupVersions(trackedName, children)); + + internal static VersionPair? GetLatestPointerPair(IEnumerable pairs) + => pairs + .Where(pair => pair.Pointer is not null) + .OrderByDescending(pair => pair.Version) + .FirstOrDefault(); + + internal static int ComputeNextVersion(string trackedName, IEnumerable childNames) + { + var max = 0; + foreach (var childName in childNames) + { + if (TryParseEntryName(trackedName, childName, out var version, out _)) + max = Math.Max(max, version); + } + + return max + 1; + } + + internal static PrunePlan BuildPrunePlan( + IReadOnlyList pairs, + int retainedVersion, + IReadOnlyDictionary targetCidsByVersion) + { + var retained = pairs.FirstOrDefault(pair => pair.Version == retainedVersion) + ?? throw new ArgumentOutOfRangeException( + nameof(retainedVersion), + retainedVersion, + "The retained version must exist in the version set."); + + var retainedCids = new HashSet(StringComparer.OrdinalIgnoreCase); + AddCid(retainedCids, retained.Pointer?.Cid); + AddCid(retainedCids, retained.Connected?.Cid); + if (targetCidsByVersion.TryGetValue(retainedVersion, out var retainedTarget)) + AddCid(retainedCids, retainedTarget); + + var paths = new HashSet(StringComparer.OrdinalIgnoreCase); + var cids = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (var pair in pairs.Where(pair => pair.Version != retainedVersion)) + { + AddPath(paths, pair.Pointer?.Path); + AddPath(paths, pair.Connected?.Path); + + AddCandidateCid(cids, retainedCids, pair.Pointer?.Cid); + AddCandidateCid(cids, retainedCids, pair.Connected?.Cid); + if (targetCidsByVersion.TryGetValue(pair.Version, out var targetCid)) + AddCandidateCid(cids, retainedCids, targetCid); + } + + return new PrunePlan(paths.ToArray(), cids.ToArray()); + } + + internal static string? TryReadTgpCurrentCid(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + + try + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + if (!root.TryGetProperty("tgp", out var tgp) + || tgp.ValueKind != JsonValueKind.Number + || tgp.GetInt32() != 1 + || !root.TryGetProperty("current", out var current) + || current.ValueKind != JsonValueKind.String) + return null; + + return NormalizeCid(current.GetString()); + } + catch (JsonException) + { + return null; + } + } + + internal static string? TryReadLegacyTargetCid(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + + try + { + using var document = JsonDocument.Parse(json); + if (!document.RootElement.TryGetProperty("TargetCid", out var target) + || target.ValueKind != JsonValueKind.String) + return null; + + return NormalizeCid(target.GetString()); + } + catch (JsonException) + { + return null; + } + } + + private static string? NormalizeCid(string? value) + { + var cid = value?.Trim(); + if (string.IsNullOrWhiteSpace(cid)) return null; + return cid.StartsWith("/ipfs/", StringComparison.OrdinalIgnoreCase) + ? cid[6..] + : cid; + } + + private static void AddPath(ISet paths, string? path) + { + if (!string.IsNullOrWhiteSpace(path)) paths.Add(path); + } + + private static void AddCid(ISet cids, string? cid) + { + if (!string.IsNullOrWhiteSpace(cid)) cids.Add(cid.Trim()); + } + + private static void AddCandidateCid(ISet candidates, ISet retained, string? cid) + { + if (string.IsNullOrWhiteSpace(cid)) return; + cid = cid.Trim(); + if (!retained.Contains(cid)) candidates.Add(cid); + } +} From 9ad1449d7637340bed07667218d5bc2cadb606a2 Mon Sep 17 00:00:00 2001 From: Magic Coding Man Date: Tue, 1 Dec 2026 01:34:19 -0500 Subject: [PATCH 2/3] Fix browser RPC and WebUI discovery with Kubo 0.42 --- Test.TruthGate/Tests/GatewayRegressionTests.cs | 4 +++- TruthGate-Web/TruthGate-Web/Endpoints/IpfsEndpoints.cs | 3 ++- TruthGate-Web/TruthGate-Web/Utils/IpfsGateway.cs | 7 ++++++- docs/developer/audit-remediation.md | 10 ++++++++++ 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/Test.TruthGate/Tests/GatewayRegressionTests.cs b/Test.TruthGate/Tests/GatewayRegressionTests.cs index 4301fa1..bbdf9c9 100644 --- a/Test.TruthGate/Tests/GatewayRegressionTests.cs +++ b/Test.TruthGate/Tests/GatewayRegressionTests.cs @@ -59,6 +59,7 @@ public async Task UnknownLengthRequestBodyStreamsToKubo_WithoutForwardingCredent 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"; @@ -68,6 +69,7 @@ public async Task UnknownLengthRequestBodyStreamsToKubo_WithoutForwardingCredent { 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")); @@ -369,7 +371,7 @@ private static Task Reply(int status, string body = "", str Task.FromResult(new HttpResponseMessage((HttpStatusCode)status) { Content = new StringContent(body, Encoding.UTF8, type) }); private static Clients WebUiClients() => new((request, _) => { - if (request.RequestUri!.AbsolutePath == "/webui") + if (request.RequestUri!.AbsolutePath == "/webui/") { var response = new HttpResponseMessage(HttpStatusCode.Found) { Content = new StringContent("") }; response.Headers.Location = new Uri($"/ipfs/{Cid}/", UriKind.Relative); diff --git a/TruthGate-Web/TruthGate-Web/Endpoints/IpfsEndpoints.cs b/TruthGate-Web/TruthGate-Web/Endpoints/IpfsEndpoints.cs index e2be672..32f5463 100644 --- a/TruthGate-Web/TruthGate-Web/Endpoints/IpfsEndpoints.cs +++ b/TruthGate-Web/TruthGate-Web/Endpoints/IpfsEndpoints.cs @@ -112,7 +112,8 @@ await context.Response.WriteAsync( var cache = context.RequestServices.GetRequiredService(); const string key = "TruthGate:trusted-webui-cid"; if (cache.TryGetValue(key, out var cid)) return cid; - cid = await IpfsIntrospection.TryGetWebUiCidAsync("http://127.0.0.1:5001/webui", clients, context.RequestAborted); + // Kubo redirects /webui to /webui/ before advertising the Web UI CID. + cid = await IpfsIntrospection.TryGetWebUiCidAsync("http://127.0.0.1:5001/webui/", clients, context.RequestAborted); if (cid is not null) cache.Set(key, cid, TimeSpan.FromMinutes(5)); return cid; } diff --git a/TruthGate-Web/TruthGate-Web/Utils/IpfsGateway.cs b/TruthGate-Web/TruthGate-Web/Utils/IpfsGateway.cs index 7403e0e..3953d2e 100644 --- a/TruthGate-Web/TruthGate-Web/Utils/IpfsGateway.cs +++ b/TruthGate-Web/TruthGate-Web/Utils/IpfsGateway.cs @@ -574,9 +574,14 @@ public static async Task OpenResponseAsync(HttpContext cont var connectionHeaders = context.Request.Headers.Connection.ToString() .Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) .ToHashSet(StringComparer.OrdinalIgnoreCase); + var isKuboRpc = context.Request.Path.StartsWithSegments("/api/v0", StringComparison.OrdinalIgnoreCase); + // TruthGate validates browser requests at its own boundary. Kubo sees a + // server-to-server RPC without the browser's Origin or Referer. + if (isKuboRpc) request.Headers.UserAgent.ParseAdd("TruthGate"); foreach (var header in context.Request.Headers) { - if (header.Key.Equals("Host", StringComparison.OrdinalIgnoreCase) || + if ((isKuboRpc && header.Key.Equals("User-Agent", StringComparison.OrdinalIgnoreCase)) || + header.Key.Equals("Host", StringComparison.OrdinalIgnoreCase) || header.Key.Equals("Content-Length", StringComparison.OrdinalIgnoreCase) || IsHopByHopHeader(header.Key) || connectionHeaders.Contains(header.Key) || IsCredentialHeader(header.Key)) continue; if (!forwardConditionals && (header.Key.StartsWith("If-", StringComparison.OrdinalIgnoreCase) || diff --git a/docs/developer/audit-remediation.md b/docs/developer/audit-remediation.md index a45fc81..e407701 100644 --- a/docs/developer/audit-remediation.md +++ b/docs/developer/audit-remediation.md @@ -80,6 +80,16 @@ The .NET package references move from 10.0.10 to 10.0.15, with SQLitePCLRaw 2.1. Key validation is performed once per request and checks the rotating internal key before expensive configured hashes. Configuration readers deserialize a detached immutable snapshot outside the writer lock instead of repeatedly serializing the live graph. TLS contexts are cached rather than rebuilt for every handshake. Publication uses one final site CID after content mutation. Rate history and publication admission/history are bounded. These are structural improvements; this branch does not claim production throughput or memory benchmarks. +## Independent loopback acceptance + +The starting draft revision was `24cae7722d0d5d13aee79da58dc9a93ad3903df0`. The two follow-up fixes address real Kubo 0.42.0 behavior. TruthGate identifies the WebUI CID through Kubo's canonical `/webui/` endpoint. The management RPC proxy sends its own user agent after applying TruthGate's authentication and browser request checks. + +- **Build and regression tests.** Release builds, both test suites (130 tests total), the Kubo settings Boolean matrix, and the production-mode publish passed locally. +- **Browser and gateway.** Chrome signed in and out, loaded Blazor assets, and listed files via cookie-authenticated Kubo RPC. Raw IPFS navigation redirected to a separate HTTPS origin that served the fixture. Kubo WebUI 4.12.0 loaded 22 JavaScript responses, connected to the isolated node, and completed normal RPC calls. A file-directory creation sent through the WebUI's injected browser adapter returned HTTP 200. +- **TLS.** A separate OpenSSL process trusted only the local fixture root and verified the app's persisted intermediate chain and management hostname after restart. +- **Interrupted publish.** A loopback relay held Kubo's successful IPNS response. TruthGate was killed with its journal at `Running`, `Prepared`, and `PublishAttempted`. The restarted app completed the same job on attempt two, with unchanged desired CIDs and completed staging cleanup. The old and new site roots remained recursively pinned, the mapped site served the recovered release, and a second isolated Kubo peer fetched its immutable index. +- **Bounded upload.** A 64 MiB browser multipart upload through the loopback relay returned HTTP 202 after 20.7 seconds and reached `Succeeded` about 1.5 seconds later. The sampled app RSS was 137 MiB at the start of browser automation and peaked at 238 MiB. This sample includes browser-management requests and publication work and represents one local fixture. + ## Acceptance work for the next reviewer The automated suites use real local TLS, SQLite and ASP.NET middleware, with a deterministic HTTP implementation of Kubo for failure injection. They do not replace an appliance run with real Kubo, browsers, ACME and multiple external peers. Review the following on this branch before merging/deploying: From 769096c89829f2955445be031ccc231c41e7c162 Mon Sep 17 00:00:00 2001 From: Magic Coding Man Date: Tue, 1 Dec 2026 01:40:44 -0500 Subject: [PATCH 3/3] Refresh authorization inside interactive management pages --- .../TruthGate-Web/Components/Pages/Home.razor | 4 ++-- .../TruthGate-Web/Components/Pages/Pinned.razor | 2 ++ .../Components/Pages/PinnedIpns.razor | 2 ++ .../Components/Pages/Settings/ApiKeys.razor | 3 +++ .../Components/Pages/Settings/Domains.razor | 2 ++ .../Components/Pages/Settings/IpBansPage.razor | 2 ++ .../Components/Pages/Settings/SettingsPage.razor | 2 ++ .../Components/Pages/Settings/UserSettings.razor | 2 ++ .../Components/Shared/ManagementSessionView.razor | 15 +++++++++++++++ docs/developer/audit-remediation.md | 6 +++--- 10 files changed, 35 insertions(+), 5 deletions(-) create mode 100644 TruthGate-Web/TruthGate-Web/Components/Shared/ManagementSessionView.razor diff --git a/TruthGate-Web/TruthGate-Web/Components/Pages/Home.razor b/TruthGate-Web/TruthGate-Web/Components/Pages/Home.razor index 39e9e07..a91c493 100644 --- a/TruthGate-Web/TruthGate-Web/Components/Pages/Home.razor +++ b/TruthGate-Web/TruthGate-Web/Components/Pages/Home.razor @@ -3,6 +3,7 @@ @using TruthGate_Web.Models @using TruthGate_Web.Utils + Dashboard
@@ -61,6 +62,5 @@
- - +
diff --git a/TruthGate-Web/TruthGate-Web/Components/Pages/Pinned.razor b/TruthGate-Web/TruthGate-Web/Components/Pages/Pinned.razor index c57db2a..eee542e 100644 --- a/TruthGate-Web/TruthGate-Web/Components/Pages/Pinned.razor +++ b/TruthGate-Web/TruthGate-Web/Components/Pages/Pinned.razor @@ -12,6 +12,7 @@ @rendermode InteractiveServer @inject IJSRuntime JS +
Pinned Content @@ -138,6 +139,7 @@ + @code { private bool _loading = true; diff --git a/TruthGate-Web/TruthGate-Web/Components/Pages/PinnedIpns.razor b/TruthGate-Web/TruthGate-Web/Components/Pages/PinnedIpns.razor index f7f1034..09d7bd7 100644 --- a/TruthGate-Web/TruthGate-Web/Components/Pages/PinnedIpns.razor +++ b/TruthGate-Web/TruthGate-Web/Components/Pages/PinnedIpns.razor @@ -16,6 +16,7 @@ @rendermode InteractiveServer @inject IApiKeyProvider Keys +
Pinned IPNS @@ -198,6 +199,7 @@ + @code { private const string ManagedRoot = "/production/pinned"; diff --git a/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/ApiKeys.razor b/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/ApiKeys.razor index 5d7aaf9..ce7d6b7 100644 --- a/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/ApiKeys.razor +++ b/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/ApiKeys.razor @@ -7,6 +7,7 @@ @inject ISnackbar Snackbar @rendermode InteractiveServer +
API Keys @@ -41,6 +42,8 @@ + + @code { private List _keys = new(); diff --git a/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/Domains.razor b/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/Domains.razor index 97d6f5a..6e2f560 100644 --- a/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/Domains.razor +++ b/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/Domains.razor @@ -17,6 +17,7 @@ @inject IPublishQueue PublicationQueue @inject IConfiguration Configuration +
Domains @@ -140,6 +141,7 @@ + @code { diff --git a/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/IpBansPage.razor b/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/IpBansPage.razor index acb3adc..52ec3f4 100644 --- a/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/IpBansPage.razor +++ b/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/IpBansPage.razor @@ -10,6 +10,7 @@ @inject ISnackbar Snackbar @rendermode InteractiveServer + Settings @@ -197,6 +198,7 @@ + @code { // -------------------- BANS -------------------- diff --git a/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/SettingsPage.razor b/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/SettingsPage.razor index 18d491b..40473fe 100644 --- a/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/SettingsPage.razor +++ b/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/SettingsPage.razor @@ -5,6 +5,7 @@ @inject ISnackbar Snackbar @rendermode InteractiveServer + Settings @@ -54,6 +55,7 @@ + @code { private string? _wildcard; // stored without "*." diff --git a/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/UserSettings.razor b/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/UserSettings.razor index d929186..e691202 100644 --- a/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/UserSettings.razor +++ b/TruthGate-Web/TruthGate-Web/Components/Pages/Settings/UserSettings.razor @@ -8,6 +8,7 @@ @rendermode InteractiveServer +
@@ -54,6 +55,7 @@ + @code { diff --git a/TruthGate-Web/TruthGate-Web/Components/Shared/ManagementSessionView.razor b/TruthGate-Web/TruthGate-Web/Components/Shared/ManagementSessionView.razor new file mode 100644 index 0000000..5a55611 --- /dev/null +++ b/TruthGate-Web/TruthGate-Web/Components/Shared/ManagementSessionView.razor @@ -0,0 +1,15 @@ +@using Microsoft.AspNetCore.Components.Authorization + + + + @ChildContent + + + + + + +@code { + [Parameter, EditorRequired] + public RenderFragment ChildContent { get; set; } = default!; +} diff --git a/docs/developer/audit-remediation.md b/docs/developer/audit-remediation.md index e407701..7d377ca 100644 --- a/docs/developer/audit-remediation.md +++ b/docs/developer/audit-remediation.md @@ -85,14 +85,14 @@ Key validation is performed once per request and checks the rotating internal ke The starting draft revision was `24cae7722d0d5d13aee79da58dc9a93ad3903df0`. The two follow-up fixes address real Kubo 0.42.0 behavior. TruthGate identifies the WebUI CID through Kubo's canonical `/webui/` endpoint. The management RPC proxy sends its own user agent after applying TruthGate's authentication and browser request checks. - **Build and regression tests.** Release builds, both test suites (130 tests total), the Kubo settings Boolean matrix, and the production-mode publish passed locally. -- **Browser and gateway.** Chrome signed in and out, loaded Blazor assets, and listed files via cookie-authenticated Kubo RPC. Raw IPFS navigation redirected to a separate HTTPS origin that served the fixture. Kubo WebUI 4.12.0 loaded 22 JavaScript responses, connected to the isolated node, and completed normal RPC calls. A file-directory creation sent through the WebUI's injected browser adapter returned HTTP 200. +- **Browser and gateway.** Chrome signed in and out, verified that rotating an account password redirected an already-open interactive Users page to login after 27 seconds, loaded Blazor assets, and listed files via cookie-authenticated Kubo RPC. Raw IPFS navigation redirected to a separate HTTPS origin that served the fixture. Kubo WebUI 4.12.0 loaded 22 JavaScript responses, connected to the isolated node, and completed normal RPC calls. A file-directory creation sent through the WebUI's injected browser adapter returned HTTP 200. - **TLS.** A separate OpenSSL process trusted only the local fixture root and verified the app's persisted intermediate chain and management hostname after restart. - **Interrupted publish.** A loopback relay held Kubo's successful IPNS response. TruthGate was killed with its journal at `Running`, `Prepared`, and `PublishAttempted`. The restarted app completed the same job on attempt two, with unchanged desired CIDs and completed staging cleanup. The old and new site roots remained recursively pinned, the mapped site served the recovered release, and a second isolated Kubo peer fetched its immutable index. -- **Bounded upload.** A 64 MiB browser multipart upload through the loopback relay returned HTTP 202 after 20.7 seconds and reached `Succeeded` about 1.5 seconds later. The sampled app RSS was 137 MiB at the start of browser automation and peaked at 238 MiB. This sample includes browser-management requests and publication work and represents one local fixture. +- **Bounded upload.** A 64 MiB browser multipart upload through the loopback relay returned HTTP 202 after 20.7 seconds and reached `Succeeded` about 1.5 seconds later. The sampled app RSS was 137 MiB at the start of browser automation and peaked at 238 MiB. This sample includes browser-management requests and publication work and represents one local fixture. A separate throttled request aborted after 16 chunks of 64 KiB and left publication history unchanged. ## Acceptance work for the next reviewer -The automated suites use real local TLS, SQLite and ASP.NET middleware, with a deterministic HTTP implementation of Kubo for failure injection. They do not replace an appliance run with real Kubo, browsers, ACME and multiple external peers. Review the following on this branch before merging/deploying: +The automated suites use real local TLS, SQLite and ASP.NET middleware, with a deterministic HTTP implementation of Kubo for failure injection. Independent loopback checks cover the cases recorded above. Complete the full acceptance matrix on this branch before merging or deploying: 1. Build and boot both production and development Docker images on AMD64 and ARM64. Recreate with persistent configuration, certificate, Kubo and publication-journal volumes. 2. Use separate management, mapped-site and raw-content gateway hosts. Verify login/logout, account revocation on an already open Blazor circuit, framework assets, Kubo WebUI file operations and CSRF headers in a real browser. Test the WebUI's actual module/network calls and CSP behavior.