Skip to content

fix(auth): keep OAuth refresh fence timeout monotonic across clock skew - #167619

Merged
fuller-stack-dev merged 2 commits into
openclaw:mainfrom
SunnyShu0925:fix/oauth-refresh-fence-deadline-wall-clock
Oct 16, 2026
Merged

fuller-stack-dev merged 2 commits into
openclaw:mainfrom
SunnyShu0925:fix/oauth-refresh-fence-deadline-wall-clock

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A wall-clock rollback can make callers observing an OAuth refresh wait beyond their timeout. The refresh observer calculated its deadline with Date.now(), although its timers measure elapsed time. Forward clock changes can also reject a healthy settlement too early.

Change

Measure the existing observation deadlines with performance.now(). Keep token expiration timestamps and credential validity checks on wall time. Refresh ownership, persistence, cancellation, timeout messages, and configured budgets remain unchanged.

Thanks @SunnyShu0925 for the report and fix; the contributor's commit is retained unchanged. The fix stays in the existing shared observer, with no new state or compatibility path. The original monotonic conversion is retained. Follow-up fixes round fractional observer timeouts and positive polling remainders upward so neither expires early nor busy-polls without yielding. Tests cover both wall-clock directions, exact boundaries, blocked reads, late settlement and cancellation.

Evidence

Validation for current head fe34335fe5c31fdabb5b0753244dcffa64cf0b5a (same source tree as locally tested 139811d3e675c87abf48156c9d47dbd2a201406f):

  • Independently reproduced premature fractional expiry through both public observer APIs: at 99 ms, monotonic time 99.75 was still below deadline 100.25, but the incoming floor-rounded timer had already rejected. Both regression fixtures failed before the correction.
  • Final focused asynchronous suite: 19 passed.
  • Qualified the final correction composed with main 5462f7f146436a50a56354dd39f8405eaeb5b60f, merged tree a0a623d39589a51a16b873a9ba7962f1542640ab: 65 passed across OAuth fence sync/async, abort-signal and backoff tests. Command: pnpm test src/agents/auth-profiles/oauth-refresh-fence.test.ts src/agents/auth-profiles/oauth-refresh-fence.async.test.ts src/infra/abort-signal.test.ts src/infra/backoff.test.ts --maxWorkers=1.
  • The prior composed candidate failed the fractional polling boundary; rounding positive polling remainders upward corrected it. Independent forward/backward wall-step polling cases also fail against the former Date-based implementation.
  • Whole changed-file and caller audit retains epoch-based token validity, refresh ownership/CAS, account barriers, durable persistence and cancellation. Local lint is not claimed: the local wrapper rejects the shared pnpm compiler realpath; required GitHub lint/type/test gates must pass before merge.
  • Fixtures use private synthetic auth state, never production credentials or stores. Original contributor runtime observations below are preserved and are not represented as this correction's own runtime proof.

Original contributor validation (historical head)

Built current main 56c315156f4542f197a2b7f727681ba3f41c21b5 and this head 588022c34c35772d025eb7c73c4c0a8b26e9dd5c in an isolated Node 24.16.0 Linux container. Synthetic pending refresh credentials were persisted in the real SQLite auth store. Only the process's Date.now() was stepped backward by 5,000 ms; the system clock was not changed. Elapsed durations were measured with performance.now().

The compiled observer reading the real persisted store, with a 200 ms budget:

Case Current main This head
Rollback, first run 5,213.5 ms 200.4 ms
Rollback, second run 5,240.2 ms 200.2 ms
No rollback 203.1 ms 201.9 ms

The shipped openclaw/plugin-sdk/provider-auth resolver, resolveProviderAuthProfileApiKey, also observed a pending refresh through the normal auth manager. This path keeps its production 120,000 ms budget. Total call durations include initialization:

Case Current main This head
Rollback, first run 127,019.9 ms 120,881.9 ms
Rollback, second run 126,755.4 ms 120,766.8 ms
No rollback 120,927.1 ms 120,893.2 ms

All calls ended with the existing OAuth refresh timeout error; the pending owner was intentionally never settled. Current main requires its published asynchronous runtime-config initialization before the resolver call.

A separate public-SDK control checked the same unchanged token-expiry timestamp before expiry, after expiry, and after a wall-clock rollback. Both builds returned [true, false, true], confirming that token validity still follows wall time.

