Skip to content

perf(codex): use owner-held credentials at the fetch boundary - #170656

Merged
steipete merged 22 commits into
mainfrom
dbasync/authowner5-guard
Oct 13, 2026
Merged

steipete merged 22 commits into
mainfrom
dbasync/authowner5-guard

Conversation

@steipete

@steipete steipete commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Codex token-sharing OAuth still rereads SQLite on the Gateway main thread immediately before bearer-authenticated fetch. This change makes that final assertion read the credential authority's committed in-memory facts. Cold preparation uses the existing async worker reader; the synchronous effect guard keeps its identity and refresh validation without issuing SQL or worker requests.

This is the final reader cutover after the landed writer changes in #170632 and #170583. Their publication changes are prerequisites: every supported credential writer must deny before mutation and publish settlement before this reader can replace the final database read.

Ownership and writer coverage

The existing personal credential authority also owns shared config_machine_state['authProfiles.store'] and agent auth_profile_store['primary'] facts. This PR carries its retained per-source getter through the internal auth read owner and the existing nonenumerable readCurrentCredential result field. There is no parallel credential owner and no function added to the serializable AuthProfileStore.

The getter follows local agent → explicitly scoped shared → ambient shared precedence. It retains absent-local dependencies so a later local insertion takes precedence, observes deletion and shared fallback, and survives temporary worker read-scope disposal. Closing the underlying authority revokes the getter. Catalog workers return committed facts rather than a host effect capability.

The extended writer-entry ratchet covers the publication graph established by the earlier PRs:

Writer family Covered route
Login/import/setup/provider persistence, logout, OAuth claim/replace/fail/restore and peer removal Native save/update facades and async authProfiles.update construction reach the canonical credential publication sinks.
External CLI sync, secrets apply/rollback and exact snapshot restoration Native ensure/load readers and save/restore writers remain in the graph because reads can persist external credentials.
Doctor/import/relocation Runtime writes use the same sinks; stopped-owner maintenance retains its explicit custody exception.
Catalog worker writes Host batch denial, catalog custody entry and committed receipt capture remain paired.
Released synchronous SDK save/upsert and native AuthStorage Reviewed exports and native facades enter managed transaction custody and synchronous publication before SQL.
Generic machine-state writes accepting the credential key Normalized protected/dynamic keys and machineState.write construction require the host publication adapter; TUI/onboarding workers construct their bounded noncredential namespaces.

The ratchet resolves named, namespace, computed and destructured references, selected dynamic imports (including Promise.all and .then), nested writer calls, facade forwarding and worker command construction. Unused sibling exports do not count as writer access; namespace escapes and actual protected selections remain guarded. Synthetic bypass fixtures must reject new routes around publication. It audits the current source graph and compatibility exports; it is not a general security type system for arbitrary reflection or dynamically constructed worker programs.

PR1's public P2 ratchet follow-ups remain future syntax extensions: raw REPLACE/UPDATE OR, Kysely replaceInto, and onConflict key reassignment. No existing production credential bypass using these forms was found. These limitations are recorded rather than expanding this cutover into another general SQL analyzer.

Preserved security semantics

Credential mutations deny synchronously before commit. Committed facts install before the denial is released; unknown outcomes remain denied until the owner restarts. Usage, order and cooldown-only changes remain outside credential revocation. Released synchronous SDK signatures remain unchanged.

The final assertion still validates issuer, client ID, subject and auth-flow fingerprint for the selected profile. Profile fallback remains disabled and the resolved profile ID must match. While the durable OAuth refresh claim temporarily removes the ID token, only the exact previously validated refresh generation with matching flow, issuer and client ID may join. A persisted credential without a retained authority getter is refused. Runtime-only credentials continue to use mutable in-memory state and observe removal.

Removed path and accepted edge cases:

  • The synchronous native final SQL fallback is deleted. Unsupported external concurrent database writes do not invalidate in-process facts; outside writers must use the Gateway or hold exclusive ownership while it is stopped.
  • The personal/native final-reader split is deleted. Missing authority for a persisted profile refuses the request instead of falling back to SQL or a captured snapshot.
  • An HTTP request whose effect already started may finish. No new bearer-authenticated effect starts while credential publication is pending or its outcome is unknown.

