Skip to content

Tighten input and storage validation - #48

Merged
FlyOverCoderKY merged 2 commits into
mainfrom
chore/tighten-input-and-codec-checks
Nov 6, 2026
Merged

FlyOverCoderKY merged 2 commits into
mainfrom
chore/tighten-input-and-codec-checks

Conversation

@FlyOverCoderKY

Copy link
Copy Markdown
Contributor

Summary

  • return parsed policy roots with null prototypes and resolve access from own data properties
  • snapshot token issue inputs before validation and signing
  • validate stored record schemas and key bindings
  • pin publication checkout to the event commit, confirm the tag target, and invoke the publisher directly with Node

Tests

  • CI=1 pnpm run format:check
  • CI=1 pnpm run check
  • CI=1 pnpm test

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

OpenRouter review posted (clean). #48 (review)

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
🔒 Security Review ✅ Completed 2026-11-06T14:03:35.262655Z bb79dd4 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

OpenRouter pull-request review

Verdict: issues
Scope: full-pr (full-pr)
Mode: initial
Commit: bb79dd461f8e578032c90b4322d7b2cb438c1898
Judge: openai/gpt-5.6-luna (repaired(canonical+1): source coverage preserved before publication cap)
Cost: $0.3729 (lanes $0.3672 + judge $0.0058)

Lanes

  • meta/muse-spark-1.2: ok (5 finding(s), 85.7s, 197438+9384 tokens (58737 cached), 3 tool round(s), via Meta, $0.22)
  • z-ai/glm-5.3-flash: ok (8 finding(s), 322.8s, 3586316+42551 tokens (3332288 cached), 50 tool round(s), via Makora, $0.15)

Warning

z-ai/glm-5.3-flash: coverage claims 1 finding(s) in 'docs/STORAGE.md' but 0 were reported

Findings

🟠 Issue 1 — Source authorization context snapshot does not enforce own-data properties

packages/tokens/src/issuer.ts:130 · risk · identified by meta/muse-spark-1.2

Failure scenario: snapshotContext in packages/tokens/src/issuer.ts reads value.principalId, value.policyVersion, value.roles etc. via direct property access (value.principalId) and only validates roles/permissions arrays via snapshotStringArray. An attacker-supplied SourceAuthorizationSnapshot.context that is an object with accessors or prototype-inherited fields can have its getter invoked and can return a different value on the single read than the value that would be seen through an own-data check, or leak prototype values. The IssueAccessGrantInput path was hardened with ownDataProperty and length-descriptor checks, but this sibling snapshot still trusts inherited/accessor data.

Evidence: issuer.ts:130-145 snapshotContext uses value.principalId and value.policyVersion directly; snapshotScope uses value.kind directly and checks typeof value.organizationId === "string" via direct read. Compare to snapshotIssueInput which correctly uses ownDataProperty for every field and a hardened snapshotStringArray.

Checked: packages/tokens/src/issuer.ts full file, packages/tokens/src/index.test.ts new accessor tests only cover IssueAccessGrantInput, no test for context accessors. Policy or core hardening does not apply here because this AccessContext comes from the host sourceReader, which the PR treats as trusted, but the inconsistency leaves the documented issuer wall-time-first / one-use boundary asymmetric.

🟠 Issue 2 — Publish job's unauthenticated git fetch fails on private repositories (persist-credentials: false)

.github/workflows/publish.yml:117 · risk · identified by z-ai/glm-5.3-flash

The new "Confirm the release tag target" step runs git fetch --force --no-tags origin "refs/tags/${RELEASE_TAG}:..." after a checkout with persist-credentials: false, so no credentials are persisted for that fetch. For a public repository anonymous HTTPS fetch succeeds, but if this repo is private (or is ever made private), the fetch fails with an authentication prompt error and every release publish job fails at the confirmation step, blocking all publishing. Evidence: .github/workflows/publish.yml:107-118; the publish job also has permissions: contents: read and OIDC trusted publishing, so the release flow runs entirely inside this repo's context. Counterevidence checked: npm provenance (--provenance) and the public README badge suggest a public repo, so this is a risk rather than a current breakage; the proof gap is that repo visibility cannot be confirmed from the checkout alone.