Focused tests: pnpm test src/agents/auth-profiles/oauth-refresh-fence.test.ts src/agents/auth-profiles/oauth-refresh-fence.async.test.ts --maxWorkers=1 — 33 passed, 2 files; command elapsed 200.31 seconds. These also cover cancellation and durable success/failure settlement.

No real-provider gate is needed for this observation-deadline-only change. No live provider credentials were used. The runtime reproduction covers pending-generation observation; the existing focused tests cover the other settlement boundaries.

Merge risk

Two-way door: reverting fully restores the previous behavior; there is no schema, stored-token, configuration, or public API migration. The affected surface is OAuth callers waiting for a refresh or refresh settlement. An incorrect deadline could return a timeout too early or let those callers wait too long; it does not change token expiry or cancel the durable refresh owner.

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@github-actions

github-actions Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

✅ Maintainer security changes approved

A maintainer approved this revision with an explicit security approval comment.

A later push requires a fresh approval comment for an external contributor's PR.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Oct 9, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR measures OAuth refresh observation deadlines with a monotonic clock so system-clock changes cannot distort timeout budgets.

Example: A healthy OAuth refresh completes in 8 seconds while the wall clock jumps forward 119 seconds during a 120-second observation budget.

  • Before: The observer incorrectly reports a timeout.
  • After: The observer accepts the healthy refresh settlement.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused root-cause repair, meaningful fake-clock regression coverage, and supplied Gateway behavior evidence; no code findings or persisted-format changes.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Supplied terminal output exercises the changed observers through polling, the production SQLite reader, and a real Gateway/WebSocket agent run with a controlled refresh adapter; healthy settlement succeeds after injected forward skew, and polling remains bounded after rewind.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A system-clock adjustment can make OAuth refresh wait too long or report a timeout despite healthy completion.
Reason: Elapsed-time budgets should survive wall-clock corrections, and the patch repairs that invariant at the existing shared owner.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current OAuth timeout defect with a focused change and no actionable findings; exact-head security approval remains outstanding.

Priority: P2
Reviewed head: 588022c34c35772d025eb7c73c4c0a8b26e9dd5c

Before merge

None.

Findings

None.

Agent review details

How this fits together

The auth-profile lifecycle owns refresh claims and durable credential settlement; its observers consume pending-store snapshots or settlement promises and return credentials, cancellation, or timeout without canceling the refresh owner.

flowchart TD
  A[Credential request] --> B[OAuth refresh manager]
  B --> C[Durable refresh owner]
  C --> D[Credential store]
  B --> E[Monotonic deadline observer]
  D --> E
  C --> E
  E --> F[Credential result or timeout]
Loading

Technical review

Best possible solution:

Land the focused monotonic-clock repair through the existing security-review gate while preserving independent durable settlement.

Do we have a high-confidence way to reproduce the issue?

Current-main source exposes both clock-domain failures directly, and the contributor supplies matching before/after output; this read-only review executed no target code.

Is this the best way to solve the issue?

Changing the clock at the shared observation owner fixes both paths without adding policy, configuration, or a competing timeout owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8ab860a75c9e.

Provenance checked

  • Durable refresh observation keeps the original intent (b824b72: Provide bounded observation of shared durable refresh generations without canceling independently owned settlement.)
  • Absolute deadline across asynchronous reads keeps the original intent (04aac5b: Await durable storage operations while retaining one observation deadline and preserving original pre-deadline outcomes.)
  • Cancelable observation keeps the original intent (83835e2: Release canceled request waits while refresh settlement continues independently.)
  • Abortable fence polling keeps the original intent (bc0b247: Bound credential preparation and prevent canceled callers from continuing queued auth work.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Focused introduced change: The introduced hunks replace wall-clock deadline calculations and checks with performance.now(), floor timer delays, and adapt focused fake-clock coverage; credential claims and durable settlement are unchanged. (src/agents/auth-profiles/oauth-refresh-fence.ts:72, 588022c34c35)
  • Current main remains affected: Current main still seeds and checks both observation deadlines with Date.now(), allowing clock rewinds to extend polling and forward jumps to reject healthy settlement. (src/agents/auth-profiles/oauth-refresh-fence.ts:72, 8ab860a75c9e)
  • Supplied behavior evidence: The PR body provides before/after polling and settlement output, a real SQLite reader scenario, and a real Gateway/WebSocket agent run with a controlled refresh adapter and injected forward skew; it explicitly excludes real provider credentials and OS-level clock manipulation. (588022c34c35)
  • Original ownership contract preserved: fix(auth): fence shared OAuth refresh generations #141477 established durable generation fencing and settlement that continues after observer timeout; fix(auth): await durable OAuth refresh transitions #145196 retained an absolute observation deadline while awaiting asynchronous reads. (src/agents/auth-profiles/oauth-refresh-fence.ts:350, 04aac5be5f15)
  • Exact-head approval gate: The security-sensitive guard requests approval for the reviewed head, and both failing commit statuses explicitly report missing maintainer approval rather than a code or test failure; obviyus requested this re-review without posting approval. (588022c34c35)
  • Repository policy applied: Read root and agent-scoped guidance and audited the changed tests against the test-value policy; no maintainer-notes directory exists in this checkout, and the checkout remained clean. (src/agents/AGENTS.md:1, 588022c34c35)

Likely related people:

  • Ayaan Zaidi: Raw commit bc0b247 adds src/agents/auth-profiles/oauth-refresh-fence.ts:72 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: bc0b24713dc8; files: src/agents/auth-profiles/oauth-refresh-fence.ts)

