Skip to content

fix(node): gate /hooks and sibling read surfaces leaking private repo metadata (#94) - #113

Merged
kevincodex1 merged 25 commits into
mainfrom
fix/gate-repo-read-surfaces
Jul 22, 2026
Merged

kevincodex1 merged 25 commits into
mainfrom
fix/gate-repo-read-surfaces

Conversation

@beardthelion

@beardthelion beardthelion commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #94, and gates the three sibling read surfaces that share its pattern.

Problem

Four GET handlers on the node sat on the optional_signature read group with no ownership or visibility check, so an unauthenticated caller who knew a repo's owner/name could read data that should be private:

Fix

Gating model follows data sensitivity, not a blanket rule:

  • list_webhooks is owner-restricted but layered read-visibility-then-owner: headerless -> 401, non-reader of a private repo -> 404 (existence hidden, uniform with the siblings), non-owner of a public repo -> 403. Webhook callback URLs are owner-secret config.
  • list_replicas, list_protected_branches, list_repo_events gate on read visibility (authorize_repo_read at /, the root-listing exception to path-scoped read gating). Public repos stay anonymously readable; private repos return an opaque 404. replicas is documented as a public mirror-discovery surface, so read-visibility (not owner-only) preserves that for public repos.
  • list_repo_events only gates the locally-hosted branch: when the node holds the repo it runs visibility_check on the loaded record before serving either the cert or gossip events; a repo known only via gossip (no local row) keeps its existing public federation-feed behavior.

Each new gate is pinned into the existing authz_guard drift table so it cannot silently regress.

CLI/MCP

Tightening the node broke gl/MCP read commands that sent unsigned requests. Fixed the callers of the newly gated endpoints: gl webhook list and the MCP webhook_list tool now sign (get_signed); gl protect list, gl repo replicas, and the replica/branch sub-fetches in gl repo info/gl repo owner sign when an identity is present via a new NodeClient::get_maybe_signed (anonymous otherwise, so public repos still work without auth). Added --dir to gl repo replicas.

Tests

Test-first throughout. Coverage includes the full per-surface matrix (owner / non-owner / reader / stranger / headerless / anonymous / absent), the no-existence-oracle property (headerless on an existing-private vs an absent repo both 401), the gossip-only vs local-private split for events, both branches of get_maybe_signed, an end-to-end test that runs a real sign_request output through the node's optional_signature middleware, and signature-header assertions on the CLI/MCP signing paths.

Deferred (separate issues)

  • The global GET /api/v1/events/ref-updates feed is ungated for private-repo ref metadata (the REST analog of GraphQL refUpdates serves private-repo ref metadata to anonymous callers (visibility bypass) #112). Out of scope here; kept to the per-repo surfaces.
  • Several other gl/MCP read commands (gl repo commits, gl pr *, MCP repo_get/pr_*) hit endpoints that were already visibility-gated before this change and send unsigned requests, so they are broken for private repos independently of this PR. Worth a follow-up to sign all gl/MCP read commands.

Summary by CodeRabbit

  • New Features
    • Added optional identity-aware HTTP request signing for CLI read operations; reads are signed when credentials are available.
    • Added --dir support for gl repo replicas and gl webhook list to enable signed, owner-gated listing.
    • MCP webhook listing now uses signed requests.
  • Bug Fixes
    • Enforced read-visibility and owner-gating for replicas, protected branches, webhooks, repo events, and labels; unauthenticated/non-owner access returns consistent 401/403/404 and private details are redacted.
    • Improved fail-closed behavior for visibility gating and aligned owner identity matching.
  • Tests
    • Expanded HTTP/MCP and end-to-end RFC-9421 verification coverage for signing, gating, and secure event redaction.

@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Node read endpoints now enforce visibility or ownership checks for webhooks, replicas, protected branches, labels, and repo events. CLI read paths for webhooks, repo info, replicas, protected branches, labels, and MCP webhook listing now conditionally sign GET requests when an identity keypair is available.

Changes

Node-side endpoint authorization

Layer / File(s) Summary
Endpoint authorization changes
crates/gitlawb-node/src/api/webhooks.rs, crates/gitlawb-node/src/api/replicas.rs, crates/gitlawb-node/src/api/protect.rs, crates/gitlawb-node/src/api/events.rs, crates/gitlawb-node/src/api/labels.rs, crates/gitlawb-node/src/visibility.rs
list_webhooks, list_replicas, list_protected_branches, list_labels, and list_repo_events now accept authenticated caller context and apply visibility or ownership checks before returning data. is_owner now delegates to shared DID matching logic.
Gate markers and integration tests
crates/gitlawb-node/src/api/mod.rs, crates/gitlawb-node/src/test_support.rs
The authz guard fixture list includes events.rs, the marker expectations cover the updated handlers, and integration tests validate webhook, replica, protected-branch, label, and event visibility behavior.

CLI signed request support

Layer / File(s) Summary
Conditional signing helper
crates/gl/src/http.rs
NodeClient gains get_maybe_signed, which signs GET requests with RFC 9421 headers when a keypair exists and otherwise sends an anonymous GET.
Webhook list signing
crates/gl/src/webhook.rs
gl webhook accepts --dir, resolves repo ownership from the loaded identity, and uses a signed request for the hooks list endpoint.
Repo read signing
crates/gl/src/repo.rs
gl repo adds --dir for replicas, loads identities for repo info, replicas, and labels, and updates tests to cover signed and unsigned request paths.
Protected branches and MCP signing
crates/gl/src/protect.rs, crates/gl/src/mcp.rs
gl protect list switches to conditional signing, and the MCP webhook_list tool uses a signed request with matching tests.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • Gitlawb/node#25: Introduced the visibility primitives now used to gate repo-event reads.
  • Gitlawb/node#52: Added authorize_repo_read, which this PR applies to multiple read endpoints.
  • Gitlawb/node#87: Covers the per-route authorization enforcement pattern extended here.

Suggested reviewers

  • kevincodex1
  • jatmn

Poem

🐇 I hop through gates with a signed little grin,
Webhooks, labels, and branches tucked in.
Events stay hidden when visibility says no,
But trusted callers still get the show.
A carrot for auth, and a signature cheer—
The rabbit approves: safe reads are here!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: gating webhook and related private-repo read surfaces.
Description check ✅ Passed The description covers the problem, fix, tests, and follow-ups, though it doesn't mirror the full template.
Linked Issues check ✅ Passed The PR addresses #94 by gating webhook listing and the related private-repo read surfaces as requested.
Out of Scope Changes check ✅ Passed The additional CLI, MCP, and test updates support the same authorization fix and don't appear unrelated.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/gate-repo-read-surfaces

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
crates/gl/src/webhook.rs (1)

157-164: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Check the webhook-list HTTP status before reading webhooks.

A 401/403/404 JSON error body has no webhooks field, so this currently prints “No webhooks” and exits successfully instead of surfacing the authorization failure.

Proposed fix
-    let resp: Value = client
+    let resp = client
         .get_signed(&format!("/api/v1/repos/{owner}/{repo}/hooks"))
-        .await?
-        .json()
-        .await
-        .context("invalid JSON")?;
+        .await?;
+    let status = resp.status();
+    let resp: Value = resp.json().await.unwrap_or_default();
+    if !status.is_success() {
+        let msg = resp["message"].as_str().unwrap_or("unknown error");
+        anyhow::bail!("webhook list failed ({status}): {msg}");
+    }
 
     let hooks = resp["webhooks"].as_array().cloned().unwrap_or_default();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/gl/src/webhook.rs` around lines 157 - 164, The webhook listing flow in
`list_webhooks` is treating error responses as empty results because it parses
JSON and reads `resp["webhooks"]` without checking the HTTP status first. Update
the `client.get_signed(...).await?` handling to inspect the response status
before deserializing or accessing `webhooks`, and surface 401/403/404 as errors
instead of falling back to `No webhooks`. Keep the fix localized around the
`list_webhooks` response handling and the `webhooks` extraction logic.
🧹 Nitpick comments (1)
crates/gitlawb-node/src/api/mod.rs (1)

177-181: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Guard both halves of list_webhooks authorization.

This row only enforces the owner gate. Add a second marker for authorize_repo_read( so the drift test also catches regressions that reintroduce private-repo existence leaks before require_repo_owner.

🧪 Proposed guard hardening
             // Bucket A/B hybrid — list_webhooks is read-visibility THEN owner:
             // authorize_repo_read 404s a non-reader of a private repo, then
             // require_repo_owner 403s a non-owner of a public one. The
             // require_repo_owner marker guards the owner half.
+            (webhooks, "list_webhooks", "authorize_repo_read("),
             (webhooks, "list_webhooks", "require_repo_owner("),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/gitlawb-node/src/api/mod.rs` around lines 177 - 181, The
`list_webhooks` drift-test row in `api::mod` only checks the owner gate, so it
can miss regressions in the read-visibility half. Update the marker set for
`list_webhooks` to include both `authorize_repo_read(` and `require_repo_owner(`
so the test covers the private-repo existence check as well as the owner check.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/gitlawb-node/src/api/events.rs`:
- Around line 66-80: The repo visibility gate in events handling is failing open
because `repo_record` is built with `.ok().flatten()`, so a database lookup
error is indistinguishable from a missing local repo and skips the
`visibility_check` path. Update the `events` flow to preserve and propagate the
lookup error from the local repo fetch, and only allow the ungated gossip-only
behavior when the lookup successfully returns `Ok(None)`. Keep the existing
`visibility_check`/`RepoNotFound` logic in the `repo_record`-based branch so
`api::events` fails closed for local private repos.

---

Outside diff comments:
In `@crates/gl/src/webhook.rs`:
- Around line 157-164: The webhook listing flow in `list_webhooks` is treating
error responses as empty results because it parses JSON and reads
`resp["webhooks"]` without checking the HTTP status first. Update the
`client.get_signed(...).await?` handling to inspect the response status before
deserializing or accessing `webhooks`, and surface 401/403/404 as errors instead
of falling back to `No webhooks`. Keep the fix localized around the
`list_webhooks` response handling and the `webhooks` extraction logic.

---

Nitpick comments:
In `@crates/gitlawb-node/src/api/mod.rs`:
- Around line 177-181: The `list_webhooks` drift-test row in `api::mod` only
checks the owner gate, so it can miss regressions in the read-visibility half.
Update the marker set for `list_webhooks` to include both `authorize_repo_read(`
and `require_repo_owner(` so the test covers the private-repo existence check as
well as the owner check.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ee75b2eb-a906-4a01-b6ce-0fd597b7eec6

📥 Commits

Reviewing files that changed from the base of the PR and between 6ae316c and e2ba8a8.

📒 Files selected for processing (11)
  • crates/gitlawb-node/src/api/events.rs
  • crates/gitlawb-node/src/api/mod.rs
  • crates/gitlawb-node/src/api/protect.rs
  • crates/gitlawb-node/src/api/replicas.rs
  • crates/gitlawb-node/src/api/webhooks.rs
  • crates/gitlawb-node/src/test_support.rs
  • crates/gl/src/http.rs
  • crates/gl/src/mcp.rs
  • crates/gl/src/protect.rs
  • crates/gl/src/repo.rs
  • crates/gl/src/webhook.rs

Comment thread crates/gitlawb-node/src/api/events.rs Resolved

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Fail closed when the local repo lookup errors
crates/gitlawb-node/src/api/events.rs:64
CodeRabbit's inline review item is still valid: get_repo errors are currently collapsed with .ok().flatten(), so a database error is indistinguishable from Ok(None) and the handler takes the ungated gossip-only path. That means the new private-repo visibility gate only runs when the lookup succeeds; on a lookup error, the handler can continue into the public event feed path instead of failing closed. Please complete that review request by propagating the lookup error and only using the gossip-only behavior for an actual Ok(None).

[P2] Surface webhook-list authorization failures instead of printing an empty list
crates/gl/src/webhook.rs:157
CodeRabbit's outside-diff review item is still valid: gl webhook list signs the request now, but it immediately deserializes the response and reads resp["webhooks"] without checking the HTTP status. A 401/403/404 JSON error body has no webhooks field, so the command prints No webhooks for and exits successfully instead of telling the user that the node rejected the request. Please complete that review request by checking resp.status() before extracting webhooks, matching the status handling already used by the neighboring list commands.

[P3] Pin both halves of the list_webhooks authorization gate
crates/gitlawb-node/src/api/mod.rs:181
CodeRabbit's drift-guard comment is still valid: the authz_guard row for list_webhooks only checks for require_repo_owner(, even though this route depends on authorize_repo_read( first to hide private-repo existence before the owner-only check runs. The behavior tests cover the current implementation, but the static guard can still pass if the read-visibility half is later removed. Please add the authorize_repo_read( marker for list_webhooks too, so the regression guard matches the layered security boundary this PR is adding.

@beardthelion beardthelion added kind:security Vulnerability fix or hardening crate:node gitlawb-node — the serving node and REST API subsystem:api Node REST API request/response surface subsystem:visibility Path-scoped visibility and content withholding sev:high Major break or real security/trust risk, no easy workaround labels Jun 29, 2026
@beardthelion
beardthelion requested a review from jatmn June 29, 2026 01:36

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
crates/gitlawb-node/src/api/events.rs (1)

55-87: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use did_matches(...) for the owner fast-path behind this new gate.

This handler now relies on visibility_check to admit the repo owner, but that helper still treats ownership as caller == owner_did || caller == owner_short. If a local repo row is stored in bare form, a signed did:key:... owner is denied here and gets the opaque 404 reserved for non-readers.

Based on learnings, owner DID comparisons must normalize bare and full forms with did_matches(...).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/gitlawb-node/src/api/events.rs` around lines 55 - 87, The new
visibility gate in the events handler is still relying on raw owner DID
equality, which can wrongly deny the repo owner when the stored owner is in bare
form and the caller is a full DID. Update the owner fast-path in the events flow
by using did_matches(...) for the ownership check, and apply it consistently in
the visibility_check path around the repo_record handling so bare and full DID
forms both match correctly.

Source: Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@crates/gitlawb-node/src/api/events.rs`:
- Around line 55-87: The new visibility gate in the events handler is still
relying on raw owner DID equality, which can wrongly deny the repo owner when
the stored owner is in bare form and the caller is a full DID. Update the owner
fast-path in the events flow by using did_matches(...) for the ownership check,
and apply it consistently in the visibility_check path around the repo_record
handling so bare and full DID forms both match correctly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: dc377dcf-7169-4355-96cd-8ce371715b57

📥 Commits

Reviewing files that changed from the base of the PR and between e2ba8a8 and 8453814.

📒 Files selected for processing (2)
  • crates/gitlawb-node/src/api/events.rs
  • crates/gitlawb-node/src/test_support.rs

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. I rechecked the changed paths and found a few issues that still need to be addressed.

Findings

  • [P2] Resolve webhook-list repos from the signing identity
    crates/gl/src/webhook.rs:153
    The new --dir support loads and signs with the user's keypair, but cmd_list still calls resolve_owner(&client), which gets the owner segment from the node root DID rather than from the keypair or an owner/repo argument. For a normal repo created by the local identity on a public node, gl webhook list my-repo --dir ... therefore signs as the repo owner but requests /api/v1/repos/<node-did>/my-repo/hooks, so the newly owner-gated route returns not found/forbidden instead of listing the user's hooks. Please resolve the owner the same way the other repo-scoped commands do: accept owner/repo when provided, and otherwise derive the owner from --dir before falling back to the node DID.

  • [P2] Complete the webhook-list status handling request
    crates/gl/src/webhook.rs:157
    CodeRabbit's outside-diff request, and the later jatmn change request based on it, is still valid in the current patch. gl webhook list signs the request now, but it immediately deserializes the response and reads resp["webhooks"] without checking the HTTP status. A 401/403/404 JSON error from the owner-gated endpoint has no webhooks field, so the command prints No webhooks for <repo> and exits successfully instead of surfacing the authorization failure. Please complete that request by keeping the Response, checking status.is_success() before extracting webhooks, and returning an error on rejected responses, like the neighboring list commands already do.

  • [P2] Use DID-normalized owner matching in the visibility gate
    crates/gitlawb-node/src/visibility.rs:17
    CodeRabbit's current owner-normalization request is still valid. The newly added event gate, and the new authorize_repo_read callers for replicas/protected branches/webhooks, rely on visibility_check to admit the repo owner, but visibility_check's is_owner helper only checks caller == owner_did || caller == owner_short. If a repo row stores the owner in bare form, as mirror rows do, a signed full did:key:... owner is denied by the new gate and gets the opaque 404 path reserved for non-readers. Please switch this helper to the same did_matches semantics used by require_repo_owner, and add coverage for the bare-owner/full-caller case on the newly gated read path.

  • [P3] Complete the list_webhooks authz-guard request
    crates/gitlawb-node/src/api/mod.rs:181
    The previous CodeRabbit/jatmn drift-guard request is still only half addressed. The implementation of list_webhooks intentionally depends on authorize_repo_read first and require_repo_owner second, but the authz_guard row only pins the owner half. That means the static guard can still pass if the private-repo existence-hiding gate is later removed. Please add the authorize_repo_read( marker for list_webhooks too, so the guard matches the layered authorization boundary this PR is adding.

beardthelion added a commit that referenced this pull request Jun 29, 2026
Address jatmn's review feedback on the read-surface gate:

- gl webhook: resolve owner from the signing identity, not the node DID.
  cmd_create/list/delete all routed through the local resolve_owner helper,
  which only ever returned the node root DID, so for a repo owned by the
  local identity the owner-gated /hooks route returned 404/403. Drop that
  helper and reuse repo::resolve_owner_repo_pair (accepts owner/repo, else
  derives from --dir/keypair). Fixed across all three subcommands so
  create-writes and list/delete-reads stay on the same owner.

- gl webhook list: check the HTTP status before reading `webhooks`. A
  401/403/404 body has no webhooks field and previously printed
  "No webhooks" and exited 0, hiding the rejection; now bails with the
  server message like cmd_create.

- visibility::is_owner: delegate to api::did_matches so the read gate and
  require_repo_owner share one normalization. Fixes the under-match (bare
  owner stored, full did:key caller, as mirror rows) that denied the owner
  with the opaque 404, and the cross-method over-match.

- authz_guard: pin both halves of list_webhooks (authorize_repo_read and
  require_repo_owner) so removing the existence-hiding gate fails the drift
  test.

cargo fmt/clippy clean; 644 workspace tests pass.
@beardthelion

Copy link
Copy Markdown
Collaborator Author

All four addressed, pushed to 60ef427.

  • Owner resolution (webhook.rs): dropped the node-DID-only resolve_owner and routed create/list/delete through repo::resolve_owner_repo_pair, so the owner comes from the signing keypair (or an explicit owner/repo). Fixed all three together so create-writes and list/delete-reads stay on the same owner.
  • Webhook-list status (webhook.rs): cmd_list now checks status.is_success() and bails with the server message before reading webhooks, matching the neighboring list commands.
  • Visibility gate (visibility.rs): is_owner now delegates to did_matches, sharing one normalization with require_repo_owner. Added coverage on the gated read path for the bare-owner/full-caller case and a cross-method non-match.
  • authz_guard (api/mod.rs): added the authorize_repo_read( marker row for list_webhooks, so both halves are pinned and removing either gate fails the drift test.

Two follow-ups in the later commits while I was in here: a list_repo_events listed-reader test (the events handler was the only gated read surface missing the non-owner-reader case its siblings already cover), and gl repo label-list switched to get_maybe_signed for parity with the other read commands.

fmt/clippy clean, 646 tests pass.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/gl/src/webhook.rs`:
- Line 159: The webhook success-path parsing in `webhook.rs` is too permissive
because `hooks` defaults to an empty array when `body["webhooks"]` is missing or
malformed. Update the response handling around the `webhooks` extraction so that
2xx responses without a valid `webhooks` array are treated as an error instead
of “No webhooks”, and keep the existing success flow only when the `webhooks`
field is present and is an array. Use the `webhooks` parsing logic in the
webhook response code to locate and tighten this validation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 761abeb7-1bd7-4e17-b0d4-d241f941a155

📥 Commits

Reviewing files that changed from the base of the PR and between 8453814 and 60ef427.

📒 Files selected for processing (5)
  • crates/gitlawb-node/src/api/mod.rs
  • crates/gitlawb-node/src/test_support.rs
  • crates/gitlawb-node/src/visibility.rs
  • crates/gl/src/repo.rs
  • crates/gl/src/webhook.rs
🚧 Files skipped from review as they are similar to previous changes (3)
  • crates/gitlawb-node/src/api/mod.rs
  • crates/gl/src/repo.rs
  • crates/gitlawb-node/src/test_support.rs

Comment thread crates/gl/src/webhook.rs Resolved
beardthelion added a commit that referenced this pull request Jun 29, 2026
)

A 2xx /hooks response without a `webhooks` array could hide a node/API
contract regression. cmd_list now errors with context instead of mapping
it to "No webhooks". An empty-but-present array stays a valid no-webhooks
result. Adds a test for the missing-array case.

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR gates the list_webhooks, list_replicas, list_protected_branches, and list_repo_events read surfaces on the node, adds NodeClient::get_maybe_signed so CLI read commands can sign when an identity is present, and updates the gl/MCP callers that hit those endpoints. I found two issues that still need to be addressed before this is ready.

Findings

  • [P2] Fix MCP webhook_list default owner resolution
    crates/gl/src/mcp.rs:935
    The webhook_list tool now uses get_signed, but when the owner argument is omitted it still calls resolve_owner, which falls back to the node DID. In a normal MCP server started with a public node and the user's --dir, the request is signed by the user's keypair but the path uses the node owner's DID, so the owner-gated list_webhooks endpoint returns 403 (or 404 for a private repo). Default the owner to the signing keypair's short DID, keeping the explicit owner argument as an override, so the MCP tool matches the behavior you already fixed for gl webhook list.

  • [P3] Decide whether list_labels is read-visibility-gated
    crates/gl/src/repo.rs:655 and crates/gitlawb-node/src/api/labels.rs:74
    cmd_label_list was switched to get_maybe_signed with a comment saying labels are "Read-visibility-gated like the sibling read surfaces", but the node's labels::list_labels handler still serves labels without calling authorize_repo_read or checking the caller. That makes the signature unnecessary and leaves private-repo labels public. Either gate the server endpoint with authorize_repo_read (and add the marker to authz_guard), or update the client comment to explain that the signing is only future-proofing and remove the claim that labels are already gated.

beardthelion added a commit that referenced this pull request Jun 29, 2026
…ls on read visibility (#113)

- MCP webhook_list: default owner to the signing keypair's short DID (explicit
  owner arg still overrides) instead of the node root DID, so the signed,
  owner-gated /hooks request resolves to the caller's own repo. Mirrors the
  gl webhook list fix. resolve_owner and webhook_create/delete left untouched.
- list_labels: gate on authorize_repo_read so a private repo's label names 404
  for non-readers (public repos stay anonymously listable), matching the sibling
  read surfaces and making the existing client comment true. Added the
  authz_guard marker and a read-visibility integration test.
- gl label list: check HTTP status before reading the body so the now-gated
  404 surfaces as an error instead of printing "No labels" and exiting 0,
  matching the sibling list clients (replicas, protected branches).
@beardthelion

Copy link
Copy Markdown
Collaborator Author

Both addressed in 80cfb13.

MCP webhook_list now defaults the owner to the signing keypair's short DID, with an explicit owner arg still overriding, and errors when no identity is loaded instead of falling back to the node DID. That matches the gl webhook list behavior.

On list_labels: gated the endpoint. It now runs authorize_repo_read like the sibling read surfaces, so a private repo's label names 404 for non-readers while public repos stay anonymously listable. Added the authz_guard marker and a read-visibility test (owner and listed reader 200, non-reader and anon 404, absent repo 404), and fixed gl label list to surface that 404 as an error instead of printing an empty list.

@beardthelion
beardthelion requested a review from jatmn June 29, 2026 22:02

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
crates/gitlawb-node/src/test_support.rs (1)

1252-1267: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Assert the anonymous 404 body does not leak labels.

This path only checks the status. Since anonymous callers are part of the private-label leak threat model, read the body here and assert !leaks(&bytes) like the signed non-reader case.

Proposed test hardening
         assert_eq!(
             resp.status(),
             StatusCode::NOT_FOUND,
             "anon is denied the private labels"
         );
+        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+            .await
+            .unwrap();
+        assert!(!leaks(&bytes), "anonymous 404 must not leak the label name");
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/gitlawb-node/src/test_support.rs` around lines 1252 - 1267, The
anonymous private-repo 404 test only verifies StatusCode in the router().oneshot
flow and does not check for label leakage. Update this test in test_support.rs
to read the response body bytes after the NOT_FOUND assertion and verify they do
not leak labels using the existing leaks(...) helper, matching the signed
non-reader coverage.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/gitlawb-node/src/test_support.rs`:
- Around line 1252-1267: The anonymous private-repo 404 test only verifies
StatusCode in the router().oneshot flow and does not check for label leakage.
Update this test in test_support.rs to read the response body bytes after the
NOT_FOUND assertion and verify they do not leak labels using the existing
leaks(...) helper, matching the signed non-reader coverage.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 177b8fc7-25a3-4bed-9ac8-e2954a160e93

📥 Commits

Reviewing files that changed from the base of the PR and between 281a7b2 and 80cfb13.

📒 Files selected for processing (5)
  • crates/gitlawb-node/src/api/labels.rs
  • crates/gitlawb-node/src/api/mod.rs
  • crates/gitlawb-node/src/test_support.rs
  • crates/gl/src/mcp.rs
  • crates/gl/src/repo.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/gitlawb-node/src/api/mod.rs
  • crates/gl/src/repo.rs

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. I rechecked the changed paths and found a couple of issues that still need to be addressed.

Findings

  • [P2] Surface denied repo-info reads instead of printing fake repo details
    crates/gl/src/repo.rs:348
    This PR changes gl repo info to use get_maybe_signed for the visibility-gated GET /api/v1/repos/{owner}/{name} path, but the command still parses the response body without checking resp.status(). When the node returns the expected JSON 404 for a private repo the caller cannot read, the command treats that error JSON as a repo, falls back to owner, ?, true, and main, prints a plausible-looking repository summary, and exits successfully. Please keep the Response, check status.is_success() before reading repo fields, and return the node's error message on 401/403/404, like the other newly gated list commands do.

  • [P3] Complete CodeRabbit's anonymous label-leak assertion request
    crates/gitlawb-node/src/test_support.rs:1252
    CodeRabbit's latest test-hardening request is still valid in the current patch. The signed non-reader label path reads the 404 body and asserts that it does not contain the private label name, and the sibling replica/protected-branch anonymous-denial cases make the same no-leak assertion. The anonymous private-label branch, though, only checks the 404 status and never reads the body, so this PR's regression coverage can still miss the exact anonymous label-name leak it is trying to close if an error body regresses later. Please complete that request by reading the anonymous 404 body here and asserting !leaks(&bytes).

@kevincodex1 kevincodex1 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

beardthelion added a commit that referenced this pull request Jun 30, 2026
…#113)

cmd_info parsed the GET /api/v1/repos/{owner}/{name} body without checking
the HTTP status, so a private-repo JSON 404 was rendered as a fake repo
summary (owner / ? / public / main) and exited 0. Capture the status and
bail on non-2xx, matching the sibling list commands.

Also assert the anonymous 404 label-list body does not leak the label name,
closing the last unread-body branch in the read-visibility gate test.
@beardthelion
beardthelion requested a review from jatmn June 30, 2026 01:46

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. I rechecked the changed paths and found issues that still need to be addressed.

Findings

  • [P1] Rebase on main and resolve the merge conflicts first
    GitHub mergeability
    GitHub currently reports this branch as CONFLICTING with merge state DIRTY, so the PR cannot be merged in its current state. Please rebase on the latest main branch and resolve those conflicts before addressing the review finding below, so any follow-up fix applies to the code that will actually land.

  • [P2] Surface denied MCP webhook-list responses as tool errors
    crates/gl/src/mcp.rs:949
    The MCP webhook_list path now signs the owner-gated /hooks request, but it still immediately deserializes the response body and returns it as a successful tool result without checking resp.status(). If the node returns the expected 401/403/404 JSON error for a missing identity, wrong owner, private repo, or deleted repo, the MCP tool reports success with that error body instead of failing the tool call, unlike the fixed gl webhook list path which checks status.is_success() before reading webhooks. Please keep the Response, check the HTTP status, and return an error with the node message for non-2xx responses before serializing the successful webhook list.

The merge changed three gl branches that no existing test executed (they
were only reasoned): resolve_owner_did with no local identity, cmd_info on
an authenticated-but-denied 403, and get_maybe_signed with no keypair. Add
a test per branch asserting the must-not case (error/unsigned, never a
fabricated repo card). Verified load-bearing by mutation: disabling the
cmd_info status gate turns the 403 test red.
@kevincodex1

Copy link
Copy Markdown
Member

hello bro @beardthelion please rebase to main again and fix the conflicts

…rfaces

# Conflicts:
#	crates/gitlawb-node/src/api/mod.rs
#	crates/gl/src/repo.rs
@beardthelion

Copy link
Copy Markdown
Collaborator Author

@kevincodex1 merged latest main in and resolved the conflicts. Mergeable and green now, ready to merge whenever.

@beardthelion

Copy link
Copy Markdown
Collaborator Author

@kevincodex1 #113 is clean (mergeable, CI green) and approved by you and jatmn. It's the /hooks and sibling read-surface leak fix (closes #94), still ready to merge whenever you have a moment.

@beardthelion

Copy link
Copy Markdown
Collaborator Author

@kevincodex1 this one's ready when you are. Approved by jatmn (and yourself), CI green across all checks, mergeable, no unresolved threads. It's been sitting since 2026-07-01. HEAD carries three main-merges plus one deny-arm test (6ca49e2) on top of the approved sha, no production changes after the approval, so the gate is the same code jatmn signed off. Flagging in case you'd rather jatmn re-glance the merges first.

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kevincodex1 kevincodex1 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@kevincodex1
kevincodex1 merged commit ee8d7c0 into main Jul 22, 2026
14 checks passed
kevincodex1 added a commit that referenced this pull request Jul 22, 2026
…229)

PRs #113 and #145 raced: #145 added owner_did to ReceivedRefUpdate and
updated its own call sites, but the seed initializer in
list_repo_events_fails_closed_when_repo_lookup_errors (added by #113)
was never updated, so main fails to compile test targets (E0063).
This breaks clippy --all-targets, both test jobs, and MSRV on CI,
including the release PR #182.

owner_did stays None here on purpose: the test exercises the legacy
None-branch slug fallback.

Co-authored-by: Kevin Codex <[email protected]>
kevincodex1 added a commit that referenced this pull request Jul 22, 2026
…229)

PRs #113 and #145 raced: #145 added owner_did to ReceivedRefUpdate and
updated its own call sites, but the seed initializer in
list_repo_events_fails_closed_when_repo_lookup_errors (added by #113)
was never updated, so main fails to compile test targets (E0063).
This breaks clippy --all-targets, both test jobs, and MSRV on CI,
including the release PR #182.

owner_did stays None here on purpose: the test exercises the legacy
None-branch slug fallback.

Co-authored-by: Kevin Codex <[email protected]>
beardthelion pushed a commit that referenced this pull request Jul 22, 2026
After merging main, the completeness fence flagged three repo-scoped list
GETs that #113 gated but the harness still treated as ungated public reads:
list_webhooks (authorize_repo_read + require_repo_owner), list_replicas and
list_protected_branches (authorize_repo_read). The runtime marker scan caught
its own hand-maintained PUBLIC_REPO_GETS list drifting stale.

Drive each real deny instead of exempting it:

- list_replicas and list_protected_branches take Option auth, so they slot in
  as standard ReadGate rows (anon and signed-non-reader both 404, owner 2xx,
  no-leak body).
- list_webhooks is doubly gated and 401s a headerless caller before any
  lookup, so a vanilla ReadGate row's hardcoded anon->404 leg does not fit.
  Add a per-Row anon_read signal (Deny404 default, Deny401 for auth-required
  reads) so its anon leg expects 401 while the signed-non-reader still drives
  the existence-hiding 404. Its owner layer is a sibling OwnerGate row on the
  public repo (signed stranger -> 403). The two share the /hooks path, so the
  consistency dedup key moves from (method, path) to (method, path, gate),
  which still catches an accidental same-gate double-registration.
- Empty PUBLIC_REPO_GETS: the three are now driven rows, classified via the
  driven-path set rather than declared public. The mechanism stays for the
  next genuinely-public repo-GET.

Each new row proven load-bearing: reverting the production gate turns the
matching hostile probe red (403->200 owner, 404->403/200 read), and flipping
list_webhooks' anon_read to Deny404 reddens its anon probe (got 401). Full
deny_harness green (39/39). No production changes.
kevincodex1 added a commit that referenced this pull request Jul 22, 2026
Two individually-green PRs can break main in combination when the second
merges on checks that ran against a stale base (#113 + #145 compiled fine
apart, but #145 added a field to ReceivedRefUpdate that #113's new test
initializer never set — E0063 on merged main, fixed by #229).

- pr-checks: add merge_group trigger so the suite can gate a GitHub merge
  queue, which re-validates every PR against the true merged result.
- main-red-alert: new workflow that opens/updates a labeled issue whenever
  a push-to-main PR Checks run fails, so a red main is loud instead of
  silent (release-please PRs inherit main breakage, as #182 showed).
@coderabbitai coderabbitai Bot mentioned this pull request Jul 22, 2026
11 of 12 tasks
beardthelion added a commit that referenced this pull request Aug 4, 2026
After merging main, the completeness fence flagged three repo-scoped list
GETs that #113 gated but the harness still treated as ungated public reads:
list_webhooks (authorize_repo_read + require_repo_owner), list_replicas and
list_protected_branches (authorize_repo_read). The runtime marker scan caught
its own hand-maintained PUBLIC_REPO_GETS list drifting stale.

Drive each real deny instead of exempting it:

- list_replicas and list_protected_branches take Option auth, so they slot in
  as standard ReadGate rows (anon and signed-non-reader both 404, owner 2xx,
  no-leak body).
- list_webhooks is doubly gated and 401s a headerless caller before any
  lookup, so a vanilla ReadGate row's hardcoded anon->404 leg does not fit.
  Add a per-Row anon_read signal (Deny404 default, Deny401 for auth-required
  reads) so its anon leg expects 401 while the signed-non-reader still drives
  the existence-hiding 404. Its owner layer is a sibling OwnerGate row on the
  public repo (signed stranger -> 403). The two share the /hooks path, so the
  consistency dedup key moves from (method, path) to (method, path, gate),
  which still catches an accidental same-gate double-registration.
- Empty PUBLIC_REPO_GETS: the three are now driven rows, classified via the
  driven-path set rather than declared public. The mechanism stays for the
  next genuinely-public repo-GET.

Each new row proven load-bearing: reverting the production gate turns the
matching hostile probe red (403->200 owner, 404->403/200 read), and flipping
list_webhooks' anon_read to Deny404 reddens its anon probe (got 401). Full
deny_harness green (39/39). No production changes.
beardthelion added a commit that referenced this pull request Sep 16, 2026
After merging main, the completeness fence flagged three repo-scoped list
GETs that #113 gated but the harness still treated as ungated public reads:
list_webhooks (authorize_repo_read + require_repo_owner), list_replicas and
list_protected_branches (authorize_repo_read). The runtime marker scan caught
its own hand-maintained PUBLIC_REPO_GETS list drifting stale.

Drive each real deny instead of exempting it:

- list_replicas and list_protected_branches take Option auth, so they slot in
  as standard ReadGate rows (anon and signed-non-reader both 404, owner 2xx,
  no-leak body).
- list_webhooks is doubly gated and 401s a headerless caller before any
  lookup, so a vanilla ReadGate row's hardcoded anon->404 leg does not fit.
  Add a per-Row anon_read signal (Deny404 default, Deny401 for auth-required
  reads) so its anon leg expects 401 while the signed-non-reader still drives
  the existence-hiding 404. Its owner layer is a sibling OwnerGate row on the
  public repo (signed stranger -> 403). The two share the /hooks path, so the
  consistency dedup key moves from (method, path) to (method, path, gate),
  which still catches an accidental same-gate double-registration.
- Empty PUBLIC_REPO_GETS: the three are now driven rows, classified via the
  driven-path set rather than declared public. The mechanism stays for the
  next genuinely-public repo-GET.

Each new row proven load-bearing: reverting the production gate turns the
matching hostile probe red (403->200 owner, 404->403/200 read), and flipping
list_webhooks' anon_read to Deny404 reddens its anon probe (got 401). Full
deny_harness green (39/39). No production changes.
@beardthelion
beardthelion deleted the fix/gate-repo-read-surfaces branch November 4, 2026 22:58
kevincodex1 pushed a commit to kevincodex1/node that referenced this pull request Nov 12, 2026
…ner-gated mutations, path-scoped reads, client-surfaced denials) (Twigpine#194)

* refactor(node): split gitlawb-node into lib+bin so integration tests can spawn a real node

Move the module tree and boot logic from main.rs into a new lib.rs crate
root exposing the boot surface (build_router, AppState, Config, migrations)
as pub; main.rs becomes a thin #[tokio::main] shim over run(). No behavior
change: both targets build and the full node suite (488 tests) stays green.

Prerequisite for the real-node deny harness (U1).

* test(node): real-node deny harness rig + INV-8 unsigned-push case (U2-U4, U5a)

Add a feature-gated (test-harness) spawn surface (src/test_harness.rs) that
boots a real node on 127.0.0.1:0 over an ephemeral #[sqlx::test] pool through
the production axum::serve stack with connect-info, and an integration crate
(tests/deny_harness.rs) that drives deny paths with a real reqwest client:

- U2 signing client: wraps gitlawb_core::http_sig::sign_request for reqwest;
  self-checks that a valid signature clears require_signature and a tampered
  body is rejected (400 content_digest_mismatch).
- U3 spawn_node: real socket, p2p disabled, per-test DB, shutdown-on-drop.
- U4 assert_denied: 4xx AND body-no-leak AND not-empty-200 (INV-8); pure core
  unit-tested for clean-403 / empty-200 / leaking-403 / wrong-status.
- U5a INV-8: unsigned git-receive-pack is denied 401 with no leak.

Widens the three cfg(test) test builders (Db/RepoStore::for_testing,
run_migrations) to also compile under the feature. No production behavior
change: prod build (no feature) excludes test_harness; node suite stays green
(488) and the 7 integration tests pass.

* test(node): INV-1 owner-gate deny case over the real stack (U6)

A validly signed non-owner PUT /visibility is rejected 403 by require_owner
(no x-ucan, so require_ucan_chain passes through to the gate); the owner's
signed PUT reaches the handler (reachability proof, guards against a 404/415
masquerading as a pass). Adds seed_repo/withhold_path seeding helpers to the
test harness. Mutation-verified load-bearing: with require_owner forced Ok the
non-owner PUT returns 201 and the INV-8 assertion flips the test RED.

* test(node): INV-2 read + content-addressed withhold deny cases (U5b, U7)

Adds seed_bare_repo (shells git to build a real bare repo at the served path,
sha1 or sha256 object format) and two INV-2 deny cases over the real stack:

- U7: a public repo with a /secret/** withhold rule denies an anonymous blob
  read of the withheld path (404) with no content/OID leak, while the sibling
  public path is served (path-scoped, not blanket).
- U5b: the same withhold denies an anonymous /ipfs/{cid} read of the withheld
  blob's content-addressed id (404, no leak), while the public blob's CID is
  served. Completes U5 (INV-8) alongside U5a.

Both mutation-verified load-bearing: forcing visibility_check to allow leaks
the secret at 200 and the INV-8 assertion flips each test RED.

* test(node): INV-2 replication-path deny case over git-upload-pack (U8)

Drives the git-upload-pack POST directly (v0 stateless-RPC: want HEAD, flush,
done) via a bounded reqwest client rather than a vanilla `git clone` (which
negotiates protocol v2 and deadlocks against the node's v0 server, and would
otherwise wedge the suite). The served pack is indexed with git index-pack and
its objects listed with verify-pack -v: a packfile-aware assertion, since a raw
byte scan cannot see an OID inside the zlib-compressed stream.

A public repo with a /secret/** withhold rule must serve a pack that omits the
withheld blob's object while keeping the sibling public blob. Mutation-verified
load-bearing: forcing visibility_check to allow puts the withheld blob back in
the pack and flips the test RED.

Completes the harness (8 units, 11 integration tests). Prod build (no feature)
and the 488-test node suite stay green.

* ci(node): run the real-node deny harness on every PR

cargo test --workspace skips the harness because it lives behind the
test-harness feature (kept off the production binary). Add an explicit step
that runs it with the feature and the same Postgres service, so the INV-1/
INV-2/INV-8 trust-boundary regression cases execute on every PR instead of
only when run by hand.

* test(node): cover the deny-assertion guard branches (U4)

Add unit tests for the two remaining check_denied branches: a non-4xx expected
status is rejected as a test bug, and an empty withheld token is skipped rather
than matching every body. Closes the last unexecuted branches in the deny
assertion.

* test(node): full-stack owner-gate deny cases for 5 high-value mutations

Fan-out of U6 to the security-sensitive owner-gated mutations that had only the
source-level authz-table guard and no runtime deny test: protect_branch,
unprotect_branch, create_webhook, delete_webhook, remove_visibility. Each
rejects a validly-signed non-owner with 403 and lets the owner reach the
handler (not 403). Mutation-verified load-bearing on their shared root gate:
did_matches forced true opens all five (non-owner protect_branch returns 201)
and the test flips RED.

Replica register/unregister were intentionally excluded: they are signer-self
(you register your own node), not owner-gated, so there is no owner-deny to
assert.

* style(node): cargo fmt the deny-harness sources

* Address PR review feedback (#194)

- Create the node identity key atomically with create_new + mode 0600, closing
  the umask-derived 0644 disclosure window and the exists()->write overwrite
  race; on AlreadyExists load the winner's key (bounded retry so a loser can't
  read a half-written PEM) and tighten looser perms on load.
- Enforce the configured shutdown grace: bound the axum drain by grace measured
  from the signal (extracted as drive_serve_with_grace), abandoning in-flight
  requests once it expires instead of waiting indefinitely. Removes the
  discarded grace value.
- Route the deny-harness reqwest clients through a shared bounded_client (30s
  timeout) so a wedged node path fails fast instead of hanging to the CI limit.

Tests: 0600-on-create, load-tighten, concurrent-start convergence (create race),
and grace-race abandon / normal-drain / signal-gated-clock. All RED-then-GREEN
by execution.

* fix(node): remove a failed first-write key file; verify key mode after tightening (#194)

F1 (P1): create_new(true) closed the permission window, but a write_all failure
after the file was created left an empty/partial PEM behind. Every later start
then took the key_path.exists() branch, re-parsed that corrupt file in load_racing,
and exited 'invalid PEM key' instead of regenerating — a transient ENOSPC/EIO on
first boot permanently wedged the node. Extract write_key_or_cleanup, which removes
the just-created file on write failure, and wire it into both the unix and non-unix
create branches.

F2 (P2): the load path tightened a loose existing key to 0600 but discarded the
set_permissions result. A chmod that failed (read-only mount, ownership/ACL
mismatch) left a world/group-readable private key in use while logging a normal
'loaded existing identity'. Surface the tighten failure (propagate it) and add
ensure_key_mode_0600, which fails closed if the key is not 0600 after the attempt.

RED->GREEN: failed_write_removes_the_partial_key_file (a failed write leaves no
file; RED without the remove_file). loose_key_mode_is_rejected_not_used (a 0644 key
is rejected; RED without the mode check). Existing created_key_is_mode_0600,
existing_key_is_loaded_and_tightened, and concurrent_starts_converge_on_one_identity
stay green. Full node lib+bin suite 497 passed, fmt + clippy clean.

* fix(node): publish the identity key atomically and wait a real deadline

The create path did create_new(final)+write_all, so the final path appeared as
an empty inode before the PEM was flushed, and a losing/fast-path start only
retried ~100ms (50x2ms). On a slow or stalled filesystem the winner's write can
exceed that window, so every other start failed boot with 'invalid PEM key'
(#194). Publish atomically instead: write the full PEM to a sibling temp, then
hard_link it into place. hard_link is atomic and fails if the target exists, so
the final path only ever appears COMPLETE (no partial-read window), a lost race
never clobbers the winner, and a crashed writer leaves only a temp rather than a
partial final that would wedge later starts. load_racing_key now polls on a
wall-clock KEY_RACE_DEADLINE (5s) instead of a fixed 100ms count. Hoisted
load_existing_key/load_racing_key to module level for testability.

Adversarial RED->GREEN: a 250ms-slow winner is waited out (RED at the old 100ms);
a reader watching the final never sees a partial file (RED with create_new+write);
a losing publish does not clobber the winner; 500 tests pass.

* fix(node): recover key publish from stale temps, make it durable; join TestNode teardown (#194)

- pick the temp key name with a bounded per-call retry instead of a
  process-global counter: a crashed start's leftover temp no longer wedges
  a PID-stable restart, and cross-container publishers stop colliding
- fsync the temp PEM before it can be linked and the key directory after
  publication, so a power crash cannot leave a durable-but-truncated
  identity.pem that permanently blocks startup
- TestNode::shutdown() joins the serve task and closes the pool before
  sqlx's DROP DATABASE cleanup runs; every deny-harness test now ends
  with it instead of relying on drop-only teardown

* test(node): let the partial-final reader wait out the fsynced publish (#194)

The added temp-file and directory fsyncs can push the hard_link past the
reader's old 400ms window under parallel-suite disk load, flaking
publish_never_exposes_a_partial_final (observed ~1 in 5 local runs). The
reader now polls a 5s deadline and stops at the first complete
observation; the never-see-partial assertion still runs before the
break, so the exposure mutation still fails the test.

Also moves the allow-unbounded-git marker in seed_bare_repo directly
above the spawn line, where the pre-push gate looks for it.

* fix(node): fall back to a direct create_new publish when hard_link fails (#194)

On a non-AlreadyExists hard_link error, publish the identity key by
creating the final path directly with create_new(0600): no-clobber is
preserved via the exclusive create (AlreadyExists routes to the lost-race
load), write failures remove the partial final, and fsync failures keep
the complete final on disk since a concurrent loser may already have
loaded it (the Won-arm policy). The fallback chains the original link
error and the rustdoc now scopes the complete-only-visibility guarantee
to the hard-link path. Link step is injectable via compile-time fault
hooks; six new tests drive both fallback arms, the lost race, the
concurrent convergence, and both failure phases.

* test(node): abort the server task in TestNode::drop (#194)

A test that returns without calling shutdown() previously relied on the
watch signal alone to unwind the server before sqlx's DROP DATABASE.
Drop now also aborts any remaining serve handle, so teardown holds even
when the graceful chain is broken; signal and abort are independently
sufficient (verified by a four-quadrant neuter matrix in the new
drop_without_shutdown_unblocks_database test, which observes leaked
sessions via a standalone connection with sqlx pool reaping disabled).

* chore: sync Cargo.lock with the 0.5.1 workspace manifests

* test(node): surface axum::serve's result through TestNode::shutdown (#194)

The spawned serve task previously discarded its io::Result; shutdown()
now joins and checks it. On axum 0.8.8 the Err arm is unreachable
(graceful shutdown hard-codes Ok and accept errors retry forever), so
this is forward-compat insurance documented as such inline; the Ok path
is exercised by every harness test.

* fix(node): verify key file mode before writing PEM bytes at both creation sites (#194)

Both creation sites (the temp on the hard-link path, the final on the
fallback path) now run the loader's tighten-then-verify pair right after
create_new and before any private bytes are written: set_permissions
repairs a umask-narrowed mode (0277 landed 0400 and previously shipped
that way), and on mode-ignoring mounts where the tighten silently no-ops
the verify fails closed with the empty file removed so retries are not
wedged. A verified temp implies a verified hard-linked final (shared
inode). Both call sites are mutation-vetted; umask cases run in child
processes because umask is process-global.

* docs(node): state the real shutdown-grace contract and lock it with a real-socket test (#194)

GITLAWB_SHUTDOWN_GRACE_SECS promised a 503 to in-flight clients at
expiry; drive_serve_with_grace (correctly) abandons them instead, and a
retroactive 503 on an in-flight response is not constructible under
hyper. The config prose now states the abandon contract, and a new test
drives a real listener with a slow handler through the driver at a
250ms grace, asserting the client never sees a 503 status line and the
driver returns bounded with grace_expired set.

This commit changes only a doc comment and a test, so it is typed docs()
rather than fix() to avoid a spurious release-please patch bump.

* test(node): close review gaps on the key-publish fallback and Drop abort (#194)

Round-five review follow-ups, no production behavior change beyond a
pure fsync_parent_dir extraction:

- Recondition the KEY_RACE_DEADLINE and publish_key_atomically rustdocs:
  a present key is complete-on-first-read only on the hard-link path; on
  the fallback the final name is visible mid-write (the deadline covers
  it) and the fallback also weakens durability (d), failing loud at next
  start, never a silently used key.
- Cover the fallback create_new open-error arm via a new fault hook,
  asserting the returned error chains the original link error.
- Make the Drop abort load-bearing (INV-21): a test-only flag suppresses
  the graceful signal so handle.abort() carries teardown alone; removing
  the abort turns the new test RED while the existing one stays green.
- Observe the crash-residue contract: empty/garbage finals fail loudly.
- Extract fsync_parent_dir, shared by the Won and fallback arms.
- Split the permissive-umask test so a 0000 regression can't hide behind
  0077.

* fix(node): recover identity-key fallback fsync failure and abort wedged serve task

F1: the hard-link fallback wrote the PEM directly to the final path then
fsync'd it separately; an fsync failure left a durable name over non-durable
content, so a later crash wedged startup (load_or_create_keypair parses the
existing truncated file instead of regenerating). Fold the file fsync into
write_key_or_cleanup so the final is removed on fsync failure, matching the
hard-link temp policy; the next start regenerates. Parent-dir fsync still
keeps-on-failure.

F2: TestNode::shutdown moved the serve JoinHandle into tokio::time::timeout and,
on elapse, the panicking .expect dropped it, detaching the still-running task
and leaking the test DB across DROP DATABASE. Retain the handle (&mut), abort
and reap it on timeout before panicking. Also: honor a task that finishes in the
timeout race as graceful (not a false wedge), propagate a real serve-task panic,
and close the pool on every path (including the wedged arm) before returning or
panicking so the leak is closed on the path that needs it most.

* test(node): invariant deny-prober (driven registry + completeness cross-check) (#195)

* test(node): U1 deny-bearing route registry (owner-gate + signature tranches)

Foundation for the invariant deny-prober (plan 002): a declarative registry of
ONLY the routes that carry a runtime deny (owner-gate 403 / read-gate 404 /
signature 401), each classified by reading its handler and recording the fn
name. Owner-gate (12 rows: merge/close_pr, close_issue, webhooks, labels,
protect, visibility set/remove/list incl the GET-is-403 correction) and
signature-required (git-receive-pack) tranches are verified; read-gate tranche
stubbed with a TODO (per-handler 404-vs-filter verification pending). A
consistency self-test asserts no dup method+path, every row names its handler,
and every read-gate row carries a positive-twin Reach. Decoupled from the #194
primitives (U1 uses none), so classification is not hostage to harness churn.

* test(node): U2 fixture state matrix + per-gate-class probe generators

Two-repo fixture (public owner-gate substrate + private read-gate substrate)
plus probes_for(): each deny-bearing row expands to a hostile probe asserting
the exact deny status and a positive twin (owner-reachability for owner-gate,
authorized read for read-gate) so a deny for the wrong reason cannot false-pass.
Three self-checks cover the owner-gate, read-gate, and signature classes.

* test(node): U1 read-gate tranche (14 repo-scoped 404-deny reads)

Each row's handler was read to confirm it gates on "/" via
authorize_repo_read / visibility_check and returns RepoNotFound (404) to a
non-reader of a private repo, with the owner re-read as the ReaderReads
positive twin. Sub-entity gets (get_issue/get_pr/get_cert/get_bounty and the
comment/review lists) are deferred to the fixture expansion that seeds them;
global list-filter surfaces and the KNOWN_UNGATED reads are excluded with
reasons. Runtime behavior is asserted by U3.

* test(node): U3 drive the deny-bearing registry over a real node

Boots a real node, seeds the two-repo fixture (plus a PR and an issue so the
author-or-owner close gates are reached, not 404'd on an absent entity), then
walks every deny-bearing route: the hostile probe must return the exact deny
status and leak nothing, and the positive twin must reach the handler (owner:
not 403; read: 2xx). A terminal invariant asserts one hostile probe per row
was driven and the count equals the registry, so a row that produced no probe
fails loud rather than passing vacuously. Adds seed_pr/seed_issue to TestNode.

Mutation-verified load-bearing: breaking did_matches drove the merge_pr
owner-gate hostile to 500 (RED, named); neutering authorize_repo_read's deny
drove the get_repo read-gate hostile to 200 (RED, named); both reverted green.

* test(node): U4 completeness cross-check keeps the registry from drifting

A pure source scrape of server.rs (multiline .route parser, floor 90) that the
runtime sweep cannot give: no deny-bearing row points at a route that no longer
mounts (anti-stale), and no handler carrying an unambiguous owner-gate marker
(require_repo_owner / require_owner) escapes the registry (orphan). The api dir
is read at test time so a new module is covered. Complements authz_guard (which
proves handlers are gated) by proving the deny-bearing ones are actually driven,
and reaches the non-API git mounts authz_guard never sees.

Mutation-verified: a bogus row path tripped anti-stale (named the row); removing
the merge_pr row tripped the orphan guard (named merge_pr); both reverted green.

* test(node): close vacuous-green gaps in the deny prober's own assertions

Vetting the harness against itself surfaced branches that ran green but were
never exercised adversarially:
- Ok2xx twin dropped its unused token Option; the arm now asserts the authorized
  read returns a NON-EMPTY 2xx, so an empty-200 denial-rendered-as-success is
  caught (executed by every read twin).
- U4 orphan guard gains a floor on the owner-marker scan (>=6), so a marker-scan
  regression to zero fails loud instead of passing by checking nothing.
- Added probe unit tests that execute the previously-uncovered probes_for arms:
  the SiblingPublic path-scoped twin, and the Reach::None fail-loud panic.

All 22 harness tests green. Every send_probe/probes_for branch is now executed;
the Deny(401), Not403, and Ok2xx-status arms were additionally mutation-verified
RED (signature-expect flip; did_matches->false; authorize_repo_read->deny) and
both U4 floors RED via threshold flips, all reverted.

* test(node): close 3 completeness gaps in the deny prober's own guards (#195)

jatmn's review flagged three ways the prober's self-guards stay green when
the protection they check is removed:

- F1: the U4 completeness check enforced owner-gate orphans but not
  read-gate ones, so dropping authorize_repo_read on get_issue/get_cert/
  get_bounty/etc. left the sweep green. Add a symmetric read-gate orphan
  guard that scans src/api for authorize_repo_read/visibility_check handlers
  and requires each to be a driven ReadGate row or an enumerated
  READ_GATE_NOT_DRIVEN entry with a reason, replacing the free-text prose.
  A staleness check keeps the allowlist from carrying dead exemptions.

- F2: the U3 registry sweep called assert_denied with an empty withheld
  list, proving status only. Seed the private fixture with a distinctive
  secret and its blob OID, carry them on the read-gate hostile probes, and
  pass them through so a denial body echoing withheld data fails.

- F3: the owner-gate orphan scan matched only require_owner/require_repo_owner
  and missed the inline did_matches(caller, &record.owner_did) idiom that
  protect_branch/unprotect_branch use. Fold in a has_owner_did_matches
  discriminator that catches the owner form without false-matching the
  signer-self (register_replica) or author (close_pr) did_matches forms,
  pinned by unit tests on the exact bodies.

* test(node): make the deny-prober guards load-bearing (#195, F1-F4)

Resolves jatmn's four INV-21 completeness findings — guards that were green but
not load-bearing:

F1: every ReadGate hostile probe was anonymous, so the signed-non-reader branch of
each private read was untested — a regression treating any valid signature as
authorized would leak while the sweep stayed green. Add a Signer::Stranger 404/
no-leak probe per read row, with a dedicated readgate_stranger counter so a dropped
probe fails loudly. RED: authorize any signed caller -> the stranger probe leaks
(200) while the anon probe stays green.

F2: get_star_status, get_icaptcha_proof, and replicate_encrypted_blobs were
source-only exemptions (a marker scan, never driven). Drive them as real ReadGate
rows and remove the allowlist entries. RED: a runtime bypass that keeps the
authorize_repo_read marker leaks -> the driven probe RED, the source scan green.

F3: git_receive_pack's protected-branch owner 403 was never driven (its registry
row is the unsigned-401 path). Add signed_stranger_protected_branch_push_is_forbidden
(a signed non-owner push to a protected branch -> 403, owner control -> not-403),
plus a seed_protected_branch harness helper. RED: invert the gate -> the probe RED.

F4: the read-gate no-leak assertion omitted the private repo id (seed discarded it).
Preserve it on the Fixture and withhold it; a synthetic 404 body carrying the UUID
must fail check_denied. RED: a UUID-bearing body passed before the token was added.

Each guard proven load-bearing by reverting the exact production auth-line (reverts
not shipped). deny_harness suite 30 passed, fmt + clippy clean.

* test(node): drive every arm of the multi-principal close/dispute gates

close_pr, close_issue (owner-or-author) and dispute_bounty (creator-or-claimant)
were each driven with a single owner/creator twin, so reverting the untested arm
stayed green. Model gates by their authorizing-principal set (MultiPrincipalGate
+ Principal), seed distinct author/creator/claimant identities, and emit one
Not403 twin per arm plus the stranger 403. registry_internal_consistency now
invokes probes_for and asserts a twin per declared arm, so a future multi-arm
handler cannot register with an untested arm.

Each arm proven load-bearing: reverting is_owner/is_author on close_pr/close_issue
and is_creator/is_claimant on dispute_bounty turns that arm's twin RED.

* test(node): drive the deferred private reads with per-read leak assertions

The deferred reads (get_issue, get_pr, get_pr_diff, list_issue_comments,
list_reviews, list_comments, get_cert, get_bounty, path-scoped get_tree) sat in
READ_GATE_NOT_DRIVEN, checked only for an authorize_repo_read marker, so an
ignored result or early return stayed green. Seed each sub-entity in the private
repo (issues/PRs via the real create handlers, a cert via a signed owner push,
a private-repo bounty), thread id-keyed paths through IdSource, and drive each as
a ReadGate row: anon/signed-stranger 404, owner 2xx.

Each seeded entity carries a distinctive marker added to the read-gate withheld
set, so a 404 that leaks the entity's own content fails (not just a status
check). get_pr_diff exercises both its repo-root gate and its per-path
visibility_check loop. get_encrypted_blob stays deferred (owner twin needs live
IPFS; reclassified structurally next).

Load-bearing: an ignored-result bypass on each read turns its hostile probe RED;
a 404 leaking a seeded marker fails the body assertion.

* test(node): close the prose-excuse hatch with a mounted-route completeness gate

READ_GATE_NOT_DRIVEN allowed a free-text reason to park a read-gated handler out
of the runtime sweep. Replace the reasons with a closed NotDrivenReason enum
(ReadGatingMutation, GitSmartHttpRead, ContentAddressedRead, GlobalListFilter,
ExternalDependencyUnavailable); get_encrypted_blob moves to the last. A drivable
404-deny GET no longer type-checks a reason and is caught by a driven-not-
relabeled assertion.

Add a completeness gate that derives the required read-gate set from the mounted
route table (scrape_mounts, INV-21b), not only the source-marker scan: every
mounted repo-scoped GET must be a driven ReadGate row, a deny-bearing GET,
structurally excused, or a declared public GET — else it fails. Catches a read
that gates via a helper the marker scan does not recognize.

Load-bearing: re-parking a driven read trips the relabel assert; removing a
driven ReadGate row trips the mounts cross-check.

* test(review): harden multi-principal twin check against signer collision

Add a distinct-signer assertion to multi_principal_rows_emit_one_twin_per_arm:
the per-arm any() check is satisfied by a single twin when two Principals map to
the same Signer, so a signer_for_principal collision would leave one arm silently
untested. Assert the emitted twins carry principals.len() distinct signers
(proven RED by colliding Author->Owner). Also correct the get_cert / priv_markers
comments, which claimed a withheld cert-content marker that is not seeded — no
cert marker is needed because get_cert 404s at the repo-root gate before the cert
is fetched, so cert fields cannot reach the deny body.

* style(test): apply rustfmt to the deny-prober additions

* test(node): drive the bounty mutation gates and pin fixture object format (#195)

- submit/approve/cancel_bounty become MultiPrincipalGate registry rows
  with status-appropriate bounty fixtures (claimed/submitted/open): their
  status check fires before the auth gate, so each row seeds its own
  bounty through the real API and the arm twins consume the status
- pin --object-format=sha1 in both fixture worktrees so a sha256 default
  object format cannot break the OID equality with the served sha1 repos

* test(node): drive the caller-self task/register gates in the deny-prober (#195)

Resolve the three review findings on head 07abcc6.

Bound the two new real-node probes (protected-branch push, PR-diff) on a
timeout-bearing client, so a wedged git subprocess fails the suite rather than
hanging it until CI kills the job.

Withhold the pushed secret blob's OID (full and [..12] short form) in the PR-diff
denial. The old branch was dead code: the OID was never in the fixture seed map,
so build_branch_push_body now returns the pushed blob OIDs.

Drive every caller-self runtime deny the registry claimed but only source-marker
checked. create_task, claim_task, and register are a new SignerSelfGate class (a
body DID field bound to the authenticated signer); complete_task and fail_task
are a MultiPrincipalGate assignee arm (the caller must equal the task's stored
assignee). Each runs hostile-then-authorized against a real node. A completeness
guard, derived from a scan of src/api, now requires every did_matches(caller, X)
handler to be a driven registry row, and the module doc is reconciled to the REST
surface (the parallel GraphQL mutation gates are fenced separately, #219).

Every gate is mutation-verified load-bearing: reverting a production did_matches
line drives its hostile probe RED, and the completeness guard goes RED when a
driven row is dropped or the classifier is starved. No production code changed.

* fix(node): bracket the fallback identity-key publish with a durable marker

The hard-link fallback exposes the final key name before the PEM is
complete, so a crash in that window used to leave a partial final that
wedged every later start. Create a bounded-name .publishing marker and
fsync its name durable before create_new(final), dispose of it on every
exit with the final's removal ordered first, and remove it only once the
final is complete and durable. The marker dir fsync is warn-and-continue
so dir-fsync-hostile mounts degrade to reduced power-loss protection
instead of never provisioning.

* fix(node): recover a crash-interrupted fallback key publish at boot

A marker plus a content-failed final (empty or unparseable PEM) is now
provably an interrupted first write: boot claims one marker by atomic
rename to a .recovering file, quarantines the final preserving its
bytes, sweeps the remaining markers, and regenerates, at most once per
start. Every other failure keeps today's loud fail bit-for-bit: a bad
final without a marker, any non-content load failure (transient EIO,
mode, stat), and a second-iteration failure never touch the key. The
error class is carried as a typed root error so recovery cannot key on
message text.

* fix(node): make the fallback marker removal a commit check for stalled winners

A fallback winner stalled past the race deadline can have its round
claimed by a recovering peer: the peer renames the marker, quarantines
the in-progress final, and republishes. The winner's own-marker removal
now decides the round: removal succeeding linearizes it ahead of any
recovery, while any failure demotes it to Lost, after waiting out live
or stale .recovering claims so the follow-up load cannot observe the
pre-quarantine key. Demotion is always safe: absent interference the
Lost path re-loads the winner's own key.

* fix(node): sweep stale key-publish markers on every healthy boot

A marker orphaned between its durability fsync and create_new(final),
or a claim left by a crashed recovery, must not linger to misclassify a
much-later corruption of a good key as an interrupted first write. Both
healthy-boot arms (successful load, and a Won publish on the generate
path) now sweep stale .publishing and .recovering entries, but only
after the sweeper itself has made the final durable: a loadable final
is not necessarily synced, and removing a live winner's marker before
its sync_all would recreate the marker-less partial-final wedge on
power loss. Any durability failure skips the sweep and leaves the
markers in place.

* fix(node): make recovery claims complete, releasable, and themselves recoverable

Three review findings against the marker protocol. Recovery now claims
every publishing marker and stale recovering claim (per-item bounded
claim names), so a live publisher's own-marker commit check can no
longer falsely succeed while its round is stolen through a stale
marker; a post-claim re-parse aborts to reload when a publisher
completed in the window. Claims count toward the crash signature and
are claimable by rename, so a recoverer crash between claim and
quarantine no longer recreates the permanent wedge. Claims are released
on every exit including publish failures, closing the leak that made
demoted publishers ride the full race deadline on a dead claim. The
crash signature also needs two consecutive observations, giving a live
mid-write publisher one poll of grace before a reader can classify its
round as a crash.

* test(node): cover the quarantine-exhaustion arm and pin recovery latency

Add the missing coverage on recover_crashed_publish's degraded arms:
quarantine-name exhaustion must fall back to removing the bad final and
still regenerate, and a blocked removal must surface the chained error
loudly, with the leftover claim proven claimable on the next boot. Route
all marker-class name construction through publishing_prefix and
recovering_prefix as the single source of truth, state the dir-fsync
degradation caveat in publish_key_atomically's guarantee prose, and pin
the crash-signature short-circuit with a timing assertion so recovery
never silently regresses to riding the full race deadline.

* fix(node): protect live recoveries from the sweep and restore hijacked keys

Second-model review findings. The healthy-boot sweep now age-gates
recovering claims (2x the race deadline; a live claim is always
younger), because sweeping a live recovery's claim cancelled a demoted
publisher's clearance wait and reopened two-sided divergence; publishing
markers keep the unconditional sweep since stealing one only forces a
safe demotion. The post-claim re-parse quarantines only on content-class
failures (a transient error there releases the claims and stays loud),
and a key completed inside the re-parse-to-quarantine window is detected
by parsing the quarantined bytes and restored via no-clobber link
instead of being discarded. The crash signature must now persist for
250ms of consecutive observations, above realistic mid-write latency on
shared volumes, so concurrent starts stop hijacking live publishes.

* fix(node): keep no-clobber on the quarantine restore and scope cleanup to owned inodes

The restore now republishes the quarantined bytes through the atomic
publisher, so every tier refuses an existing final and a concurrent
winner survives; a lost restore keeps the quarantine as forensics and
loads the winner. The fallback's post-write error arms remove the final
only after proving the name still refers to the inode this publish
created, so a failing publisher whose round was claimed away can no
longer unlink the recoverer's republished key. Pre-write arms keep
by-name removal: they complete inside the crash-signature persistence
window, before any recovery can have claimed the round.

* fix(node): hand post-write publish failures to boot recovery, stamp claim freshness

A failed write or fsync on the fallback path now removes nothing: the
partial final and its marker stay in place as exactly the crash state
boot recovery claims, quarantines, and regenerates from. That deletes
the stat-then-unlink cleanup whose race could destroy a recoverer's
republished key, and can no longer strand a marker-less partial final
when an unlink fails. Pre-write failures keep removal and disposal;
they complete inside the crash-signature persistence window. Claim
renames also stamp the claim's mtime to now, because rename preserves
the source mtime and an aged stale marker otherwise births a live claim
the healthy-boot sweep would treat as orphaned mid-round.

* fix(node): key recovery claims by process nonce and harden the freshness stamp

Two PID-1 containers on a shared identity volume derive identical claim
names, and rename replaces an existing destination, so one recoverer's
release could unlink the other's live claim. Claim names now carry a
per-process nonce between pid and counter, so the release set can never
alias another process's claims. The claim-freshness stamp gains a write
fallback (a one-byte append bumps mtime where set_modified is
unsupported), and its failure warning names the real hazard. Also lock
the vanished-final re-parse arm with a dedicated regression test.

* fix(node): adopt stranded quarantined identities and age-gate claim stealing

A completed key stranded in quarantine by a failed or crash-interrupted
restore is no longer abandoned: the generate arm first scans quarantines
newest-first and republishes the first parseable one through the atomic
publisher, preserving identity continuity instead of silently minting a
fresh DID; unparseable quarantines stay as forensics. Recovering claims
become claimable only past the same age floor the sweep uses, so a
second starter can never steal a live recoverer's round mid-flight; a
claim-crash state recovers after the bounded age floor passes. The
crash-signature persistence doc now states the slow-mount trade-off
plainly: a pre-write window exceeding the floor yields churn that
converges, never divergence.

* fix(node): bound quarantine adoption, expire orphan claims, align the waiter

Adoption of a stranded quarantined identity is now bounded by the claim
age floor, so a current round's completed key is preserved while a
historical forensic quarantine can never resurrect an old DID or defeat
the delete-identity-for-fresh-DID operator procedure. A healthy boot
also schedules one delayed re-sweep after the age floor passes, so
claims spared as possibly-live cannot linger as aged residue that would
let later real corruption of a good final masquerade as a crash state
and silently regenerate. The demotion waiter now shares the sweep's
liveness rule: it waits out claims younger than the age floor rather
than a flat race deadline, and skips aged orphans quickly.

* fix(node): sweep every healthy return, supersede outcompeted quarantines, fail closed on unsettled rounds

Every arm that returns a loaded, adopted, or reloaded key now funnels
through one sweep-then-return closure, so stale markers cannot outlive
any healthy boot path. Quarantines that provably lost their round (a
Lost restore, or siblings of an adopted quarantine) move to an inert
superseded class: bytes preserved as forensics, never adoptable, so the
delete-identity-for-fresh-DID operator procedure can no longer
resurrect an outcompeted key. The demotion waiter fails closed when its
bound expires while a live young claim persists: an unsettled round now
surfaces as a loud failed publish instead of resolving a key that disk
may be about to contradict.

* fix(node): supersede on every Lost arm, heartbeat live claims, retire old forensics

Complete the supersede rule across its mirror arms: a lost adoption and
a restore-Won round now both demote every outcompeted adoptable
quarantine, so no arm leaves bytes the fresh-DID procedure could
resurrect. Live recovery rounds now heartbeat their claim mtimes every
quarter of the age floor under an RAII stop-and-join guard, making
age-as-orphan sound: an aged claim provably lost its recoverer, and a
stalled-but-live round on a slow volume can no longer be mistaken for
residue by the waiter, the sweep, or a competing recoverer. Superseded
forensic files are retention-swept after 24 hours, bounding growth on
long-lived key directories.

* fix(node): order supersede before consume, retire quarantine forensics, key the waiter on absence

Both Won arms now supersede sibling quarantines before consuming the
chosen one, so a crash in the gap cannot leave an outcompeted key
adoptable. Plain quarantine forensics get the same 24h retention sweep
as superseded files, bounding growth on long-lived key directories. The
demotion waiter drops age logic entirely: it returns Ok only when every
claim file is gone and fails the publish closed while any claim
survives the bound, young or aged, so a heartbeat failure on a hostile
volume can no longer convert a live round into orphan residue mid-wait.
Doc prose reconciled with the shipped wait contract.

* test(node): drive the #113 read/owner gates in the deny-harness fence

After merging main, the completeness fence flagged three repo-scoped list
GETs that #113 gated but the harness still treated as ungated public reads:
list_webhooks (authorize_repo_read + require_repo_owner), list_replicas and
list_protected_branches (authorize_repo_read). The runtime marker scan caught
its own hand-maintained PUBLIC_REPO_GETS list drifting stale.

Drive each real deny instead of exempting it:

- list_replicas and list_protected_branches take Option auth, so they slot in
  as standard ReadGate rows (anon and signed-non-reader both 404, owner 2xx,
  no-leak body).
- list_webhooks is doubly gated and 401s a headerless caller before any
  lookup, so a vanilla ReadGate row's hardcoded anon->404 leg does not fit.
  Add a per-Row anon_read signal (Deny404 default, Deny401 for auth-required
  reads) so its anon leg expects 401 while the signed-non-reader still drives
  the existence-hiding 404. Its owner layer is a sibling OwnerGate row on the
  public repo (signed stranger -> 403). The two share the /hooks path, so the
  consistency dedup key moves from (method, path) to (method, path, gate),
  which still catches an accidental same-gate double-registration.
- Empty PUBLIC_REPO_GETS: the three are now driven rows, classified via the
  driven-path set rather than declared public. The mechanism stays for the
  next genuinely-public repo-GET.

Each new row proven load-bearing: reverting the production gate turns the
matching hostile probe red (403->200 owner, 404->403/200 read), and flipping
list_webhooks' anon_read to Deny404 reddens its anon probe (got 401). Full
deny_harness green (39/39). No production changes.

* test(node): harden deny-harness so its guarantees can't pass vacuously

Resolve three review findings on the real-node deny harness, all test-only.

- assert_denied no longer folds a body-read error into an empty body: an
  unreadable denial (a mid-body reset/truncation) now fails loud instead of
  being certified leak-free by a withheld-token scan over "".

- The three sqlx::test cases that returned via TestNode's async Drop
  (signed_stranger_protected_branch_push_is_forbidden,
  get_pr_diff_withheld_path_is_denied,
  deny_bearing_registry_denies_hostile_and_admits_authorized) now end with
  node.shutdown().await, releasing the serve task's pool clones before sqlx's
  synchronous DROP DATABASE cleanup instead of racing it.

- A source-scrape guard, every_spawn_node_test_shuts_the_node_down, makes that
  contract load-bearing for every spawn_node test, with a closed allowlist for
  the two Drop-regression tests that deliberately skip shutdown. Removing any
  one shutdown() turns it RED (verified).

- The eight fixture seeders in support/probe.rs use the bounded client, so a
  hung setup route fails fast rather than running to the CI job timeout.

Full deny_harness suite green (40 tests).

* test(node): close two vacuity holes in the shutdown-completeness guard

An adversarial review flagged that the new every_spawn_node_test_shuts_the_
node_down guard could itself pass vacuously - the exact class it exists to
prevent (INV-21 on the guard).

- A spawn_node test whose only `node.shutdown(` occurrence was a comment
  (`// node.shutdown().await`) satisfied the raw substring check while still
  returning via Drop.
- An unbalanced `{` inside a string literal in a test body could over-extend
  the brace-matched body slice and swallow a later test's shutdown, clearing
  the earlier one (latent: no current test triggers it).

Both are closed by sanitizing the source through a new `code_only` pass
(blanks comment and string/raw-string content, length-preserving) before the
scan sees it, and the offender check is extracted to a pure
spawn_node_tests_missing_shutdown so it can be driven with synthetic sources.
Three adversarial unit tests pin both holes shut; stubbing code_only to a
no-op turns the comment and brace tests RED (verified), so the sanitizer is
load-bearing.

deny_harness suite green (43 tests); clippy clean.

* fix(ci): stub the gitlawb-node lib target in the Docker dependency cache

This branch gives gitlawb-node a lib target alongside its binary, and the
dependency-cache layer only wrote a main.rs stub for it. Cargo resolves every
declared target before it fetches anything, so the layer aborted on the missing
src/lib.rs and took the whole image build with it.

Adds the matching lib.rs stub. The layer deliberately has no `|| true`, so this
was a hard failure rather than a silently cold cache, which is the behavior that
block's comment asks for.

* fix(node): open the identity key without following symlinks, and close the temp before removing it

Two findings from the last review.

Loading an existing key ran metadata, set_permissions, a mode verify, and the
read as four separate path lookups, all of which follow symlinks. A key path
inside a writable directory could therefore be pointed at any service-readable
file, and a privileged start would chmod that target to 0600 before it ever
looked at the contents. On Unix the load now opens the path once with O_NOFOLLOW
and does the mode check, the tightening, and the read through that one
descriptor, which refuses a symlink outright and closes the window between the
check and the use. A non-regular file is refused for the same reason. A regular
key with loose bits is still narrowed rather than rejected, since rejecting it
would break existing deployments.

The failed-write path called the cleanup helper while the temp file handle was
still open. Removing an open file fails on Windows, so a write or fsync failure
left the temp behind, and the temp names are deterministic per process id with
64 of them, so a service restarting under a reused pid could exhaust the set and
stay stuck after storage recovered. The handle is now closed first, with fsync
still ahead of it since it needs the live descriptor. A removal that fails is
logged, because it is the precursor to that exhaustion, while the write error
stays the one surfaced to the caller.

* fix(node): do not block on a FIFO planted at the identity key path

The non-regular-file refusal added in the previous commit sits after the open,
and opening a FIFO read-only waits for a writer to connect. A named pipe at the
key path therefore hung startup indefinitely instead of being refused, reachable
by the same actor the symlink case assumes. The directory case did not catch it,
since opening a directory fails immediately and does reach the refusal.

Opening with O_NONBLOCK as well makes the open return so the file-type check can
run. It has no effect on a regular file, and a non-regular descriptor never gets
past the check, so nothing needs to clear it afterwards.

* fix(node): apply review fixes for identity key dir and deny harness

Tighten identity key parent directories to 0700 before load/publish,
create fallback publish markers with 0600, and extend U5b /ipfs withhold
coverage with signed non-reader denial and allowlisted-reader grant legs.
Add OwnerGate/ReadGate registry probe-shape tests.

* fix(node): close deny harness gaps after main integration

Tighten identity key parent dirs only on publish, extend INV-8 header
scanning, add inline claimant orphan guard, and align gossip ping tests
with the /ready-first readiness probe.

* ci(codeql): exclude test paths and drop secret tokens from panic text

CodeQL flagged intentional deny-harness fixtures (HTTP secret_cid probe and
pack listing assertion). Ignore tests and test_support for analysis, remove
an unused import, and keep the allow-unbounded-git marker on the harness
git spawn line.

* test(node): clear CodeQL false positives on deny harness fixtures

Reuse the signed anon probe path for the loopback GET so the cleartext-
transmission query does not flag secret_cid in the URL builder, and mark
the assert_denied panic as an intentional leak witness for cleartext-logging.

* fix(node): restore lib/bin boot regressions dropped in the deny-harness extraction

Re-wire Config::validate(), the advisory-lock pool, and gossip peer-reachability
hysteresis on the library boot path, and narrow CodeQL suppressions on fixture-only
harness assertions.

* fix(node): close remaining #194 gaps (CI lib, key parent, gossip shutdown)

Run join_or_abort lib tests in the deny-harness CI step, repair
group/world-writable key parents on existing-key load, abort gossip on
HTTP shutdown with per-peer shutdown polling, and log list_peers errors.

* test(node): restructure deny-harness fixtures to clear CodeQL alerts

Route the anonymous withheld-CID GET through an anon_get helper (matching
the unflagged signed_request pattern) so CodeQL no longer traces the
secret into a single inline HTTP expression. Redact withheld tokens from
the assert_denied panic witness so a leak failure does not itself leak
the secret to stderr. Both are test-only changes; no production code moved.

* fix(node): tighten identity-key parent-dir reload mask and add owner-push socket coverage

The reload fast-path checked only write bits (0o022) while the publish
helper checked all group/world bits (0o077), so a 0755 parent survived
reload but was tightened on publish. Align the reload mask to 0o077 so
the owner-only 0700 invariant holds across restarts, not just first
publish. Adds a regression test proving a 0755 parent is tightened on
reload (RED with the old mask, GREEN after).

Adds real socket coverage for enforce_owner_push on an unprotected
branch, isolating the owner-push gate from branch protection. The
existing protected-branch test could not distinguish which gate fired
the 403.

Updates sweep_failure_tolerated to reflect the tightened reload path: a
0555 parent is now tightened to 0700 before the sweep, so the marker is
removed rather than surviving behind a read-only directory.

* test(node): clear CodeQL alert and restore gossip readiness tests

Two findings from the 2026-09-08 review on head 988e8ea:

1. CodeQL rust/cleartext-logging on assert.rs:118. The panic sink
   interpolated redact_withheld(&reason, withheld), but CodeQL's taint
   analysis traces withheld tokens through redact_withheld without
   recognizing it as a sanitizer. Replace the interpolated panic with a
   fixed string so no tainted data reaches the sink. redact_withheld is
   still called (keeping it live) and its unit tests still pass; only the
   panic message changes. This is a test-only fixture false positive: no
   production path logs secrets.

2. Four gossip readiness tests dropped in the lib+bin split. Merge-base
   main.rs had 7 ping_peer_* tests; head had 3 renamed ping_peer_health_*
   tests. Restore the 4 missing: the /ready 200 direct happy path, the
   /ready 503 + /health 200 must-not-be-ready case, the legacy fallback
   with explicit expect-count, and the shared-deadline probe. No
   production code change; the function signatures are unchanged.

Verified: cargo fmt --check, cargo clippy -- -D warnings, 9 gossip
tests pass, 53 deny_harness tests pass (including assert unit tests).

* test(node): refresh deny harness for post-July main drift

Main's quarantine read pre-checks and task visibility layering landed
after the registry froze, so the merged table needed three classes of
refresh:

- scan hygiene: mask string/comment contents and strip cfg(test) mods
  before the marker scans, so fixture text (the resolver_body helper)
  cannot fake a decl boundary or inherit markers
- registry refresh: allowlist the read-gating mutations that gained
  authorize_repo_read (merge_pr, visibility/protect/webhook/label/
  bounty/close/replica writes, git_receive_pack), drop the task_claimable
  helper and create_task's dedicated-test-driven conditional owner gate,
  and class list_visibility (owner-driven GET) and list_anchors
  (query-scoped read) explicitly
- sweep substrate: scope the visibility twins to /swept-scope so
  set_visibility cannot 404 later strangers on the shared repo, and seed
  completable/failable tasks on the public repo so strangers reach the
  assignee 403 through get_visible_task

* test(node): restore main's lock-pool-direct for_testing semantics

The merge reconstruction derived an 8-connection lock pool inside
for_testing, so callers passing a pool observed nothing checked out.
Main's contract is that the argument IS the lock pool, which the
exhaustion, deadline, backend-reuse, and waiter-isolation tests observe
directly. Route through Self::new like for_testing_with_tigris so the
cfg(test) fields stay gated.

* fix(node): close review leaks in the deny harness and the grace knob doc

- config.rs: GITLAWB_SHUTDOWN_GRACE_SECS documented an enforced drain
  bound that production never applies; the value is only logged and axum
  drains in-flight requests unbounded. Say so.
- test_harness.rs: join_or_abort unwound a serve-task panic before
  pool.close() ran, leaking the test database on exactly the path where
  teardown matters. Carry the payload as ServeTeardown::Panicked and
  resume unwinding only after the pool and repos dir are released.
- probe.rs: the cert-push workdir was keyed on pid+server_main_tip, which
  two parallel fixtures seeding within one second share; one fixture's
  cleanup could delete another's in-progress tree. Use a tempfile
  TempDir, which is unique and also cleans up on the panic path.

* test(node): point the inv26 purge gate at lib.rs after the lib/bin split

The queue-lifecycle purge boot wiring moved from main.rs to lib.rs in the
crate split, but the source gate still scanned main.rs, so
inv26_step4_queue_lifecycle_purge_is_wired panicked in CI while the
purge itself stayed correctly wired. Scan lib.rs and update the doc and
assertion strings; the purge contract is unchanged.
kevincodex1 added a commit to kevincodex1/node that referenced this pull request Nov 17, 2026
…ead their own private repo (Twigpine#115) (Twigpine#392)

* fix(gl): status-check the client read/write surfaces so a node denial surfaces as an error, not a fake result (Twigpine#123)

Convert the gl CLI + MCP read/write surfaces to status-check the node's
response before parsing, so a denial (401/403/404) or a degraded 5xx surfaces
as an error instead of being rendered as an empty list or a fake success. The
shared http::read_json helper checks the status first and bounds the error-body
read (a hostile node can't stream an arbitrarily large error body to exhaust
the client), replacing the prior parse-before-status pattern across agent,
bounty, cert, changelog, issue, mcp, peer, pr, protect, repo, star, status,
sync, task, visibility, and webhook. A no_parse_before_status regression gate
locks the converted set in.

Rebased onto current main (squash of the prior branch). main had independently
gated several of these same surfaces, so the overlapping arms are reconciled to
keep BOTH fixes rather than let either regress:

- repo::cmd_label_list keeps main's get_maybe_signed (read-visibility gating:
  public repos stay anon-listable, a private-repo owner signs) carrying
  read_json on top; the PR's get_authed is dropped so the visibility gate holds.
- mcp webhook_list keeps main's get_signed and its signing-keypair-DID owner
  resolution (NOT resolve_owner's node DID) — list_webhooks is owner-gated AND
  auth-required, so the PR's plain get()+resolve_owner would have 401'd then
  403'd — with read_json layered for the bounded error read.
- webhook create/list/delete keep main's get_signed + resolve_owner_repo_pair
  structure and its tests, with read_json swapped in for the manual
  resp.json() so the error body is bounded. main's superseded resolve_owner
  helper and its duplicate tests are dropped.

gl: 388 unit tests + the no_parse_before_status gate green; fmt + clippy clean.

Rebased again onto current main (2026-08-11), which had moved 238 commits.
main independently landed read_body_capped and sanitize_node_msg into http.rs,
so this branch's duplicate definitions in sync.rs are dropped and read_json is
layered on main's helpers instead. main's peer.rs also grew its own announce
handling (remote_announce_failure, local_add_report/local_add_refusal, capped
read, sanitized message) which supersedes this branch's read_json conversion
there; main's side is kept whole and only peer::cmd_list, which main had not
gated, still takes read_json.

fix(gl): report why the node-DID comparison was skipped in cert show

The rebase onto main dropped did_check_report, since main's cmd_show had
been rewritten to do real Ed25519 verification and collapsed every
node-info failure into one "could not fetch current node info" NOTE.

Put the tri-state reporting back on top of main's structure: the signature
verdict and the --verify issuer anchoring are untouched, but the node-DID
comparison now names the reason it could not run and points at the offline
verification path, and "carried no DID" stays distinct from "the lookup
failed". The lookup goes through read_json so a denial yields a reason
rather than an opaque None, and it stays fail-soft: a node-info hiccup must
not turn a successfully displayed certificate into an error exit.

The DID extraction is split out as did_from_node_info so its guard is
testable. An empty did rejects rather than flowing into the comparison,
where it would print a mismatch WARNING against a DID the node never
claimed. That guard had no coverage: removing it leaves every pre-existing
test green and only the new one goes red.

fix(gl): close two completeness-gate escapes; surface the node's error key

Review of the rebased branch found the Twigpine#186 completeness gate could not fail
on the two shapes that matter most. Both were reproduced by seeding the
regression and watching the gate stay green.

An unguarded parse escaped entirely. The rule flagged a parse followed by
.is_success(), which describes one bad ordering and says nothing about a read
with no status check at all -- the more dangerous revert, since it renders a
denial body as a result. Inverted it to require a status check above the parse,
which also covers a check spelled as_u16() >= 400. The lookback is 24 lines
because sync.rs's hand-rolled Trigger arm puts its .status() 19 lines up; it
should shrink if that arm is ever routed through read_json.

Membership in the scanned set keyed on the text "read_json" rather than a call
site, so a handler fully reverted off read_json kept its membership on a
leftover comment. Still-derived meant the pinned-vs-derived equality never
fired and the deconversion shipped green, dropping the cap and the sanitizer.
Now counts call sites on non-comment lines.

read_json read only `message`, but the task API answers with `error` alone
({"error":"task not found"} in gitlawb-node/src/api/tasks.rs), so every gl task
denial rendered as the generic "request failed". Falls back to `error` through
the same sanitizer and cap; `message` still wins when both are present, which
is the shared AppError envelope. sync.rs already read both.

Also covers cmd_show --verify, which had no test at all: the issuer anchoring
is the security-bearing half of the command, since a valid signature only
proves the certificate is self-consistent and a hostile node can self-sign one.
The certificates carry real signatures, otherwise --verify would bail before
reaching the anchoring and the assertions would be vacuous.

Each fix verified by reverting it: both gate escapes go red, dropping the error
fallback fails the two new read_json tests, and removing the anchoring block
fails three of the five --verify tests.

* test(gl): pin the stats mock hits and the unsigned MCP webhook_list denial

Closes the two items left open on the last review round.

The bounty-stats denial tests were already load-bearing: breaking either
mock's route regex turns both red, because mockito answers an unmatched
route with 501 and neither test's asserted status is 501. That proof is
incidental to mockito's fallback status, though, so a reworded assertion
would silently drop it. Assert the hit directly with expect(1) +
assert_async.

MCP webhook_list keeps get_maybe_signed rather than aligning with the CLI's
get_signed. An agent driving the MCP tool may legitimately have no local
identity, and issuing the request so the node's own denial reaches the
caller is more useful than failing client-side before the node is asked.
That is only defensible if the denial actually surfaces, so pin it: no
identity plus an explicit owner must issue an UNSIGNED request and turn the
node's 401 into an error carrying the status and the node's reason, not an
empty webhook list.

The new test points at an empty temp dir instead of passing None. None
falls back to the ambient ~/.gitlawb/identity.pem, which exists on a dev box
and not on CI, so the request would have been signed here and unsigned
there; the first run of this test failed exactly that way before the dir was
pinned.

Verified by execution: swapping get_maybe_signed for get_signed reds the new
test on "must name the status", and breaking either stats mock route reds
its test. gl: 412 unit tests + the no_parse_before_status gate green; fmt
and clippy clean.

* docs(gl): describe the client-contract rules in plain English

The comments carried internal shorthand identifiers that resolve to nothing
for a reader outside this repo. Replace each with the property it names: a
denial must surface as an error rather than render as an empty or fabricated
result, and an error body must be read under a cap and sanitized before it
reaches the terminal. Comment-only; no behavior change.

Verified after the edit because the completeness gate reads source text to
decide which handlers it scans: reverting a converted handler to a bare
.json().await still turns it red. gl: 412 unit tests green, fmt and clippy
clean, cargo check --workspace --locked clean.

* test(gl): accept only a full non-success guard above a raw parse

A 404-only equality upstream counted as status evidence, so reverting a
read_json call behind agent.rs's special-404 hint to resp.json().await?
kept the fence green while a 500's denial body rendered as a result.
Require .is_success() or an as_u16() range comparison in the lookback,
and pin the distinction with a mutation regression that performs that
exact revert on the real agent.rs source.

* fix(gl): sign the visibility-gated client reads so a repo owner can read their own private repo (Twigpine#115)

`gl pr list/view/diff/comments` and `gl repo commits` loaded the caller's
keypair, used it only to derive the owner string, then built NodeClient with
None and sent an unsigned GET. Those routes are gated by authorize_repo_read,
which denies an anonymous caller with a 404, so a private repo's own owner was
told the repo had no pull requests and no commits. The six MCP read arms had
the same shape while already holding the keypair.

pr.rs now passes Some(keypair) at the four sites and calls get_maybe_signed.
repo.rs cmd_commits builds the client with load_keypair_from_dir(..).ok() so
`owner/name` against a public repo still works with no identity on disk.
mcp.rs switches repo_get, repo_commits, pr_list, pr_view (both fetches) and
pr_diff to get_maybe_signed. This is the pattern PR Twigpine#113 established for the
subset of routes it gated.

Tests: the existing happy-path mocks in pr.rs and repo.rs now assert the
signature and signature-input headers, following the protect.rs pattern;
cmd_diff gets its first test; a new test pins that the anonymous public-repo
path stays unsigned. Reverting the production hunks turns 7 tests red. Full gl
suite 365 passed, fmt and clippy clean.

DO NOT MERGE BEFORE Twigpine#186.

Review found two ordering hazards, both verified by execution.

First, this regresses public-repo reads on its own. These call sites sent no
signature before, so the node's require_signature was unreachable for them.
Now that they always sign, a client whose clock is more than 300s off gets a
400 clock_skew, and since no changed call site checks the response status, that
renders as an empty list with exit 0. A public repo the user could always read
reports itself empty. Twigpine#186 adds the status check these lines need underneath
them, which turns that failure into an error the user can act on.

Second, Twigpine#186 rewrites these same expressions and its replacement keeps
`client.get(`, so if Twigpine#186 merges after this branch it silently reverts the
signing. Land Twigpine#186 first and rebase this on top.

Known gaps left for the follow-up, none of them fixed here: the MCP arms have
no signing test and reverting all six leaves the suite green; MCP owner/repo
arguments are interpolated into the path unvalidated, so a signed request can
be aimed at another owner-gated route; the signed path is not percent-encoded,
so a non-ASCII branch or a repo argument containing a space signs a string the
node cannot reproduce; `.ok()` cannot tell a missing identity from an
unreadable one; and repo_list, repo_tree, git_refs and gl status remain
unsigned against the same class of route.

Refs Twigpine#115

* fix(gl): bind signed reads to encoded targets, surface corrupt identity

The signed read call sites interpolated caller-supplied owner, repo and
branch values straight into the request target. The target is signed as
written, so a non-ASCII branch (percent-encoded by reqwest after signing)
failed verification, and a repo argument containing "/" or "?" retargeted
an owner-signed read at a different endpoint such as the webhook list.
Percent-encode those components before signing.

Also: assert both cmd_view sub-fetch mock hits so an unsigned regression
fails, state the signer-first default in the repo_get schema, and let
cmd_commits propagate an unreadable or unparseable identity file instead
of silently reading anonymously.

---------

Co-authored-by: Kevin Codex <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

crate:node gitlawb-node — the serving node and REST API kind:security Vulnerability fix or hardening sev:high Major break or real security/trust risk, no easy workaround subsystem:api Node REST API request/response surface subsystem:visibility Path-scoped visibility and content withholding

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unauthenticated GET /repos/:owner/:repo/hooks leaks webhook target URLs for any repo

3 participants