🟠 Issue 3 — Optional fields inherited from prototypes are silently dropped, not reported — silent permission loss for class/getter-based subjects and policies

packages/core/src/index.ts:171 · risk · identified by z-ai/glm-5.3-flash

resolveAccess({ principalId: "p", roles: [...] }, policy) where the subject (or policy) is a class instance or an object that exposes roles/entitlements/defaults through an inherited accessor or inherited data property now silently treats the field as absent: optionalOwnDataValue returns undefined for anything not an own property, without a diagnostic and without an error (packages/core/src/index.ts:38-50, 165-175). A host that materializes subjects as class instances with prototype getters (e.g., class TrustedSubject implements AccessSubject { get roles() { ... } }) or that reuses a shared policy prototype used to have those fields honored; after this PR the roles/entitlements simply vanish from resolution — unknownRoles/unknownEntitlements stay empty because the role never reaches the resolver, and permissions silently shrink. The prototype-pollution hardening itself is correct (and the own-accessor case throws loudly); the gap is that inherited values are dropped without any signal, unlike the accessor case. Mitigation is fail-closed (fewer permissions, not more), but the host has no diagnostic to notice it. Evidence: resolveAccessInternal reads copyOptionalStringArray(subject, "roles", "roles") and optionalPermissionMap(policy, "roles") (packages/core/src/index.ts:171-186); the test "treats optional fields inherited from custom prototypes as absent" pins the silent-drop behavior (packages/core/src/index.test.ts:128-180).

🟠 Issue 4 — listRoleAssignmentAuditEvents silently returns [] when the assignment record is missing but audit rows exist (fail-open regression)

packages/storage/src/role-store.ts:767 · risk · identified by z-ai/glm-5.3-flash

Before this PR, listRoleAssignmentAuditEvents listed the partition, and if audit positions existed for the assignment it required the authoritative assignment record via requireAssignment, throwing StorageError on a corrupt store where audit rows survived without the assignment. The rewritten function (packages/storage/src/role-store.ts:754-808) first point-reads the assignment via readAssignment and returns Object.freeze([]) when it is null — so a corrupt store with orphaned audit positions now silently reports an empty audit history instead of failing closed, and the audit trail disappears without any error. This also contradicts the unchanged docs claim that the adapter enforces "no audit position without its assignment" (docs/STORAGE.md, "In-memory reference adapter" section, around line 385) — a documented guarantee weakened without a documentation update, against AGENTS.md's rule. Evidence for absence of detection elsewhere: no other reader surfaces orphaned audit rows (listings decode them fine and listRoleAssignments filters to kind === "assignment"), and the codec accepts valid audit records regardless of whether the assignment exists.

🟠 Issue 5 — Concurrent benign writes now surface as 'corrupt record' StorageError on healthy stores, conflating races with corruption

packages/storage/src/role-store.ts:415 · risk · identified by z-ai/glm-5.3-flash

confirmRecordListing, confirmHolderListing, and confirmPointerListing (packages/storage/src/role-store.ts:415-477) point-read every listed row and reject the read with a StorageError whose message says the store "holds a corrupt record" whenever a row disappears or changes between the listing and the confirmation — which also happens on every ordinary concurrent grant/revoke, not just corruption. docs/STORAGE.md documents this ("a concurrent change between the partition listing and point confirmation may cause the read to reject"), so it is a deliberate fail-closed trade, but the concrete operational cost is that a host cache fill racing a revocation now intermittently fails the whole read, and the error message/type misleads operators into investigating corruption on a healthy store. Callers previously received a valid (non-snapshot) result in this window; there is no way to distinguish a benign race from real corruption at the error surface (same StorageError, same "corrupt record" wording for both).

🔵 Issue 6 — Core array copy uses direct length read instead of descriptor check

packages/core/src/index.ts:88 · nit · identified by meta/muse-spark-1.2