The security check itself remains immediately before native fetch after awaited preparation. No admitted-write relaxation, polling read, new generation or additional handshake is introduced.

Measurements

The direct native-boundary test uses the actual released SDK save, OAuth resolution and guarded fetch for both shared and agent stores. The baseline probe at 592b7e4aea9386e05912e6df2d3ba5493e629aaa measured three warmed assertions per scope. Final candidate boundary CI at f75d70303829cd9790d37a288968de4b69c6df59 passed both cases (681 ms shared / 702 ms agent) and all nine OAuth adapter cases: job.

Final credential assertion Base Candidate
MAIN SQL statements, median [min–max], each scope 2 [2–2] 0 [0–0]
Worker requests, median [min–max], each scope 0 [0–0] 0 [0–0]
Native SQL sites reachable from Codex final guard 2 0
Static lane T1 sites 2 2: released synchronous SDK reader retains both primitives

The sole workload pair used harness 2.1.0, base cbb3812a9ee0c54bd833ebfdc4423f66d424d022 and candidate b8df112c3b520182d9600329fb33bb660b2c335b. Both completed ten warmed turns. These are turn medians from one alternating base/candidate pair, not three run pairs. Both measured revisions already include the parent writer-publication changes. The synthetic API-key workload does not exercise the Codex token-sharing guard.

Warmed all-thread metric Base Candidate
Causal SQL statements, median [min–max] 170 [170–170] 169 [169–186]
Causal requests, median [min–max] 41 [41–42] 41 [41–44]
Causal MAIN SQL, median [min–max] 0 [0–0] 0 [0–0]
Causal SQL / requests, mean 170 / 41.1 170.7 / 41.4
Wall-window SQL, median [min–max] 180.5 [179–222] 212.5 [178–284]
Wall-window requests, median [min–max] 45 [44–57] 55 [44–76]
Shared read family Base SQL / requests per turn Candidate SQL / requests per turn
Exact-entry facts 4 / 4 4 / 4
Actor hydration 1 / 1 1.1 / 1.1
Entry-cache snapshots 0 / 0 0 / 0
Row facts 0 / 0 0 / 0
Watermark reads 1 / 1 1 / 1
Auth rows 1 / 1 1.1 / 1.1

Nine candidate turns used 169 statements. The ordinary one-statement reduction is an inherited participant-projection optimization; it is not credited to this credential change. Candidate turn 04 adds 17 SQL / 3 requests: transcript anchors +9/+1, activity-summary source +6/+1, actor rehydration inside an existing append +1/+0, and scoped auth rows +1/+1. Native stacks show the preceding transcript rewrite using the existing fallback branch and the following append rehydrating. The precise cause of that resident-token miss is not recorded. The scoped auth read follows summary preparation by 10 ms; its truncated origin stack supports correlation, not a proven parent-call attribution.

The immutable-source attribution also covers indirect shared-family effects: the authority, domain-publication and SDK/native writer-custody modules are identical between these measured heads. The new SQL preparation is entered only by non-personal chatgpt-token-sharing OAuth; API-key and token branches return before it. Runtime-reader capture calls the existing credential capture method, not its SQL read method. Capture, observation and retained getters change only credential cells/maps and register a database-lifecycle resource; they publish no write receipt, session event, actor-token change, row-cache invalidation or activity scheduling event. Thus the added actor hydration/auth request has no new operation or invalidation edge from this reader cutover. The trace does not identify the exact inherited token-invalidating event, and arbitrary timing perturbation remains unquantified. The extra work stays included in the reported counts.

Across the ten windows, background SQL / requests rose 226/75 → 396/132; causal totals were 1700/411 → 1707/414. Those components exactly reconcile the wall-window totals of 1926/486 → 2103/546. Host load was 42.1–53.1 for base and 112.2–150.0 for candidate on 32 CPUs. Latency is unmeasured.