PR surface

Source 0, Tests +32. Total +32 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 6 6 0
Tests 2 35 3 +32
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 41 9 +32

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Clock adjustments can cause spurious OAuth refresh failures or extended waits, with impact limited to refresh observations spanning those adjustments.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-09T08:56:43.533Z sha 1a981e5cab9767a2a9de027df059a517374ca997 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-09T09:19:10.746Z sha 3b0be2bf662b746b54584ffa9d5719974791c407 :: needs changes before merge. :: none
  • reviewed 2026-10-09T10:10:28.201Z sha 3710b5962a1364b26e70619089081a4212a3a9a8 :: needs changes before merge. :: none
  • reviewed 2026-10-09T10:26:33.516Z sha 3710b5962a1364b26e70619089081a4212a3a9a8 :: needs changes before merge. :: none
  • reviewed 2026-10-12T23:25:47.143Z sha 3710b5962a1364b26e70619089081a4212a3a9a8 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-14T02:18:35.102Z sha 23b5e49fea98e8f3afa090568e1cb930457a82e1 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-14T02:41:59.716Z sha 832c8a2fabd6b22b47f4929bdfd176c376f06696 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-14T03:28:09.190Z sha 588022c :: needs maintainer review before merge. :: none

Reviewed October 15, 2026, 10:15 PM ET / October 16, 2026, 02:15 UTC (Revision 12).