Failure scenario: copyStringArrayValue in packages/core/src/index.ts validates density via Object.getOwnPropertyDescriptor(candidate, index) but obtains the iteration bound via candidate.length directly. If candidate is an array whose own length is defined as an accessor (e.g., Object.defineProperty(arr, "length", {get: () => 1}) with two real indices), the loop bound can be spoofed to hide extra indices or to read past the intended length, diverging from the strictly descriptor-checked logic used in packages/tokens/src/issuer.ts:snapshotStringArray which validates the length descriptor is an own non-negative safe integer data property.

Evidence: packages/core/src/index.ts:88-102 for (let index = 0; index < candidate.length; index++) vs issuer.ts:115-130 which first does Object.getOwnPropertyDescriptor(value, "length") and fails if not a data value. copyStringArrayValue is used for roles, entitlements, policy.defaults and serializeAccessContext.

Checked: packages/core/src/index.ts and packages/core/src/index.test.ts; no test exercises an accessor length on a policy defaults array. The present dense array check still iterates by index descriptor, so the bug requires a crafted length accessor, but the inconsistency leaves two different hardness levels for the same threat model.

🔵 Issue 7 — Stored-record equality ignores symbol keys

packages/storage/src/role-store.ts:253 · nit · identified by meta/muse-spark-1.2

Failure scenario: storedRecordsEqual in packages/storage/src/role-store.ts compares StoredRecord objects via Object.keys, while assertExactFields in collections.ts rejects any non-string Reflect.ownKeys and Object.getOwnPropertySymbols is explicitly validated elsewhere. An encoded record that carries a symbol property (which Object.keys ignores) would appear equal to a clean record under storedRecordsEqual, so the confirmRecordListing/confirmHolderListing/confirmPointerListing check could pass even though the persisted row contains an unexpected symbol field. The row would still be rejected on decode in other paths, but this confirmation step would not surface it.

Evidence: role-store.ts:253-264 uses Object.keys(left)/Object.keys(right) and Object.hasOwn, while collections.ts:33-48 uses Reflect.ownKeys and rejects symbols. defineCollection codecs use StoredRecord as Record<string,StoredValue> but the store backend could preserve symbol keys if the underlying storage is not JSON-only.

Checked: packages/storage/src/collections.ts, packages/storage/src/role-store.ts, packages/storage/src/collections.test.ts which tests symbol rejection on input but not equality via storedRecordsEqual.

🔵 Issue 8 — Optional fields with explicit undefined silently treated as absent

packages/core/src/index.ts:45 · nit · identified by meta/muse-spark-1.2

Failure scenario: optionalOwnDataValue + copyOptionalStringArray treats an own data property whose value is explicitly undefined ({roles: undefined}) the same as a missing property — it returns [] without error. A caller that mistakenly sets roles: undefined or policy.defaults: undefined (e.g., from a JSON merge that preserves undefined instead of omitting the key) gets silent deny-by-default behavior rather than a diagnostic TypeError that would surface the misconfiguration. The strict ownDataValue path would throw for a missing required field, but this optional path intentionally swallows undefined.

Evidence: packages/core/src/index.ts:45-67 optionalOwnDataValue returns undefined for present-but-undefined, and copyOptionalStringArray:102-104 maps candidate === undefined to []. Same pattern in optionalPermissionMap. Previous code subject.roles ?? [] behaved identically, so this preserves existing semantics but retains a silent-coercion risk that the hardening otherwise tries to eliminate.

Checked: packages/core/src/index.ts, packages/core/src/index.test.ts new tests for absent and accessor cases but no test for roles: undefined explicit.

🔵 Issue 9 — Publish job fetch may lack authentication after disabling credential persistence

.github/workflows/publish.yml:107 · nit · identified by meta/muse-spark-1.2

Failure scenario: the publish job now sets persist-credentials: false on the initial actions/checkout and then runs git fetch --force --no-tags origin "refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" unauthenticated. In a public repository this succeeds anonymously, but in a private repository or in a fork with restricted token scope the fetch would fail with could not read from remote repository because GITHUB_TOKEN is no longer persisted to the git config and no Authorization header is supplied. The previous workflow checked out the tag directly via the checkout action (which authenticates even with persist-credentials: false for that single clone) and did not need a second fetch.

