Repository navigation
feat(chat-auth): P1 — Clerk-JWT verify + τ-metering (rebased onto C-a/C-b/C-c/#112ii), unblocks staging Clerk path - #44
Conversation
…at-path auth, zero-dep node:crypto)
Phase A of P1 (Clerk-JWT verify + tau-metering), spec chat-endpoint-contract.md v1 section 3. Net-new src/gateway/clerk-jwt.ts: verifyClerkJwt(token,{jwksUrl,issuer,audience,now?,fetchJwks?}) -> {sub,claims}|null. RS256 via node:crypto (createPublicKey jwk + RSA-SHA256), ZERO new deps (jose NOT used). alg-confusion guard first; fail-closed never-throws; explicit non-empty-segment + required-kid guards; exact-kid JWKS match; injected-fetcher-authoritative module cache w/ one-refresh-on-unknown-kid. QG: 4 parallel reviewers, no exploitable CRITICAL/HIGH, 2 hardening fixes applied. Coverage 16/16 (src/gateway/clerk-jwt.test.ts); sealed referee 22/22 (committed separately under test-author identity). tsgo clean, oxfmt+oxlint clean on production files. NOTE: committed under cto identity due to submodule-cwd identity resolution (should be openclaw).
Stage: impl
Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…verification onto the chat path (auth + user-scope) Generated-With: Claude Code Co-Authored-By: cto <[email protected]> Co-Authored-By: Claude <[email protected]>
…ternalId (Clerk sub) into agent ctx so HTTP callers share the user graph Closes the HTTP-memory-scope gap from P1.B: a Clerk/mobile chat turn now keys its graph group_id on the verified user identity, unifying it with the SAME person's other-channel graph (openclaw#834/openclaw#836) instead of forking. Mirrors the P3 senderE164 thread: new PluginHookAgentContext.externalId (string|null); threaded from RunEmbeddedPiAgentParams.externalId through the 3 hook-ctx sites (run.ts before_agent_start, attempt.ts before_agent_start + agent_end) and through AgentCommandOpts → agentCommand → runEmbeddedPiAgent; the two HTTP handlers pass externalId: handled.externalId (the verified sub, never client-set) ?? null. memory-graphiti: a new exported externalIdScopeKey(ctx) helper (identity.ts, reuses deriveScopeKey) is preferred at BOTH recall (before_agent_start) and capture (agent_end) group_id derivation when ctx.externalId is present — BEFORE the identity-DB query — so an HTTP Clerk user sub=X and WhatsApp lp_users.external_id=X resolve the SAME group_id=X. Behavior-preserving: channel callers carry no externalId → existing DB/derive path byte-identical (characterization 14 + index 55 unchanged). PHI tripwire untouched (still gates on senderE164; HTTP has none → fail-closed to Zep). 703 affected tests pass +6 (identity 5, openresponses e2e 1), tsgo 0, oxlint 0/0, sealed 60/60. Generated-With: Claude Code Co-Authored-By: cto <[email protected]> Co-Authored-By: Claude <[email protected]>
…ring on the chat path (per user_scope 429 + Retry-After) Wire a config-driven, default-OFF per-user_scope τ budget onto both chat surfaces (/v1/responses + /v1/chat/completions). The meter (tau-meter.ts) and the handler check/record seams already existed from the contract scaffold; this constructs the meter and threads it end-to-end so it actually throttles in prod. - types.gateway.ts: GatewayTauConfig (+ tau? on GatewayAuthConfig); io.ts: OPENCLAW_TAU_* env keys. - auth.ts: resolveTauConfig() -> ResolvedTauConfig on ResolvedGatewayAuth; present ONLY when explicitly enabled (config tau.enabled or OPENCLAW_TAU_ENABLED), else undefined -> unmetered no-op (behavior-preserving). parsePositiveIntEnv accepts decimal ints only. - server.impl.ts: construct TauMeter once next to authRateLimiter; thread as a param and dispose() on shutdown (mirrors the rate-limiter lifecycle). server-runtime-state.ts shares the one meter across all bind-host servers (process-global budget per user_scope). - server-http.ts: thread tauMeter into both chat handlers. - openai-http.ts: record() a turn on both non-stream + stream completion (was check-only -> the OpenAI-compat surface enforced a budget it never debited; QG metering-evasion fix). Contract section 9: 429 + Retry-After keyed on the server-derived user_scope (verified Clerk sub), shared across a user's consumers; unscoped requests never metered. PHI/tripwire posture untouched. QG: sealed-referee Phase C suite (16 unit + 28 config + 8 e2e incl /v1/chat/completions metering regression lock + tauTurnCost token-cost debit). 4-reviewer adversarial QG: 1 CRIT (openai record gap) + 1 MED (dispose lifecycle) + 2 LOW fixed; zero residual CRIT/HIGH. tsgo 0, oxfmt clean, gateway unit 532/532, e2e chat lane 18/18, sealed 60/60. Stage: impl Generated-With: Claude Code Co-Authored-By: cto <[email protected]> Co-Authored-By: Claude <[email protected]>
…arness (local Clerk-JWT'd gateway for /v1/responses SSE) scripts/dev/chat-auth-qa-preview.ts stands up the REAL gateway (startGatewayServer) with the P1 chat-auth surface wired on — Clerk-JWT verification + τ-metering — so QA can exercise the integrated mobile flow (Clerk-JWT'd POST /v1/responses -> SSE) without a deploy. Default local mode mints a throwaway RSA keypair, serves its public JWK from a local JWKS endpoint, points gateway.auth.clerk at it, and mints a valid Clerk-shaped JWT (mirrors the tau-meter.e2e.test.ts harness — same verifier/scope/401/429 behavior as prod). --real-clerk mode reads devex's OPENCLAW_CLERK_* from env (Infisical) and expects a real Clerk session JWT. Prints copy-paste curl for: streamed + non-streaming /v1/responses, auth fail-closed (no/bad token -> 401), τ 429 + Retry-After scope-keying, and the unscoped-never-metered legacy path. Verified live: 401 fail-closed, SSE event stream (response.created/in_progress/output_item.added), 429+Retry-After on budget exhaust, legacy-token never throttled. Dev-only harness; not shipped in the gateway runtime. Stage: impl Generated-With: Claude Code Co-Authored-By: cto <[email protected]> Co-Authored-By: Claude <[email protected]>
… — channels-free, contract-faithful /v1/responses streamed mock (shrinemobile local co-debug) scripts/dev/chat-mock-server.ts: standalone http server (NO gateway/channels/agent — safe alongside the live bot). Mints a local Clerk JWKS+JWT, verifies via the REAL verifyClerkJwt (401 fail-closed), streams a deterministic mock reply matching the real handler's §2.2 SSE sequence (response.created→ in_progress→output_item.added→content_part.added→output_text.delta×N→…→completed→[DONE], full-event- object data per the real writeSseEvent) + §2.3 stream:false envelope + 400/429(+Retry-After). Mock text echoes input + resolved scope/session/device so the client can see scope threading. Flags: --port --stream-delay-ms --budget --sub --legacy-token. DEV-stage tool only (test plan stage 1); not prod code. 7 tests (src/gateway/chat-mock-server.test.ts), tsgo 0, oxfmt clean. Verified: 401 + 200 stream:false + ordered SSE live. Generated-With: Claude Code Co-Authored-By: cto <[email protected]> Co-Authored-By: Claude <[email protected]>
…rebased # Conflicts: # src/config/io.ts # src/gateway/openresponses-http.ts
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (38)
Disabled knowledge base sources:
📝 WalkthroughWalkthroughThis PR adds RS256 Clerk JWT gateway authentication backed by a local JWKS verifier, a per- ChangesClerk JWT Auth + τ-Meter + externalId Pipeline
Sequence Diagram(s)sequenceDiagram
participant Client
participant authorizeGatewayConnect
participant verifyClerkJwt
participant tauMeter
participant handleOpenResponsesHttpRequest
participant agentCommand
participant memoryGraphiti as memory-graphiti hooks
Client->>authorizeGatewayConnect: Bearer JWS token
authorizeGatewayConnect->>verifyClerkJwt: token, ResolvedClerkAuth
verifyClerkJwt-->>authorizeGatewayConnect: {ok:true, externalId: sub}
authorizeGatewayConnect-->>handleOpenResponsesHttpRequest: GatewayAuthResult{externalId}
handleOpenResponsesHttpRequest->>tauMeter: check(userScope)
tauMeter-->>handleOpenResponsesHttpRequest: {allowed:true}
handleOpenResponsesHttpRequest->>agentCommand: {externalId}
agentCommand->>memoryGraphiti: before_agent_start{externalId}
memoryGraphiti->>memoryGraphiti: externalIdScopeKey(ctx) → groupId
agentCommand-->>handleOpenResponsesHttpRequest: response + usage
handleOpenResponsesHttpRequest->>tauMeter: record(userScope, tauTurnCost(usage))
handleOpenResponsesHttpRequest-->>Client: 200 response
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
The formal models extracted constants ( This check is informational (not blocking merges yet). If this change is intentional, follow up by updating the formal models repo or regenerating the extracted artifacts there. |
P1 chat-auth (Clerk-JWT verify + τ) reconciled onto current main f988c54 (supersedes the stale chat-auth-p1-clerk-jwt-tau off old main). #112ii timeout now wraps the P1 runResponsesAgentCommand (externalId) in both stream+non-stream; τ-record + C-b failure-terminal coexist. QG green: tsgo 0, gateway unit 546, e2e 184 (Clerk auth + τ 429 + C-b + #112ii + chat-service all coexist), sealed 60/60. WHY NOW: gating item for shrinemobile's STAGING Clerk-JWT live-reply QA (openclaw#1506) — on land, devex rebuilds staging w/ Clerk verify (currently Clerk JWTs 401, no verify code deployed). STAGING only — PROD rollout stays gated on the staging QA + principal go. @ f8e44d3. CTO lands.
Summary by CodeRabbit
New Features
Bug Fixes