@SunnyShu0925
SunnyShu0925 force-pushed the fix/oauth-refresh-fence-deadline-wall-clock branch from d212c67 to 05fd23f Compare October 9, 2026 07:31
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 9, 2026
@SunnyShu0925
SunnyShu0925 force-pushed the fix/oauth-refresh-fence-deadline-wall-clock branch 2 times, most recently from 1a981e5 to 3b0be2b Compare October 9, 2026 09:04
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 9, 2026
@SunnyShu0925
SunnyShu0925 force-pushed the fix/oauth-refresh-fence-deadline-wall-clock branch from 3b0be2b to 3710b59 Compare October 9, 2026 09:55
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@obviyus @altaywtf — you both have merged the sibling monotonic-clock fixes (#155323, #155603, #156979) with the same Date.now() → performance.now() + Math.floor pattern. This PR applies the identical fix to the last remaining clock-domain mismatch in oauth-refresh-fence.ts.

  • ClawSweeper: 0 findings, patch quality 🐚 platinum, proof: sufficient
  • Net 0 production lines — only the clock source moved
  • Blocked on security-sensitive-changed approval for head 3710b596

Could one of you post /allow-security-sensitive-change when you have a moment? Happy to address any feedback.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 12, 2026
@SunnyShu0925
SunnyShu0925 force-pushed the fix/oauth-refresh-fence-deadline-wall-clock branch 3 times, most recently from 441aa69 to f5fe745 Compare October 14, 2026 02:27
@SunnyShu0925
SunnyShu0925 force-pushed the fix/oauth-refresh-fence-deadline-wall-clock branch from f5fe745 to 832c8a2 Compare October 14, 2026 02:34
observeOAuthRefreshSettlementBeforeDeadline seeded its deadline with
Date.now() and fed deadline - Date.now() to setTimeout. Wall-clock
adjustments (NTP, container drift, sleep resume) warped the remaining
budget: a rewind let the fence hang past the configured timeout and a
forward jump tripped the timeout on a healthy refresh.

Seed the deadline from performance.now() and read remaining budget from
the same monotonic clock, flooring the value before handing it to
setTimeout/sleepWithAbort. Mirrors the canonical wall-clock fix in openclaw#155323.

Ref: BUG-153-oauth-refresh-fence-deadline-wall-clock (local finding)
@SunnyShu0925
SunnyShu0925 force-pushed the fix/oauth-refresh-fence-deadline-wall-clock branch from 832c8a2 to 588022c Compare October 14, 2026 03:21
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 14, 2026
@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Oct 16, 2026
@fuller-stack-dev

Copy link
Copy Markdown
Member

/allow-security-sensitive-change

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Oct 16, 2026
@fuller-stack-dev
fuller-stack-dev enabled auto-merge (squash) October 16, 2026 03:00
@fuller-stack-dev
fuller-stack-dev merged commit 27b0180 into openclaw:main Oct 16, 2026
128 of 129 checks passed
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@fuller-stack-dev Thanks!
There's also a similar PR related to security. Would you mind taking a look at that one as well when you get a chance? 🙂
#171838

I also have a couple of other small wall-clock fix PRs under my name — all fairly minor changes. Feel free to check them out if you have some bandwidth. Thanks a lot~

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…ew (openclaw#167619)

* fix(auth): keep OAuth refresh fence timeout monotonic across clock skew

observeOAuthRefreshSettlementBeforeDeadline seeded its deadline with
Date.now() and fed deadline - Date.now() to setTimeout. Wall-clock
adjustments (NTP, container drift, sleep resume) warped the remaining
budget: a rewind let the fence hang past the configured timeout and a
forward jump tripped the timeout on a healthy refresh.

Seed the deadline from performance.now() and read remaining budget from
the same monotonic clock, flooring the value before handing it to
setTimeout/sleepWithAbort. Mirrors the canonical wall-clock fix in openclaw#155323.

Ref: BUG-153-oauth-refresh-fence-deadline-wall-clock (local finding)

* fix(auth): yield across fractional refresh polling remainders

---------

Co-authored-by: Jason (Json) <[email protected]>
hilsbos pushed a commit to hilsbos/openclaw that referenced this pull request Oct 22, 2026
…ew (openclaw#167619)

* fix(auth): keep OAuth refresh fence timeout monotonic across clock skew

observeOAuthRefreshSettlementBeforeDeadline seeded its deadline with
Date.now() and fed deadline - Date.now() to setTimeout. Wall-clock
adjustments (NTP, container drift, sleep resume) warped the remaining
budget: a rewind let the fence hang past the configured timeout and a
forward jump tripped the timeout on a healthy refresh.

Seed the deadline from performance.now() and read remaining budget from
the same monotonic clock, flooring the value before handing it to
setTimeout/sleepWithAbort. Mirrors the canonical wall-clock fix in openclaw#155323.

Ref: BUG-153-oauth-refresh-fence-deadline-wall-clock (local finding)

* fix(auth): yield across fractional refresh polling remainders

---------

Co-authored-by: Jason (Json) <[email protected]>
(cherry picked from commit 27b0180)
Co-authored-by: RomneyDa <[email protected]>
RomneyDa pushed a commit that referenced this pull request Oct 27, 2026
…ew (#167619)

* fix(auth): keep OAuth refresh fence timeout monotonic across clock skew

observeOAuthRefreshSettlementBeforeDeadline seeded its deadline with
Date.now() and fed deadline - Date.now() to setTimeout. Wall-clock
adjustments (NTP, container drift, sleep resume) warped the remaining
budget: a rewind let the fence hang past the configured timeout and a
forward jump tripped the timeout on a healthy refresh.

Seed the deadline from performance.now() and read remaining budget from
the same monotonic clock, flooring the value before handing it to
setTimeout/sleepWithAbort. Mirrors the canonical wall-clock fix in #155323.

Ref: BUG-153-oauth-refresh-fence-deadline-wall-clock (local finding)

* fix(auth): yield across fractional refresh polling remainders

---------

Co-authored-by: Jason (Json) <[email protected]>
(cherry picked from commit 27b0180)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. security-sensitive-changed size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants