From f32c9127a055bfc015254f57528badaa2bd21f38 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 17 Jun 2026 11:38:34 +0100 Subject: [PATCH] Validate bridge provenance against bifrost state --- README.md | 1 + docs/agent-transport.md | 1 + docs/bridge.md | 1 + .../Features/Bridge/BridgeActionService.cs | 121 ++++++++++++++++++ .../PlatformEndpointsTests.cs | 106 ++++++++++++++- 5 files changed, 228 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c071487..544796f 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ For the full staged roadmap, including contribution points, revenue share, patro - the same bridge URL/token pair lets `tools/dispatch-agent-requests.mjs` record `/dispatch/runs/*` receipts for launched Codex work, so Bifrost keeps a live run trail even when a turn fails - those hosted runtime receipt lanes are local-bridge-owned writes, not ordinary member-session writes: `/dispatch/runs/*`, `/transport/receipts`, and `/governance/receipts` now require the configured bridge token and do not inherit browser-user identity into agent activity rows - those hosted runtime receipts also validate linkage instead of accepting free-floating text: dispatch runs require an existing request-lane receipt for the same request id, governance promotion receipts require a known promoted dispatch request, and request-lane rows cannot silently drift to a different repo or agent identity midstream +- GitHub bridge actions that claim Bifrost-owned provenance now validate that provenance too: a `bifrost_agent_transport_request` source must point at a known request-lane request for the same repo, and governance-backed bridge actions must point at a known Bifrost topic instead of a decorative source string - Bifrost-dispatched Codex turns also inject Bifrost-owned GitHub gates through environment config: `git` and `gh` wrappers are prepended in `PATH`, a `pre-push` hook backs up raw Git pushes, raw `git push` stays blocked, and direct `gh` usage is limited to explicit read-only commands unless `tools/bifrost-bridge.mjs` authorizes the bridge-owned GitHub write path - dispatched Codex turns now default to `workspace-write` instead of full machine access, and the app-server sandbox policy disables network access unless the operator explicitly chooses a broader sandbox - `tools/agent-transport.mjs` also uses that bridge configuration to record `/transport/receipts` entries for queue, claim, release, and close events on the request lane diff --git a/docs/agent-transport.md b/docs/agent-transport.md index b3796c2..c49c6f5 100644 --- a/docs/agent-transport.md +++ b/docs/agent-transport.md @@ -128,6 +128,7 @@ Dispatch receipts should use Bifrost's own public persona in the Bifrost governa The dispatcher now tags those Discord receipts with the Bifrost request id as bridge provenance, and dispatched Codex turns inherit default bridge provenance environment variables so any explicit `tools/bifrost-bridge.mjs` crossing inside the turn can land on the same request trail without hand-carried flags. When `BIFROST_BRIDGE_BASE_URL` and `BIFROST_BRIDGE_TOKEN` are configured, the dispatcher also records `/dispatch/runs/*` receipts in the hosted app so Bifrost keeps a first-class run ledger for launch, completion, cancellation, and failure. Those hosted runtime receipt endpoints are owned by the local bridge token, not by ordinary member sessions. A signed-in member can govern work and request crossings, but they cannot POST `/dispatch/runs/*`, `/transport/receipts`, or `/governance/receipts` without the configured bridge token and pretend to be the worker runtime. Those hosted receipt endpoints now also cross-check each other. Dispatch starts require an existing request-lane receipt for the same request id, governance promotions that cite `dispatchRequestId` must point at a known request-lane request, and additional request-lane receipts for one request id cannot drift onto a different repo or agent identity. The ledger is still transitional, but it has stopped politely accepting shape-shifting runtime history. +That same Bifrost request provenance now matters at the GitHub crossing too. When a dispatched worker uses `tools/bifrost-bridge.mjs` with the inherited `bifrost_agent_transport_request` source, the hosted bridge checks that the cited request exists in the request-lane ledger and still belongs to the same repo before it authorizes the GitHub mutation. Those dispatched turns also inherit Bifrost-owned GitHub gates through environment config. `git` and `gh` wrappers are prepended in `PATH`, a `pre-push` hook backs up raw Git pushes, raw `git push` stays blocked inside dispatched work even with `--no-verify`, and direct `gh` usage is limited to explicit read-only commands unless the bridge explicitly authorizes the GitHub mutation it owns. Those dispatched turns also lock the local-only recovery hatches. `--allow-ungated-github`, `BIFROST_ALLOW_UNGATED_GITHUB`, `--allow-unreceipted-activity`, and `BIFROST_ALLOW_UNRECEIPTED_ACTIVITY` are refused inside dispatched work so an agent cannot quietly downgrade itself out of Bifrost's gate or receipt trail. Those dispatched turns also scrub ambient GitHub auth state from the child environment before the worker starts. `GH_TOKEN` and `GITHUB_TOKEN` are cleared, `gh` gets an isolated config directory, `git` gets an isolated global config plus non-interactive credential settings, and terminal prompts are disabled. That does not prove every imaginable direct-HTTP escape is impossible, but it removes the normal ambient credential path from dispatched work. diff --git a/docs/bridge.md b/docs/bridge.md index 1132f6f..007357c 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -79,6 +79,7 @@ This covers the other side of the swarm's work: topic opens, comments, approvals These runtime receipt lanes are not generic member write surfaces. In the current machine, `/dispatch/runs/*`, `/transport/receipts`, and `/governance/receipts` are owned by the configured local bridge token. Active members may govern and request bridge actions through the app, but they may not mint worker-history rows directly through a browser session and impersonate runtime activity. They also now validate linkage across the hosted ledger instead of accepting isolated claims. A dispatch run must point at an already-seen request-lane receipt for the same request id. A governance promotion receipt that cites `dispatchRequestId` must point at a known request-lane request. Repeated request-lane rows for one request id may add activity, but they may not quietly change the repo or agent identity the request belongs to. +GitHub bridge actions that cite Bifrost-owned provenance now validate that provenance too. If a bridge action says its source is `bifrost_agent_transport_request`, the hosted bridge checks that the request exists in the request-lane ledger and still belongs to the same repo. If a bridge action says its source is `bifrost_governance_topic` or legacy `governance_topic`, the hosted bridge checks that the topic exists in the governance receipt trail before authorizing the crossing. Current gate behavior: diff --git a/src/Bifrost.Web/Features/Bridge/BridgeActionService.cs b/src/Bifrost.Web/Features/Bridge/BridgeActionService.cs index 21f9696..ca55cfa 100644 --- a/src/Bifrost.Web/Features/Bridge/BridgeActionService.cs +++ b/src/Bifrost.Web/Features/Bridge/BridgeActionService.cs @@ -10,6 +10,10 @@ public sealed class BridgeActionService( AuditTrailService auditTrailService, TimeProvider timeProvider) { + private const string AgentTransportRequestSourceKind = "bifrost_agent_transport_request"; + private const string GovernanceTopicSourceKind = "bifrost_governance_topic"; + private const string LegacyGovernanceTopicSourceKind = "governance_topic"; + public async Task RequestAsync( BridgeActionRequest request, BridgeCaller caller, @@ -223,14 +227,131 @@ public sealed class BridgeActionService( return BridgePolicyDecision.Reject("Referenced motion does not exist."); } + var provenanceDecision = await EvaluateBifrostOwnedProvenanceAsync(request, cancellationToken); + if (provenanceDecision is not null) + { + return provenanceDecision; + } + return BridgePolicyDecision.Permit( caller.IsLocalBridge ? "Authorized through the configured local Bifrost bridge token and Bifrost policy." : "Authorized for an active Bifrost member through Bifrost policy."); } + private async Task EvaluateBifrostOwnedProvenanceAsync( + BridgeActionRequest request, + CancellationToken cancellationToken) + { + var sourceKind = NormalizeText(request.SourceKind); + if (string.IsNullOrWhiteSpace(sourceKind)) + { + return null; + } + + if (string.Equals(sourceKind, AgentTransportRequestSourceKind, StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrWhiteSpace(request.SourceId)) + { + return BridgePolicyDecision.Reject("Bifrost request-backed bridge actions must cite the request id as sourceId."); + } + + var linkedReceipt = await dbContext.AgentTransportReceipts + .AsNoTracking() + .Where(x => x.RequestId == request.SourceId) + .OrderByDescending(x => x.OccurredAtUtc) + .FirstOrDefaultAsync(cancellationToken); + + if (linkedReceipt is null) + { + return BridgePolicyDecision.Reject($"Bifrost request-backed bridge action references unknown request {request.SourceId}."); + } + + var repoMismatch = LinkedRepositoryMismatch( + request.TargetRepositoryFullName, + linkedReceipt.TargetRepositoryFullName, + linkedReceipt.TargetRepoName); + if (repoMismatch is not null) + { + return BridgePolicyDecision.Reject(repoMismatch); + } + + return null; + } + + if (string.Equals(sourceKind, GovernanceTopicSourceKind, StringComparison.OrdinalIgnoreCase) || + string.Equals(sourceKind, LegacyGovernanceTopicSourceKind, StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrWhiteSpace(request.SourceId)) + { + return BridgePolicyDecision.Reject("Bifrost governance-backed bridge actions must cite the topic id as sourceId."); + } + + var linkedReceipt = await dbContext.GovernanceActivityReceipts + .AsNoTracking() + .Where(x => x.TopicId == request.SourceId) + .OrderByDescending(x => x.OccurredAtUtc) + .FirstOrDefaultAsync(cancellationToken); + + if (linkedReceipt is null) + { + return BridgePolicyDecision.Reject($"Bifrost governance-backed bridge action references unknown topic {request.SourceId}."); + } + + var repoMismatch = LinkedRepositoryMismatch( + request.TargetRepositoryFullName, + string.Empty, + linkedReceipt.JurisdictionRepoName); + if (repoMismatch is not null) + { + return BridgePolicyDecision.Reject(repoMismatch); + } + } + + return null; + } + + private static string? LinkedRepositoryMismatch( + string targetRepositoryFullName, + string linkedTargetRepositoryFullName, + string linkedRepoName) + { + var normalizedTargetRepository = NormalizeRepository(targetRepositoryFullName); + var normalizedLinkedRepository = NormalizeRepository(linkedTargetRepositoryFullName); + if (!string.IsNullOrWhiteSpace(normalizedTargetRepository) && + !string.IsNullOrWhiteSpace(normalizedLinkedRepository) && + !string.Equals(normalizedTargetRepository, normalizedLinkedRepository, StringComparison.OrdinalIgnoreCase)) + { + return "GitHub target repository does not match the linked Bifrost provenance."; + } + + var targetRepoShortName = ShortRepositoryName(normalizedTargetRepository); + var normalizedLinkedRepoName = NormalizeText(linkedRepoName); + if (!string.IsNullOrWhiteSpace(targetRepoShortName) && + !string.IsNullOrWhiteSpace(normalizedLinkedRepoName) && + !string.Equals(targetRepoShortName, normalizedLinkedRepoName, StringComparison.OrdinalIgnoreCase)) + { + return "GitHub target repository does not match the linked Bifrost provenance."; + } + + return null; + } + private static string NormalizeRepository(string value) => NormalizeText(value).ToLowerInvariant(); + private static string ShortRepositoryName(string normalizedRepositoryFullName) + { + if (string.IsNullOrWhiteSpace(normalizedRepositoryFullName)) + { + return string.Empty; + } + + var slash = normalizedRepositoryFullName.LastIndexOf('/'); + return slash >= 0 && slash < normalizedRepositoryFullName.Length - 1 + ? normalizedRepositoryFullName[(slash + 1)..] + : normalizedRepositoryFullName; + } + private static string NormalizeText(string? value) => value?.Trim() ?? string.Empty; } diff --git a/tests/Bifrost.Web.Tests/PlatformEndpointsTests.cs b/tests/Bifrost.Web.Tests/PlatformEndpointsTests.cs index 306a0b1..2cce0a8 100644 --- a/tests/Bifrost.Web.Tests/PlatformEndpointsTests.cs +++ b/tests/Bifrost.Web.Tests/PlatformEndpointsTests.cs @@ -299,6 +299,18 @@ public sealed class PlatformEndpointsTests : IClassFixture x.EntityType == nameof(BridgeAction) && x.Action == "bridge.denied"); } + [Fact] + public async Task Agent_github_action_with_unknown_bifrost_request_is_denied_and_recorded() + { + using var client = _factory.CreateClient(); + + var requestPayload = JsonSerializer.Serialize(new + { + actorKind = "Agent", + actorName = "nibu", + targetSurface = "GitHub", + actionKind = "GitHubDraftPullRequest", + targetRepositoryFullName = "GameCult/Bifrost", + targetLocator = "pulls", + sourceKind = "bifrost_agent_transport_request", + sourceId = "req_missing_123", + authorityReference = "dispatch-approved", + title = "Unbacked request bridge action", + summary = "This should not pass policy." + }); + + using var request = new HttpRequestMessage(HttpMethod.Post, "/bridge/actions/request"); + request.Headers.Add("X-Bifrost-Bridge-Token", "test-bridge-token"); + request.Content = new StringContent(requestPayload, Encoding.UTF8, "application/json"); + + using var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + var action = await response.Content.ReadFromJsonAsync(); + Assert.NotNull(action); + Assert.Equal("Denied", action.Status); + + using var scope = _factory.Services.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + var savedAction = dbContext.BridgeActions.Single(x => x.Id == action.Id); + + Assert.Equal(BridgeActionStatus.Denied, savedAction.Status); + Assert.Contains("unknown request", savedAction.PolicyDecision, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task Agent_github_action_with_mismatched_bifrost_request_repo_is_denied_and_recorded() + { + using var client = _factory.CreateClient(); + await PostTransportReceiptAsync(client, new + { + requestId = "req_bridge_mismatch_123", + title = "Queue the VoidBot bridge hardening pass", + targetRepoName = "VoidBot", + targetRepositoryFullName = "GameCult/VoidBot", + targetAgentIdentity = "nibu", + activityKind = "Claimed", + status = "claimed", + actorName = "bifrost-dispatcher", + note = "Request claimed for VoidBot." + }); + + var requestPayload = JsonSerializer.Serialize(new + { + actorKind = "Agent", + actorName = "nibu", + targetSurface = "GitHub", + actionKind = "GitHubDraftPullRequest", + targetRepositoryFullName = "GameCult/Bifrost", + targetLocator = "pulls", + sourceKind = "bifrost_agent_transport_request", + sourceId = "req_bridge_mismatch_123", + authorityReference = "dispatch-approved", + title = "Repo mismatch bridge action", + summary = "This should not pass policy." + }); + + using var request = new HttpRequestMessage(HttpMethod.Post, "/bridge/actions/request"); + request.Headers.Add("X-Bifrost-Bridge-Token", "test-bridge-token"); + request.Content = new StringContent(requestPayload, Encoding.UTF8, "application/json"); + + using var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + var action = await response.Content.ReadFromJsonAsync(); + Assert.NotNull(action); + Assert.Equal("Denied", action.Status); + + using var scope = _factory.Services.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + var savedAction = dbContext.BridgeActions.Single(x => x.Id == action.Id); + + Assert.Equal(BridgeActionStatus.Denied, savedAction.Status); + Assert.Contains("target repository does not match", savedAction.PolicyDecision, StringComparison.OrdinalIgnoreCase); + } + [Fact] public async Task Local_bridge_token_can_record_dispatch_run_lifecycle() {