Evidence: .github/workflows/publish.yml:107-122 adds persist-credentials: false and a manual git fetch. tests/release-packages.test.ts:471-486 asserts this exact fetch sequence and persist-credentials: false, confirming the intended behavior; no test or doc (docs/RELEASING.md, docs/securityscan.md) notes the private-repo limitation.

Checked: .github/workflows/publish.yml, .github/workflows/ci.yml for sibling pattern, docs/RELEASING.md release recovery section, and grep for persist-credentials (only this file).

🔵 Issue 10 — Dead tautological check in listRoleAssignmentAuditEvents

packages/storage/src/role-store.ts:782 · nit · identified by z-ai/glm-5.3-flash

if (grantPosition.sequence !== grantRecord.sequence) (packages/storage/src/role-store.ts:782-784) can never fire: grantPosition was just validated by requireLifecyclePosition(..., GRANT_SEQUENCE, ...) to have sequence === GRANT_SEQUENCE, and grantRecord is built by grantAuditRecord, whose sequence is the same GRANT_SEQUENCE constant. The guard reads like corruption detection but is dead code; if the intent was to cross-check the derived audit record, it should compare something that can actually differ (e.g., grantPosition.eventId).

🔵 Issue 11 — resolveAccess now throws on null map entries that previously resolved to no permissions

packages/core/src/index.ts:148 · nit · identified by z-ai/glm-5.3-flash

ownPermissions previously used assignments[name] ?? [], so a policy entry like { roles: { support: null } } resolved as an empty grant set; now descriptor.value === undefined treats only undefined as empty, and null falls into copyStringArrayValue(null, ...), throwing TypeError: policy.roles.support must be an array of strings (packages/core/src/index.ts:135-158). A host that generated policies with explicit null entries (e.g., template-driven config emitting null for roles with no grants) moves from silently resolving to a runtime exception on every request. This is fail-closed and parsePolicy never emits nulls, but it is an undocumented behavior change on inputs the public API previously accepted.

🔵 Issue 12 — parsePolicy output no longer accepted by validatePolicy (null-prototype vs JSON-object input check)

packages/policy/src/index.ts:117 · nit · identified by z-ai/glm-5.3-flash

parsePolicy now returns a null-prototype frozen object (packages/policy/src/index.ts:464-483), but plainRecordIssue still requires input to satisfy Object.getPrototypeOf(value) === Object.prototype (packages/policy/src/index.ts:115-120), so a host that re-validates an already-parsed, cached policy document through validatePolicy — which worked before this PR, when the parsed policy was a plain object — now gets invalid_structure ("Expected an ordinary JSON object."). JSON.stringify/parse round-trips remain supported and the documented input contract is "produced by JSON.parse", so this is a nit: the previously working re-validation flow breaks silently with only a generic diagnostic.

🔵 Issue 13 — Sequential unbatched point reads in confirmRecordListing for the two principal listings

packages/storage/src/role-store.ts:419 · nit · identified by z-ai/glm-5.3-flash

listActiveRoleAssignments and listRoleAssignments confirm every decoded row with a sequential await records.get(key) inside a plain for-loop (packages/storage/src/role-store.ts:415-436, called at lines 596-600 and 618-622), unlike the by-role read whose verification is batched 16-wide. For a principal with a long assignment history, the listing now costs an extra serialized point-read per row on top of the partition listing, with latency growing linearly; docs/STORAGE.md documents the extra confirmation but mentions batching only for the by-role path, so the cost asymmetry between the two listing flavors is easy to miss when sizing hosts. Minor, documented-ish, but a real latency regression for large partitions.

Workflow run