Both runs later failed child-spawn scripting with the same dispatch_action / tool_call mismatch. Candidate additionally exceeded the 120-second process-exit deadline after logging shutdown completion. Observed workload totals (6032→6292 SQL, 1064→1144 requests, 842→847 MAIN) are incomplete diagnostics, not passing full-workload evidence. No extra harness pair is run. These measurements precede the final cold-scope fix and main integration; that fix does not change warmed final-assertion code.

Evidence

Final candidate: f75d70303829cd9790d37a288968de4b69c6df59, integrating main 2444aae8f8f9e593f4801127eab4b37d3703c4c6 and cold-scope fix a1687a0f43222. The three conflict resolutions retained the candidate's ratchet and test contents unchanged. The ordinary PR CI is fully green, including the required Actions gate and security checks. The exact-head dispatch supplies the required Knip scans that ordinary PR CI does not select. This supported workflow has no individual-job selector and also runs broader checks/tests; it is not a static-only dispatch.

The supplemental dispatch completed with 78 successful, 20 skipped and six failed jobs (five underlying failures and the aggregate). Its failed Actions gate is treated as required: direct GraphQL reports isRequired: true, despite the narrower gh pr checks --required display showing only the successful ordinary and security gates.

The raw-head static dispatch also exposed a recovery-fixture type error already fixed on main by 605065ce7461177e9b438c8d8917641a8e8380e0 (#170722). Its title fixture field was replaced with the supported label. Ordinary PR CI tested merge checkout 2bdaecd0f20ca50d19ce830358389dc58e5307fb against becaa38baaf9f2a650580a831ef8f04511f4c52b, which includes that fix, and its corresponding type job passed. The raw-head dispatch remains distinct evidence; it is not represented as an all-green run.

Executed-main attribution for the supplemental dispatch uses scheduled run 38359584345, head 0348a2526c561d8ccce61bfd23931024a6b8f13e:

Dispatch failure Matching main result
Knip full-tree unused-file scan Main job 115170478488 reports the same sole src/infra/sqlite-existing-database.bun.test-support.ts finding. Production unused-file and export scans pass.
Dark/light reader-position and keyboard jumps; reply-preview recovery Main UI8 job 115170476361 reproduces both 120-second reader-position timeouts and the 30-second reply-preview click timeout at line 186.
Deep earlier reply reveal Main UI2 job 115170476315 reproduces the 30-second screenshot timeout at line 177.

Main UI diagnostics show connected browsers and open pages with renderer stalls; these are inherited failures, not a claimed infrastructure fault or harmless flake. The main repair owners already cover the Knip and UI findings. Queued local Knip/UI probes were canceled before execution when this evidence arrived. The separate agent-recreation timeout is not included in this inherited classification. Supplemental job 115165594516 hit a 30-second client timeout at the first agents.delete call; it recorded no server-side cause. The same case passes in ordinary PR CI (25.248 seconds) and scheduled main job 115170479853 (26.455 seconds). The supplemental sibling Trash case also passes, but takes 38.064 seconds versus 13.932/15.113 seconds in the passing runs. Those timings do not establish a cause or a fix. A single focused local baseline attempt completed compilation but produced no testcase outcome before it was stopped after approximately 20 minutes; it is inconclusive, not inherited evidence. A second local run would require another complete native preparation, so it was not started. No assertion, timeout or retry was changed.

Landing disposition: retain this timeout as an investigated, unresolved failure under the explicitly requested relaxed landing policy, which stops for proven product regressions. It is not waived as inherited and no passing replay is claimed as a repair. The completed ordinary PR run executes the same case successfully on the merge source containing this head. All mandatory changed-code static, authority, custody and security checks pass; the remaining static/UI failures have exact main evidence above. The red supplemental aggregate is disclosed, not described as green.

After the second review, a real P1 was found in scoped legacy-main cold preparation: it requested shared ownership even though the captured scope deliberately contained only its agent owner. The fix follows inheritedAuthDir, retains that owner after scope disposal, and adds one regression covering cold parity, update and deletion without ambient fallback. No warmed effect-check code changed. No local pre-fix failure was executed under the compute-conservation policy. The new regression passed on final CI in 610 ms. SDK documentation now describes the shared/agent retained getter.

The native boundary regression uses isolated state, the actual released synchronous SDK save, actual createCodexResponsesOAuth.resolve, and actual fetchWithSsrFGuard. It prepares synthetic token-sharing credentials cold and compares them with a fresh worker read. Three synchronous assertions measure SQLite execution and both Worker/MessagePort sends. During awaited DNS preparation, a real SDK save revokes sharing; the final assertion must deny before native fetch. DNS and fetch are the only external I/O fixtures. Retained-reader tests cover absent/present local sources, insertion, deletion fallback, shared replacement, explicit scope, disposal and fresh-reader parity. OAuth tests preserve fingerprint, selected-profile and validated pending-refresh behavior, and cover missing authority and runtime-only removal.

Located final-head results:

Contract Actual CI result
Shared/agent native fetch boundary and OAuth adapter Job 115163605938: both guards pass (681/702 ms), all nine OAuth cases pass
Credential owner and retained readers Job 115163605988: all 53 owner-family and retained-reader cases pass; explicit scoped legacy-main regression passes in 610 ms
Async store reads Job 115163606066: all 14 cases pass, including cold canonical shared/agent reads and invalidation after writes
Synthetic writer bypasses Job 115163606200: 83/83 tests, 823 ms, including released SDK, AuthStorage and generic machine-state entries
Worker/custody and dialect ratchets Job 115163605520: global T1 454→454, compatibility T1 9→9; all three changed-file dialect categories 0→0
Architecture Job 115163605633: zero runtime import cycles, zero Madge cycles, Kysely guardrails pass
SDK compatibility Job 115165593730: report inspected; zero entrypoint additions/removals and zero direct export-signature changes. The 168 reachable-only records reduce to two internal additive fields (prepareAuthProfileCredentialRead and optional AuthProfileReadOwner.readCurrentCredential). Released synchronous writer signatures are unchanged. This report compares the same becaa38b → 2bdaecd0 merge source used by ordinary PR CI.

Earlier CI exposed dynamic-import selection, object-method/facade classification and optional-name typing defects in the ratchet; those were fixed before this final pass. An earlier same-session E2E had a generic reply failure whose inheritance was not established. Prior b8df CI subsequently passed the actual scenario (1/1 test, all four A/B pairs, 92.353 seconds test / 104.65 seconds Vitest); no causal repair is claimed. Final-head CI remains the merge evidence, and earlier heads are not substituted for it.

Both Codex autoreview rounds completed; round 2 reviewed 3411b0795f8d2. The scoped P1 and documentation issue are addressed; no third review is requested. Lower-priority ratchet syntax extensions remain the disclosed follow-ups above. Local validation is changed-file oxfmt/oxlint and git diff --check; there are no local broad suites or scans.

No schema, updater, Doctor, migration, plugin-loading or service-lifecycle behavior changes in this PR, so it does not trigger another published-driver update cell. The parent writer PR records that proof. The Phase E hold is absent at the final pre-merge check.

Exact diff 2444aae8f8f9e593f4801127eab4b37d3703c4c6..f75d70303829cd9790d37a288968de4b69c6df59: 15 files, +1612/−98 total. Runtime production: +121/−15; custody-ratchet tooling: +764/−42; combined production including the ratchet: +885/−57 (net +828). Tests: +688/−34; documentation: +38/−7; test routing: +1/−0.

@clawsweeper

clawsweeper Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T06:37:31.567586Z f75d703 New commits
ℹ️ 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts agents Agent runtime and tooling extensions: codex size: XL labels Oct 13, 2026

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ae70763cb4

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

profileType: credential.type,
credential: resolved.credential,
readCurrentCredential: personalStore?.readCurrentCredential,
readCurrentCredential: personalStore?.readCurrentCredential ?? readCurrentCredential,

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.

P2 Badge Document retained readers for shared and agent profiles

For a persisted chatgpt-token-sharing credential, this now exposes a live readCurrentCredential function for shared and per-agent profiles, but the public openclaw/plugin-sdk/agent-runtime documentation in docs/plugins/sdk-runtime/models.md:80-87 still explicitly says those profiles return null. Third-party consumers following that contract will not retain or invoke the new owner-held check at their final transport boundary, so update the SDK documentation alongside this behavior change.

AGENTS.md reference: AGENTS.md:L127-L127

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3411b0795f

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/store.ts Outdated
reads.env,
params.profileId,
);
} else if (reads.effectiveAgentDir && requestedPath !== (await reads.sharedPath())) {

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.

P1 Badge Handle scoped legacy-main credential ownership

When a Codex run is wrapped by withAuthProfileStoreAgentDir and the operator still uses the supported legacy-main auth-store location, the scope sets inheritedAuthDir to the selected agent and supplies no scopedSharedStore. Consequently withPreparedAuthProfileStoreReads does not capture a shared context, but this condition still calls reads.sharedPath(), which throws Auth profile read requested an uncaptured shared owner; persisted ChatGPT token-sharing therefore fails before every request even when requested() already found the local credential. Avoid consulting the uncaptured shared owner in this scoped legacy state, or use the scope's selected owner directly.

AGENTS.md reference: AGENTS.md:L80-L81

Useful? React with 👍 / 👎.

Base automatically changed from dbasync/authowner5-sdk to main October 13, 2026 05:56
@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: f75d70303829cd9790d37a288968de4b69c6df59
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/oauth.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/runtime-read.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/runtime-read.types.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/shared-store-scope.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/store-runtime.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/store.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

# Conflicts:
#	scripts/lib/personal-credential-writer-guard.mts
#	src/agents/auth-profiles/credential-authority.test.ts
#	test/scripts/personal-credential-writer-guard.test.ts
@steipete
steipete merged commit d1553a7 into main Oct 13, 2026
256 of 262 checks passed
@steipete
steipete deleted the dbasync/authowner5-guard branch October 13, 2026 07:27
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…aw#170656)

Use the existing credential authority for the final shared and agent Codex bearer check. Retain cold worker preparation, selected-profile and fingerprint validation, strict deny-before-commit publication, and unknown-outcome denial. Remove the native final SQL read while preserving released synchronous SDK readers.

Extend the credential writer custody ratchet and cover native fetch revocation, cold parity, scoped legacy ownership, and synthetic bypasses. The warmed final assertion executes zero SQL and zero worker requests; static SDK T1 debt remains documented.
steipete added a commit that referenced this pull request Oct 14, 2026
…pins (#172374)

Reuse writer-published credential authority for personal OAuth acceptance and remove duplicate account reads, repeated validation, and the personal-accept worker transaction. Prepare provider metadata asynchronously at six native session model-selection callers. Keep live credential checks at physical I/O and retain released synchronous SDK compatibility.

Regression coverage verifies fresh credentials and model pins after in-process writes. No schema, configuration, or public SDK changes.

Release-note context: personal-account authentication avoids redundant database work and session model selection avoids synchronous fallback reads. Follow-up to #171726, #170583, and #170656.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 15, 2026
…pins (openclaw#172374)

Reuse writer-published credential authority for personal OAuth acceptance and remove duplicate account reads, repeated validation, and the personal-accept worker transaction. Prepare provider metadata asynchronously at six native session model-selection callers. Keep live credential checks at physical I/O and retain released synchronous SDK compatibility.

Regression coverage verifies fresh credentials and model pins after in-process writes. No schema, configuration, or public SDK changes.

Release-note context: personal-account authentication avoids redundant database work and session model selection avoids synchronous fallback reads. Follow-up to openclaw#171726, openclaw#170583, and openclaw#170656.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: codex plugin: file-transfer scripts Repository scripts security-sensitive-changed size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant