Skip to content

fix(auth)!: check client credentials, validate the body, verify real TOTP codes - #223

Open
gjtorikian wants to merge 7 commits into
mainfrom
fix/authenticate-validation
Open

gjtorikian wants to merge 7 commits into
mainfrom
fix/authenticate-validation

Conversation

@gjtorikian

Copy link
Copy Markdown
Collaborator

Finding 4 of the 2026-12-04 parity scan: POST /user_management/authenticate minted a session for any client, answered a missing field with a shape production does not use, and refused a real TOTP code. Three commits, one per part.

1. Client credentials (fix(auth): check client credentials before any grant runs)

Production runs four guards before the body is validated or a grant reads it: UserlandClientIdGuard, UserlandPkceGuard, UserlandClientSecretGuard, UserlandAuthenticateGuard (packages/api/src/userland-sessions/guards/*.guard.ts). The emulator now runs the same checks, in the same order:

Request Before Now, as production
No client_id 200 400 {"error":"invalid_request","error_description":"Missing required parameter: client_id."}
client_id not in the client_ form 200 400 invalid_client "Invalid client id."
No client_secret, empty, unknown, expired, or an API key in the Authorization header instead 200 400 invalid_client "Invalid client secret."
refresh_token or device_code grant without a secret 200 200 (credentials of their own)
authorization_code with a verified PKCE verifier and no secret 200 200
Wrong or missing code_verifier for a code bound to a challenge; a verifier for a code without one, unknown codes included invalid_request "code_verifier is required." or a spent code 400 invalid_grant "Invalid code verifier.", before the grant runs; the code is not spent and no event is recorded

The emulator has one environment, so any id in the client_ form names it. A client_secret is any API key the emulator accepts for Authorization: Bearer, unexpired. Hosted AuthKit's /x/authkit/users/authenticate alias keeps authenticating with the API key alone, as its session bearer does in production.

2. Body validation (fix(auth): answer 422 for a missing or malformed authenticate field)

Production validates the body with the class-validator rules in packages/api/src/userland-sessions/dto/userland-session-token.dto.ts through ValidationWithErrorCodePipe, and answers 422 invalid_request_parameters with one errors[] entry per failing field, in DTO order. The Node SDK raises UnprocessableEntityException; the emulator's 400 invalid_request made it raise OauthException.

Request Before Now, as production
No or empty grant_type 400 invalid_request 422 grant_type_string_required "Grant Type must be a non-empty string."
Required field missing or empty (code, email, password, pending_authentication_token, authentication_challenge_id, organization_id, device_code, …) 400 invalid_request with one sentence 422 with <field>_string_required " must be a non-empty string." for each, in DTO order
Wrong type (password: 5) 200 422 " must be a string."
Optional field sent empty (invitation_token: "", ip_address: "") 200 422
Malformed or padded email on the password grant 400 invalid_request or 200 422 email_required "Email must be a valid email address."
Magic Auth without email 400 invalid_request 422 email_required (its DTO lists IsEmail first); no check once user_id names the user, which the grant now also accepts
refresh_token missing "refresh_token is required." 400 invalid_request "Missing refresh token." (optional to the DTO; the grant's own refusal)

The base body (grant_type, the optional context fields) is validated before the grant's fields, so its failures come back alone. An unimplemented grant (email completion, Radar) still validates its DTO first.

3. TOTP (fix(mfa): verify a TOTP code computed from the enrolled secret)

Production verifies a challenge with the code otplib computes from the factor's secret (packages/api-services/src/authentication-challenges/totp-authenticator.ts: HMAC-SHA1, six digits, 30-second steps, window: 1). The emulator accepted only the random code it stored on the challenge, so a client using otplib, speakeasy or an authenticator app never completed enrollment, the factor was never listed, and a password login never stepped up.

POST /auth/challenges/{id}/verify, the mfa-totp grant and the hosted login page now verify a code computed from the enrolled secret, with node:crypto and no new dependency (totpCode, totpCodeMatches, verifyChallengeCode in helpers.ts; the RFC 6238 test vectors pin the implementation). The stored code still verifies, as the convenience for a test that reads it off the store. Production also blocks a code reused across challenges inside its window; the emulator does not, and the doc says so.

Verified against the live sandbox

harness/out/prauth-validation/report.md in the scan's scratchpad: 27 request pairs (every row above plus the success paths) answer the same status and body as api.workos.com after normalization. The one remaining difference is by design: a well-formed client_id that is not the environment's application is invalid_client live and accepted here, since the emulator registers no AuthKit clients.

Migration

A caller that sent POST /user_management/authenticate without client_id and client_secret now gets 400 invalid_client, which is what production would have answered. Send client_id (any client_… value) and client_secret (the emulator's API key, sk_test_default by default) as the SDKs do. The refresh_token and device_code grants need only client_id. Tests that asserted the old 400 invalid_request for a missing field now get the 422 shape. Tests that read the MFA code off the store keep working.

Tests and docs

  • bun test (2137 pass), bun run typecheck, bun run lint, bun run fmt:check.
  • New: src/workos/totp.spec.ts; client credentials and body validation blocks in auth.spec.ts. Existing authenticate calls in 20 spec files now send client credentials.
  • docs/behavior.md: new ### Client credentials section; the failure-shapes table and its prose; ## Multi-Factor Auth. docs/testing.md: the authenticate examples send credentials.

Not in this PR: the mfa_challenge 403 body shape (production returns user and authentication_factors, no challenge), sso_required and the other step-up codes, email_verification/send returning {user}, and the access token's aud claim — rows 5 to 8 of the scan's authentication findings.

Production guards POST /user_management/authenticate before it validates
the body: the client id, PKCE, the client secret, and then whether anything
credentialed the request. The emulator minted a session for any client_id
and client_secret, so a caller that omits or misspells them passes here and
fails there.

The emulator now answers as production does. A missing client_id is 400
invalid_request. A client_id not in the client_ form is 400 invalid_client.
A client_secret that is not an unexpired API key of the environment, or is
missing on a grant that needs one, is 400 invalid_client "Invalid client
secret.". A refresh_token or device_code grant needs no secret, and a
verified PKCE verifier stands in for one on authorization_code. A wrong or
missing verifier for a code bound to a challenge, or a verifier for a code
without one, is 400 invalid_grant "Invalid code verifier." before the grant
runs, so the code is not spent and no event is recorded.

Hosted AuthKit's /x/authkit/users/authenticate alias keeps authenticating
with the API key alone, as its session bearer does in production.

Source: packages/api/src/userland-sessions/guards/*.guard.ts in
workos/workos; live sandbox diffs from the parity scan.
Production validates the authenticate body with the class-validator rules
its DTOs declare before any grant runs, and answers 422
invalid_request_parameters with one errors[] entry per failing field, in
the DTO's order. The emulator answered 400 invalid_request with one
sentence, so the Node SDK raised OauthException here and
UnprocessableEntityException there.

The emulator now reports the same errors: grant_type_string_required for
an absent or empty grant_type, <field>_string_required for a required
field that is missing, empty, or not a string, and email_required for an
address production's IsEmail refuses, taken as sent. Magic Auth's DTO
lists IsEmail first and skips the address once user_id names the user,
which the grant now also accepts. The base body is validated before the
grant's fields. A missing refresh_token stays the grant's own 400, worded
"Missing refresh token." as production words it.

Source: packages/api/src/userland-sessions/dto/userland-session-token.dto.ts
and common/pipes/validation-with-error-code.pipe.ts in workos/workos;
live sandbox diffs from the parity scan.
Production verifies a challenge with the RFC 6238 code otplib computes
from the factor's secret (HMAC-SHA1, six digits, 30-second steps, one step
of drift either way). The emulator only accepted the random six-digit code
it stored on the challenge, so a client that computes the code with
otplib, speakeasy or an authenticator app never completed enrollment, the
factor was never listed, and a password login never stepped up.

The emulator now verifies a code computed from the enrolled secret on
POST /auth/challenges/{id}/verify, on the mfa-totp grant and on the hosted
login page, with node:crypto and no new dependency. The stored code still
verifies, as the convenience for a test that reads it off the store. The
one-time-code rules are unchanged: single use, three misses, expiry.

Source: packages/api-services/src/authentication-challenges/totp-authenticator.ts
in workos/workos; live diff in the parity scan (harness/out/auth-mfa-flow).
The Node compatibility suite signed in with the password grant and no
client_id or client_secret, which the guard chain now refuses with 400
invalid_client, as production does. The call now names its client and
proves it with the emulator's API key.
@gjtorikian gjtorikian changed the title fix(auth): check client credentials, validate the body, verify real TOTP codes fix(auth)!: check client credentials, validate the body, verify real TOTP codes Dec 4, 2026
@greptile-apps

greptile-apps Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5RetriggerView in Greptile

[High impact] The PR appears safe to merge; no new actionable issues remain.

Summary

The PR adds client credential checks, field-specific 422 responses, and real TOTP verification. The latest change fixes the earlier rejection of quoted email addresses.

  • Authenticate requests must name a client and prove they can use it.
  • Authenticate requests get field-specific errors when their body is incomplete or malformed.
  • TOTP challenges accept codes made from the enrolled secret.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Authenticate request] --> B[Check client ID]
  B --> C[Check PKCE]
  C --> D[Check client secret or other credential]
  D --> E[Validate body fields]
  E --> F[Run grant]
  F --> G[Return session or next sign-in step]
Loading

Reviews (3) · Last reviewed commit: "fix(auth): accept a quoted local part in..." · Reviewed by Greptile

Comment thread src/workos/routes/auth.ts Resolved
Comment thread src/workos/routes/auth.ts Resolved
Comment thread src/workos/totp.spec.ts Resolved
…'s rule

The alias skipped the whole guard block, and the grant no longer compared
the verifier itself, so a challenge-bound code redeemed there without its
verifier. PKCE is not a client credential: the alias keeps its exemption
from client_id and client_secret only.

The 422 email check used the storage bar (one @, no spaces), which let
alice@example through where production answers email_required. The check
now applies validator.js's isEmail rule, the one production's IsEmail
decorator (packages/api/src/common/validators/is-email.validator.ts)
applies; each refused and accepted case was confirmed against the live API.
A fixed guess such as 000000 is a real code for the factor's secret once
in a million steps, now that computed codes verify. wrongTotpCode picks a
six-digit code the secret does not produce in the window, nor one a test
stored on the challenge.
Comment thread src/workos/helpers.ts Resolved
validator.js's isEmail, the rule production applies, takes a quoted local
part ("john doe"@example.org) with backslash escapes inside; the check
refused one. Confirmed live: the quoted forms reach the credential check,
an unquoted embedded quote is 422 email_required.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant