← Back to Pull requests

Security: invariant prefix-skip scans make guaranteed forward progress on hostile keys #1163

Merged
c1-squire-dev[bot] merged 3 files (370 lines) on Oct 03, 2026 18:22 UTC
View on GitHub
c1-squire-dev[bot] c1-squire-dev[bot] commented on Oct 03, 2026 17:38 UTC
Author

Summary

C1Z-SEC-006 (CWE-835). The syncer's referential invariants (I3, I7, I8, I9) run as group-skip scans over the Pebble keyspace. Each scan visits the first key of a group, then SeekGEs past the group, so a pass costs one seek per distinct group.

The skip target was built by decoding the key's tuple components and re-encoding them. For two non-canonical shapes the re-encoded prefix sorts below the key, so SeekGE landed on the same key and the scan spun at full CPU until its context was cancelled:

  • Byte 2 is not the tuple separator. The iterator covered the 2-byte [v3|type] family. The decoder assumed a separator at byte 2, and the re-encoded prefix always has one.

  • I8 identity flag other than "0"/"1". The scan folded any such value to "0".
  • A hostile .c1z reaches these scans through the syncer and the compaction worker.

    Changes

  • forEachKeyGroup (ingest_facts.go) is the one group-skip loop for all four scans. It owns the iterator bounds, the ctx check, component decoding, malformed-key rejection and the skip. The skip seeks to the upper bound of the visited key's own prefix. That bound sorts after every key sharing the prefix, so the scan advances whatever the key bytes are. Pagination cursors and grant-digest partition repair already derive their seeks from raw key bytes; these scans were the exception.

  • Malformed keys fail the scan with a malformed key error. The helper covers the whole record family and rejects:

  • - a key without the tuple separator after the header;
    - a key with fewer than the scan's separator-terminated components.

    I8 also rejects a flag other than "0"/"1".

  • Each scan now holds only its per-group logic. I9 (ForEachDanglingGrantPrincipal) was not exploitable, because its iterator already started at the separator. It used the same decode→re-encode skip, though, so it moves onto the helper too, and no scan keeps that pattern.
  • Behavior changes

  • Unparseable keys in these families are now errors in all four scans. Before this, I9 ignored a by_principal key that lacked the separator, and I8 accepted a grant key that ended inside the entitlement identity. No writer produces either shape: every grant, entitlement and by_principal key builder emits the separator, and grant primary keys have six components.

  • Well-formed keys are grouped exactly as before. The tuple escape decoder is strict, so decode→re-encode reproduced valid keys byte for byte, including both flag values.

  • Cost is unchanged: one seek per group, with one fewer allocation per seek.
  • Tests

  • TestSecurity_IngestScansRejectNonCanonicalKeys runs each hostile shape against every scan that reads it:

  • - bad header byte (I3, I7, I8, I9);
    - flag "2" (I8);
    - a grant key that ends inside the identity (I8).

    Each must return malformed within 10s. To check that the test can fail, I reverted the skip to decode→re-encode and dropped the header check; the four header cases then failed at the deadline.

  • TestIngestScansVisitEachGroupOnce writes two grants per entitlement and per principal. I3, I7, I8 and I9 each visit every group once, and stripped and opaque identities on one resource stay distinct.

  • Existing tests also pass: TestIngestScansFailLoudOnMalformedKeys, TestIngestScanSurfaceAfterCloseReturnsClosing, and the pkg/sync referential invariant tests.

  • golangci-lint run ./...: 0 issues.

  • go test -short -tags=baton_lambda_support ./...: passes.

  • go test -race: passes on pkg/dotc1z/engine/pebble and pkg/sync.
  • Diff: 370 lines (+207 / -163) across 3 files Reviewer: pquerna Review duration: 43m
    All Vouch review confidence checks passed
    Residual risk 0.09 = Change Risk (0.65) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.65 · 370 lines diff across 3 files
    0.65
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.86 · 4 substantive comment(s)
    0.86
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.354
    Sensitive Paths sensitive_paths
    0.065
    Real PR Conversation Timeline
    8 items
    github-actions[bot] github-actions[bot] commented on Oct 03, 2026 17:39 UTC
    Bot

    <!-- review-superseded: {"report_comment_id": 5971757660, "run_id": "37141266902", "run_attempt": "1"} -->
    <details>
    <summary>Superseded — see the <a href="https://github.com/ConductorOne/baton-sdk/pull/1163#issuecomment-5971757660">current review report</a> for commit <code>a933f7f11af7</code></summary>

    General PR Review: Security: invariant prefix-skip scans make guaranteed forward progress on hostile keys

    Blocking Issues: 0 | Suggestions: 1 | Threads Resolved: 0
    Criteria: Criteria status: loaded .claude/skills/ci-review.md from trusted base 768d840ca236.
    _Review mode: full_
    View review run

    Review Summary


    The PR changes the three prefix-skip scans in pkg/dotc1z/engine/pebble/ingest_facts.go (I3, I7, I8). Each one now rejects keys whose byte 2 is not 0x00, and the dangling scan also rejects flag components other than "0" or "1". Each scan now builds its SeekGE target from the current key's raw bytes (key[:skipLen]) instead of decoding and re-encoding the components, so the iterator always moves forward. A new red/green test covers this, and ingest_repair.go only gets a doc comment.

    I scanned the full diff (3 files) for security and correctness. I checked the splice offsets against codec.DecodeTupleStringAlias. That function returns the offset of the next separator, and the escape rules (0x00→0x01 0x01, 0x01→0x01 0x02) mean an encoded component never contains a bare 0x00. So headerLen+ridEnd+1 and headerLen+off always end on the component's own separator. KeyUpperBound can't return nil there, because the spliced prefix ends in 0x00, or is clamped to a key that starts with the v3 header. I also checked that canonical grant and entitlement keys always have bytes after rid, so the new ridEnd >= len(tail) rejection only applies to malformed keys. Legacy single-component entitlement keys were already rejected by the existing next >= len(tail) check. I confirmed the doc claim about ForEachDanglingGrantPrincipal: its prefix includes the separator, and a valid escape sequence decodes and re-encodes to the same bytes.

    Repo criteria applied, triage:

  • Silence: no. The old failure was a visible hang, and the new behaviour is a typed error.

  • Durability: no. Key format, proto, and serialized state are unchanged.

  • Uncontrolled dimensions: yes, hostile or malformed input. The test plants these keys directly.

  • Consumer distance: same package.

  • Consequence: rung 1 (redeploy).

  • Verdict: LOW.
  • The scan cost stays O(distinct) seeks, and the change removes an allocation per seek, so the cost-curve rule needs no new benchmark. There are no exported API, proto, default, dependency, or version changes. Malformed keys that were silently tolerated now fail the invariant pass. That is intentional and matches the policy of #1160.

    Security Issues


    None found.

    Correctness Issues


    None found.

    Suggestions


  • New (low severity, high confidence): the PR description says the raw splice "also fixes the flag fold for legitimate keys: two entitlements differing only in stripped/opaque flag were previously skipped as one." The old code doesn't support that. It set stripped: comps[2] == idFlagStripped and re-encoded with id.flagComponent() (identity.go:47-52), so canonical "0"/"1" keys round-tripped exactly and were never folded. The fold only affected non-canonical flags such as "2". Because of this, the "two-flag distinctness" check in the control subtest (ingest_facts_security_test.go:~146) would pass before the fix too, so it is not a regression guard for a fixed bug. Please correct the PR description so nobody sets out to remediate a legitimate-key I8 miscount that never existed.
  • </details>

    github-actions[bot] github-actions[bot] commented on Oct 03, 2026 17:40 UTC
    Bot

    <!-- review-superseded: {"report_comment_id": 5972028679, "run_id": "37143158106", "run_attempt": "1"} -->
    <details>
    <summary>Superseded — see the <a href="https://github.com/ConductorOne/baton-sdk/pull/1163#issuecomment-5972028679">current review report</a> for commit <code>495ce7998c05</code></summary>

    General PR Review: Security: invariant prefix-skip scans make guaranteed forward progress on hostile keys

    Blocking Issues: 0 | Suggestions: 1 | Threads Resolved: 0
    Criteria: Criteria status: loaded .claude/skills/ci-review.md from trusted base 768d840ca236.
    _Review mode: full_
    View review run

    Review Summary


    The PR changes the three prefix-skip scans in pkg/dotc1z/engine/pebble/ingest_facts.go (I3, I7, I8). Each one now rejects keys whose byte 2 is not 0x00, and the dangling scan also rejects flag components other than "0" or "1". Each scan now builds its SeekGE target from the current key's raw bytes (key[:skipLen]) instead of decoding and re-encoding the components, so the iterator always moves forward. A new red/green test covers this, and ingest_repair.go only gets a doc comment.

    I scanned the full diff (3 files) for security and correctness. I checked the splice offsets against codec.DecodeTupleStringAlias. That function returns the offset of the next separator, and the escape rules (0x00→0x01 0x01, 0x01→0x01 0x02) mean an encoded component never contains a bare 0x00. So headerLen+ridEnd+1 and headerLen+off always end on the component's own separator. KeyUpperBound can't return nil there, because the spliced prefix ends in 0x00, or is clamped to a key that starts with the v3 header. I also checked that canonical grant and entitlement keys always have bytes after rid, so the new ridEnd >= len(tail) rejection only applies to malformed keys. Legacy single-component entitlement keys were already rejected by the existing next >= len(tail) check. I confirmed the doc claim about ForEachDanglingGrantPrincipal: its prefix includes the separator, and a valid escape sequence decodes and re-encodes to the same bytes.

    Repo criteria applied, triage:

  • Silence: no. The old failure was a visible hang, and the new behaviour is a typed error.

  • Durability: no. Key format, proto, and serialized state are unchanged.

  • Uncontrolled dimensions: yes, hostile or malformed input. The test plants these keys directly.

  • Consumer distance: same package.

  • Consequence: rung 1 (redeploy).

  • Verdict: LOW.
  • The scan cost stays O(distinct) seeks, and the change removes an allocation per seek, so the cost-curve rule needs no new benchmark. There are no exported API, proto, default, dependency, or version changes. Malformed keys that were silently tolerated now fail the invariant pass. That is intentional and matches the policy of #1160.

    Security Issues


    None found.

    Correctness Issues


    None found.

    Suggestions


  • New (low severity, high confidence): the PR description says the raw splice "also fixes the flag fold for legitimate keys: two entitlements differing only in stripped/opaque flag were previously skipped as one." The old code doesn't support that. It set stripped: comps[2] == idFlagStripped and re-encoded with id.flagComponent() (identity.go:47-52), so canonical "0"/"1" keys round-tripped exactly and were never folded. The fold only affected non-canonical flags such as "2". Because of this, the "two-flag distinctness" check in the control subtest (ingest_facts_security_test.go:~146) would pass before the fix too, so it is not a regression guard for a fixed bug. Please correct the PR description so nobody sets out to remediate a legitimate-key I8 miscount that never existed.
  • ---
    Reviewed commit: a933f7f11af7
    <!-- review-state: {"last_reviewed_sha": "a933f7f11af768d229f79c42e93e6e79253c15d5", "base_sha": "768d840ca23627e6acf250d1fe5eb9d0accaa64d", "workflow_ref": "ConductorOne/github-workflows/.github/workflows/general-pr-review.yaml@refs/heads/main", "run_id": "37141266902", "run_attempt": "1", "summary_marker": "### General PR Review:", "verdict_mode": "baseline", "publication": "completed", "started_at": "2026-10-03T17:39:01Z", "working_comment_id": 5971744849, "working_comment_updated_at": "2026-10-03T17:40:30Z"} -->

    </details>

    github-actions[bot] github-actions[bot] commented on Oct 03, 2026 17:40 UTC
    Reviewer

    No blocking issues found — see the full review report

    <!-- review-publication: {"run_id": "37141266902", "run_attempt": "1", "workflow_ref": "ConductorOne/github-workflows/.github/workflows/general-pr-review.yaml@refs/heads/main", "summary_marker": "### General PR Review:", "verdict_mode": "baseline", "report_comment_id": 5971757660} -->

    github-actions[bot] github-actions[bot] commented on Oct 03, 2026 18:09 UTC
    Bot

    <!-- review-superseded: {"report_comment_id": 5972028679, "run_id": "37143158106", "run_attempt": "1"} -->
    <details>
    <summary>Superseded — see the <a href="https://github.com/ConductorOne/baton-sdk/pull/1163#issuecomment-5972028679">current review report</a> for commit <code>495ce7998c05</code></summary>

    General PR Review: Security: invariant prefix-skip scans make guaranteed forward progress on hostile keys

    Blocking Issues: 0 | Suggestions: 0 | Threads Resolved: 0
    Criteria: Criteria status: loaded .claude/skills/ci-review.md from trusted base 768d840ca236.
    _Review mode: incremental since a933f7f_
    View review run

    Review Summary


    The new commits move all four referential-invariant scans (I3 ForEachDistinctGrantEntitlementResource, I7 ForEachDistinctEntitlementResource, I8 ForEachDanglingGrantEntitlement, I9 ForEachDanglingGrantPrincipal) onto one helper, forEachKeyGroup (ingest_facts.go:136). The helper bounds the iterator to the whole 2–3 byte family and rejects keys without the header separator or with fewer than n separator-terminated components. After each group it seeks to upperBoundOf(key[:off]), where off is one past the n-th separator. That target is always strictly greater than the current key, so every scan makes progress. I scanned the full PR diff (3 files) for security and correctness issues and checked the helpers it relies on:
  • codec.KeyUpperBound copies its input, so the uncapped key[:off] slice cannot alias or mutate the iterator buffer.

  • DecodeTupleStringAlias returns the separator offset as end.

  • key[:off] always ends in 0x00, so the bound is never nil.

  • No writer emits non-separator keys under [v3,typeIndex,idxGrantByPrincipal] (keys.go:185,265,273), so widening I9 to the 3-byte family adds no false rejections. The same holds for grant and entitlement keys.
  • For well-formed keys, grouping is byte-identical to the previous decode→re-encode skip. The tests cover each hostile shape against every scan that reads it, plus a group-once control that includes I9.

    Repo criteria triage:

  • Silence: no. Malformed keys now fail loudly instead of hanging.

  • Durability: no. The scans write nothing new; the orphan-heal path is unchanged.

  • Uncontrolled dimensions: no. Cost stays at one seek per group, and the change only touches attacker-supplied byte shapes.

  • Consumer distance: low. These are package-internal engine methods; exported signatures are unchanged.
  • Verdict: LOW, so no escalation. No exported API, proto, serialized-state, default or dependency surface changes. The cost-curve rule for compaction-adjacent paths is satisfied because the cost is unchanged (O(distinct groups) seeks, stated in the PR). The only behavior change is that truncated or non-canonical keys now return errors, which the PR documents.

    Security Issues


    None found.

    Correctness Issues


    None found.

    Suggestions


    None.

    Resolved prior findings


  • Fixed — the earlier note that the PR description wrongly claimed a fold fix for legitimate stripped/opaque keys. The description now says "Well-formed keys are grouped exactly as before… including both flag values", and the control test is framed as a grouping check (TestIngestScansVisitEachGroupOnce), not a regression guard.
  • </details>

    github-actions[bot] github-actions[bot] commented on Oct 03, 2026 18:11 UTC
    Bot

    General PR Review: Security: invariant prefix-skip scans make guaranteed forward progress on hostile keys

    Blocking Issues: 0 | Suggestions: 0 | Threads Resolved: 0
    Criteria: Criteria status: loaded .claude/skills/ci-review.md from trusted base 768d840ca236.
    _Review mode: incremental since a933f7f_
    View review run

    Review Summary


    The new commits move all four referential-invariant scans (I3 ForEachDistinctGrantEntitlementResource, I7 ForEachDistinctEntitlementResource, I8 ForEachDanglingGrantEntitlement, I9 ForEachDanglingGrantPrincipal) onto one helper, forEachKeyGroup (ingest_facts.go:136). The helper bounds the iterator to the whole 2–3 byte family and rejects keys without the header separator or with fewer than n separator-terminated components. After each group it seeks to upperBoundOf(key[:off]), where off is one past the n-th separator. That target is always strictly greater than the current key, so every scan makes progress. I scanned the full PR diff (3 files) for security and correctness issues and checked the helpers it relies on:
  • codec.KeyUpperBound copies its input, so the uncapped key[:off] slice cannot alias or mutate the iterator buffer.

  • DecodeTupleStringAlias returns the separator offset as end.

  • key[:off] always ends in 0x00, so the bound is never nil.

  • No writer emits non-separator keys under [v3,typeIndex,idxGrantByPrincipal] (keys.go:185,265,273), so widening I9 to the 3-byte family adds no false rejections. The same holds for grant and entitlement keys.
  • For well-formed keys, grouping is byte-identical to the previous decode→re-encode skip. The tests cover each hostile shape against every scan that reads it, plus a group-once control that includes I9.

    Repo criteria triage:

  • Silence: no. Malformed keys now fail loudly instead of hanging.

  • Durability: no. The scans write nothing new; the orphan-heal path is unchanged.

  • Uncontrolled dimensions: no. Cost stays at one seek per group, and the change only touches attacker-supplied byte shapes.

  • Consumer distance: low. These are package-internal engine methods; exported signatures are unchanged.
  • Verdict: LOW, so no escalation. No exported API, proto, serialized-state, default or dependency surface changes. The cost-curve rule for compaction-adjacent paths is satisfied because the cost is unchanged (O(distinct groups) seeks, stated in the PR). The only behavior change is that truncated or non-canonical keys now return errors, which the PR documents.

    Security Issues


    None found.

    Correctness Issues


    None found.

    Suggestions


    None.

    Resolved prior findings


  • Fixed — the earlier note that the PR description wrongly claimed a fold fix for legitimate stripped/opaque keys. The description now says "Well-formed keys are grouped exactly as before… including both flag values", and the control test is framed as a grouping check (TestIngestScansVisitEachGroupOnce), not a regression guard.
  • ---
    Reviewed commit: 495ce7998c05
    <!-- review-state: {"last_reviewed_sha": "495ce7998c052ba1c0b1558a7654d26a72135ce4", "base_sha": "768d840ca23627e6acf250d1fe5eb9d0accaa64d", "workflow_ref": "ConductorOne/github-workflows/.github/workflows/general-pr-review.yaml@refs/heads/main", "run_id": "37143158106", "run_attempt": "1", "summary_marker": "### General PR Review:", "verdict_mode": "baseline", "publication": "completed", "started_at": "2026-10-03T18:09:55Z", "working_comment_id": 5972016392, "working_comment_updated_at": "2026-10-03T18:11:13Z"} -->

    github-actions[bot] github-actions[bot] commented on Oct 03, 2026 18:11 UTC
    Reviewer

    No blocking issues found — see the full review report

    <!-- review-publication: {"run_id": "37143158106", "run_attempt": "1", "workflow_ref": "ConductorOne/github-workflows/.github/workflows/general-pr-review.yaml@refs/heads/main", "summary_marker": "### General PR Review:", "verdict_mode": "baseline", "report_comment_id": 5972028679} -->

    pquerna pquerna approved these changes on Oct 03, 2026 18:22 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    c1-squire-dev[bot] c1-squire-dev[bot]
    Labels
    risk: low confidence: 85.4% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 64.5% (MEDIUM) · Higher = larger blast radius
    64.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.4% · Lower = rushed or shallow review
    85.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 9.4% · Safe to merge
    9.4%