Comment thread packages/tokens/src/issuer.ts Resolved
Comment thread .github/workflows/publish.yml Resolved
Comment thread packages/core/src/index.ts Resolved
Comment thread packages/storage/src/role-store.ts Resolved
Comment thread packages/storage/src/role-store.ts Resolved
Comment thread packages/core/src/index.ts Resolved
Comment thread .github/workflows/publish.yml Resolved
Comment thread packages/storage/src/role-store.ts Resolved
Comment thread packages/core/src/index.ts Resolved
Comment thread packages/storage/src/role-store.ts Resolved

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

OpenRouter pull-request review

Verdict: clean
Scope: latest-commit (commit-range)
Mode: verify
Commit: f863d1c03a0911cd2a90f006fd43e81972f2f369
Judge: openai/gpt-5.6-luna
Cost: $0.1883 (lanes $0.1882 + judge $0.0001)

Lanes

  • meta/muse-spark-1.2: ok (0 finding(s), 40.2s, 110186+3937 tokens (11731 cached), 3 tool round(s), via Meta, $0.14)
  • z-ai/glm-5.3-flash: ok (0 finding(s), 236.0s, 766032+24359 tokens (670720 cached), 21 tool round(s), via Friendli, $0.0466)

Round 2 resolution

  • ✅ r1-1 fixed correctly — Source authorization context snapshot does not enforce own-data properties: packages/tokens/src/issuer.ts now snapshots via ownDataProperty (getOwnPropertyDescriptor, value check) for principalId/policyVersion/roles/entitlements/permissions and scope.kind/organizationId and input.*, with snapshotStringArray checking own length descriptor and per-index own data descriptors. No direct value.foo getter invocation remains; tests in `packages/tokens/src/index.t…
  • ✅ r1-2 fixed correctly — Publish job's unauthenticated git fetch fails on private repositories (persist-credentials: false): .github/workflows/publish.yml:116-126 now authenticates the tag fetch even with persist-credentials:false via ephemeral GITHUB_TOKEN → AUTHORIZATION: basic extraheader (GIT_CONFIG_COUNT/KEY_0/VALUE_0) and unsets secrets after. Verified against tests/release-packages.test.ts which now asserts presence of token injection, extraheader config, and absence of git config leakage.
  • 🤝 r1-3 disputed — Optional fields inherited from prototypes are silently dropped, not reported — silent permission loss for class/getter-based subjects and policies: packages/core/src/index.ts:47-62 intentionally treats non-own optional fields as absent (optionalOwnDataValue → undefined → []) and own accessors as error, documented in docs/POLICY.md:76-82 as Inherited optional fields are ignored.... This is a fail-closed deny (permission loss, not grant) for class/prototype subjects; hosts are required to supply plain own-data subjects/policies. Doc…
  • ✅ r1-4 fixed correctly — listRoleAssignmentAuditEvents silently returns [] when the assignment record is missing but audit rows exist (fail-open regression): packages/storage/src/role-store.ts:787-808 now fail-closes when assignment missing: lists partition for StoredAudit positions for assignmentId and throws corrupt(... lifecycle positions without a record) if any exist instead of returning []. Includes miskeyed position check. Covered by two new tests in packages/storage/src/collections.test.ts.
  • ✅ r1-5 fixed correctly — Concurrent benign writes now surface as 'corrupt record' StorageError on healthy stores, conflating races with corruption: confirmRecordListing/confirmHolderListing/confirmPointerListing now split errors: malformed key/duplicate → corrupt, vanished/changed between list and point-get or storedRecordsEqual mismatch → changedDuringRead("... moved") with retry message. Batched in 16 (RECORD_CONFIRM_BATCH/HOLDER_VERIFY_BATCH) and documented in docs/STORAGE.md:355-362; tests updated to expect retry vs `cor…
  • 8 nit finding(s) from earlier rounds retired (severity floor for follow-up rounds is risk).
  • Open findings after this round: 0 (0 bug-severity).

No structured findings from the successful lane(s).

Workflow run

@FlyOverCoderKY
FlyOverCoderKY merged commit ada1f3a into main Nov 6, 2026
5 checks passed
@FlyOverCoderKY
FlyOverCoderKY deleted the chore/tighten-input-and-codec-checks branch November 6, 2026 18:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant