Repository navigation
feat: add effect/oauth clients - #11247
danieljvdm wants to merge 19 commits into
Conversation
🦋 Changeset detectedLatest commit: c446b11 The changes in this PR will be included in the next version bump. This PR includes changesets to release 43 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
Thanks for splitting this out from #9884 and putting so much care into the protocol details. The overall architecture is in really good shape—lazy scoped discovery, a single serializable We run OAuth 2.1 / OIDC relying parties (including FAPI 2.0-style profiles with PAR, JARM, and 1. Bugs & Interoperability Traps to Fix in This PR1.1
|
Bundle Size AnalysisGenerated from PR build output; treat the content below as untrusted.
UI Bundle SizeVite 8.3.8/Rolldown, production, default Oxc minification, es2023, ES modules, gzip level 9 per chunk. effect 4.1.7, Node v26.12.1. Effect-only client: 27308 B gzip (Δ 0 B vs base).
|
|
Hey @danieljvdm. Thx for working on this ! Are there any plans to add client-side support for DPoP (RFC 9449)? |
… and Effect idioms
|
@eugene1g thanks for the comprehensive review! I will look into all your feedback shortly |
|
@Benjamin-htr will look into it! |
|
@eugene1g went through the full list. A few of these landed in a8988a2 ( Wanted to flag the few places where I'm planning to take a slightly different tack in case I'm missing an angle:
Let me know if any of those don't hold up for your setup! |
|
@danieljvdm Reviewed No blockers from my side - this is great for us. Happy to help with follow-up PRs (PAR/JARM, RFC 9068 resource server / Non-blocking notes for future evolutionNothing below needs to touch this PR, just a few lessons from running multi-tenant OIDC federation / an identity broker in production as Small RP follow-ups:
|
|
One more question for right after this lands: would you be interested in doing PAR (RFC 9126) + JARM ( Why PAR + JARM mattersWith what's already in #11247—
Combined with Proposed shape (building directly on #11247)Since #11247 already added the 1. PAR (RFC 9126)
2. JARM (
|
Replace Discovery, Grant, Pkce and the stateless operations with two services. OAuth.Client covers authorization with PKCE, callbacks, token requests and revocation, with lazy cached discovery. Oidc.Client adds ID token verification and UserInfo, keeping effect/jose out of plain OAuth bundles. Tests are reduced to the protocol contracts.
… harden ID token checks - Transactions record the issuer and client ID; callback rejects others. - Issuer and endpoints must be HTTPS (or loopback HTTP), checked for static and discovered metadata. - Add HttpClient.FollowRedirectsEnabled; token and revocation requests turn off followRedirects. - Reject untrusted ID token audiences, multi-audience tokens without azp, and future iat/auth_time. - Malformed callback URLs fail with CallbackRejected.
Fetch sends redirect: "manual" after merging RequestInit, so Bun and Deno layer options cannot override it. Undici sets maxRedirections: 0 to turn off redirect interceptors. XMLHttpRequest and React Native cannot turn redirects off, so they fail before sending. OAuth now only sets the reference.
|
I ran the OpenID Foundation Basic RP suite v5.3.5 against
That’s good evidence for the standard code flow. I also found four cases the suite doesn’t cover.
|
Oidc.make now hands its transformed HttpClient to OAuth.make, so transformClient runs once. Both layerConfig functions share one config reader and the public OAuth.ConfigOptions type. Issuer matching, success-only caching and UTF-8 encoding live in internal helpers, and the Redacted unwrap reuses the http internal one.
- FetchHttpClient fails before sending through an XMLHttpRequest-based fetch polyfill (React Native's built-in fetch) when redirects are off. - Oidc callback and refresh require ID tokens issued to the client ID. - Client assertions use the caller's clock. - authorize rejects reserved parameters and servers that require PAR. - Document which transports can send token requests.
…s are off A wrapper such as expo-router's can hide the whatwg-fetch polyfill flag, so on React Native the global fetch fails before sending unless FetchHttpClient.Fetch is provided. A missing fetch is a TransportError.
|
@Benjamin-htr just pushed client-side RFC 9449 DPoP support in 3b4d093! You can create a signer with
Let me know if you run into anything testing it against your server! |
|
@eugene1g awesome that you ran the OpenID Basic RP conformance suite against it, thank you! All four of those cases are now covered on the branch (d9af359 + 3b4d093):
Also +1 on PAR + JARM as a follow-up once this lands, happy to collaborate on that! |
jpowersdev
left a comment
There was a problem hiding this comment.
Left some notes inline. The first three look like real bugs to me, the rest are smaller things and a couple of questions.
| const { access_token, token_type, expires_in, refresh_token, id_token, scope, ...extra } = body | ||
| const expiresIn = typeof expires_in === "string" ? Number(expires_in) : expires_in | ||
| if ( | ||
| typeof access_token !== "string" || typeof token_type !== "string" || !optionalString(refresh_token) || |
There was a problem hiding this comment.
A token response with JSON null for an optional member is rejected as invalid. refresh_token, id_token and scope only accept undefined or a string, expires_in only a number or numeric string, and error: null is treated as an error response.
Some providers do send nulls, e.g. {"access_token":"a","token_type":"Bearer","refresh_token":null,"expires_in":null}. That fails with "The token response is invalid" after the authorization code has already been redeemed, so the user can't retry.
Treating null as absent for these members, and for the optional endpoints in invalidEndpoint, would cover it.
| callback: Effect.fnUntraced(function*(transaction, params, callbackOptions) { | ||
| const tokens = yield* oauth.callback(transaction, params, callbackOptions) | ||
| if (tokens.idToken === undefined) return yield* verificationFailed("The token response has no ID token") | ||
| const claims = yield* verify(tokens.idToken, { |
There was a problem hiding this comment.
callback passes transaction.nonce straight to verify, and verify only compares the nonce when one is given. Since Transaction.nonce is an optional key, a transaction without it skips the check silently.
That can happen with a transaction created by a plain OAuth.make client for the same issuer and client ID, or one whose nonce was lost in storage. The code is redeemed and an ID token with any nonce, or none, is accepted.
Maybe Oidc.callback could reject a transaction with no nonce (transactionMismatch?) before redeeming the code.
| const digest = Context.get(cryptoContext, Digest.Digest) | ||
| const random = Context.get(cryptoContext, SecureRandom.SecureRandom) | ||
|
|
||
| const exported = yield* Jwk.exportPrivate(privateKey).pipe( |
There was a problem hiding this comment.
make gets the public JWK by calling Jwk.exportPrivate on the private key, so it can't work with a non-extractable key. That's the usual way to hold a DPoP key in a browser (a CryptoKey kept in IndexedDB), and it fails here with "Could not export DPoP public key parameters".
Could make accept the public key or JWK as an option, and only fall back to exporting the private key when it isn't given?
| const callbackParams = (input: CallbackInput): ReadonlyArray<readonly [string, string]> | undefined => { | ||
| if (typeof input === "string") { | ||
| try { | ||
| input = new URL(input, "http://localhost") |
There was a problem hiding this comment.
Nit: every string is resolved with new URL(input, "http://localhost"), so a raw query string or form_post body like code=abc&state=xyz becomes a path with no search params. The caller gets stateMismatch even though the state matches, and the invalidUrl branch looks unreachable.
Either parse a string with no ? that isn't a URL as URL-encoded parameters, or document that strings must be URLs and reject the rest with invalidUrl.
| Effect.flatMap(oauth.server, (server) => | ||
| server.jwks_uri === undefined | ||
| ? requestFailed("discovery", "The authorization server has no jwks_uri") | ||
| : Jwks.makeRemote({ url: server.jwks_uri }).pipe( |
There was a problem hiding this comment.
Nit: the plain httpClient is passed to Jwks.makeRemote, without FollowRedirectsEnabled set to false as the token requests have. With FetchHttpClient.layer, a 302 from jwks_uri is followed to the other host before makeRemote rejects the response by URL.
Should the key set fetch run with redirects disabled too? If following is intended here, a short comment saying why would help.
| const request = signer === undefined | ||
| ? HttpClientRequest.bearerToken(baseRequest, accessToken) | ||
| : yield* signer.authorize(baseRequest, accessToken, { nonce }) | ||
| const response = yield* httpClient.execute(request).pipe(Effect.mapError(httpFailure("userinfo"))) |
There was a problem hiding this comment.
Nit: userInfo calls httpClient.execute(request) without the redirect-disabling wrapper that post uses, so this request still follows redirects while carrying the access token. A 307 gets the request re-sent: same-origin with the Authorization header, cross-origin still with the DPoP proof.
Is that intended? If not, disabling redirects as the token endpoint does would match.
| const credentials = yield* clientAuth({ clientId, issuer: metadata.issuer, endpoint: url }).pipe( | ||
| // The caller's clock applies even when it is the default, which has no | ||
| // entry to override the captured one. | ||
| Effect.updateContext((context: Context.Context<never>) => |
There was a problem hiding this comment.
Nit: authContext captures the whole context, including Tracer.ParentSpan. The caller's context wins on merge, but when the caller has no parent span the captured one is used. So if the layer is built inside a span and client.refresh later runs on a fiber with no parent, the ClientAuth.jwt signing spans attach to the long-finished layer-build span.
Dpop.make already omits ParentSpan for this reason; the same here would fix it.
| }).pipe( | ||
| Effect.provideService(Jwks.Jwks, jwks), | ||
| Effect.provideService(Signature.Signature, signature), | ||
| Effect.catch((cause) => verificationFailed("The ID token is invalid", cause)) |
There was a problem hiding this comment.
Nit: verify maps every failure of Jwt.verifyWithKeySet to VerificationFailed "The ID token is invalid", including the key set fetch failing. A 503 from jwks_uri during callback then looks like a forged or bad token rather than a transient outage worth retrying.
Could key-set-unavailable failures map to RequestFailed, as the jwks_uri setup failure already does, with VerificationFailed kept for problems with the token itself?
|
Thanks for fixing the four cases from my earlier comment. Two things stood out in the refactor:
I also agree with four points @jpowersdev raised inline. I’d prioritize the first two:
|
|
Thanks for the fixes. Two small follow-ups on the latest commit:
|
Add unstable
effect/oauthmodules for OAuth 2.1 and OpenID Connect clients, built oneffect/http,effect/crypto, andeffect/jose.OAuth.Clientis a service for one authorization server and client registration. It hasauthorize(PKCES256and a freshstate),callback(checksstate, RFC 9207iss, and duplicate parameters, then redeems the code),exchangeCode,refresh,clientCredentials,tokenRequestfor extension grants, and RFC 7009revoke.Oidc.Clienthas the same methods. Itsauthorizeaddsopenid, anonce, and an optionalmax_age, and itscallbackalways verifies the ID token. It also hasverifyIdToken, which takes options instead of a transaction so tokens from refresh or mobile SDKs can be verified, anduserInfo.Oidc.layerprovides the client asOAuth.Clienttoo.ClientAuthhasnone,secretBasic,secretPost, andjwt(private_key_jwtorclient_secret_jwt). A custom method is a plain function.Dpopsigns RFC 9449 proof-of-possession headers (make,generate):OAuth.ClientandOidc.Clientbinddpop_jkt, attachdpop+jwtproofs, cacheDPoP-Nonceheaders, and retry a freshuse_dpop_noncechallenge once;signer.authorizesignsHttpClientRequestcalls to resource servers.OAuthErrorwith a closedreasonunion.Notable decisions
serverto skip it, or callOAuth.discoverto fetch and adjust metadata yourself. A failed discovery is retried on the next call.HttpClient, so timeouts and retries are configured there. Token and revocation requests never follow redirects. They set the newHttpClient.FollowRedirectsEnabledreference tofalse, whichHttpClient.followRedirectsand every built-in transport respect: fetch (including Bun and Deno layer options) sendsredirect: "manual", undici turns off redirect interceptors, and XMLHttpRequest, React Native, and XMLHttpRequest-based fetch polyfills such as React Native's built-in fetch cannot turn redirects off, so they fail before sending. On React Native, fetch fails unless an implementation that supports manual redirects, such asexpo/fetch, is provided asFetchHttpClient.Fetch, since the global may wrap React Native's built-in fetch.dpopJktwhen DPoP is used), andcallbackrejects it on any other client or key.make, or use aLayerMap. Two layers that provideOAuth.Clientwould replace each other.effect/joseis only loaded byOidc,ClientAuth.jwt, andDpop. Measured withpackages/tools/bundle(gzipped), compared with the previous revision of this PR:OAuth.layer, discovery,secretBasic)Oidc.layer, discovery, ID token verification)Replaces #9884.
Closes EFF-5007