Skip to content

Auth foundations, including GetClaims and GetUser - #78

Merged
QuintinWillison merged 21 commits into
mainfrom
auth-foundations
Sep 14, 2026
Merged

QuintinWillison merged 21 commits into
mainfrom
auth-foundations

Conversation

@QuintinWillison

@QuintinWillison QuintinWillison commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Introduces a new auth module, to sit alongside postgrest as a logical sibling.

It verifies JWTs locally against the project's JWK Set with cached keys and rotation refetch, falling back to server verification through GetUser for projects still on legacy symmetric signing.

Quite a lot of related flux sits within this PR, all with the aim of improving the codebase as a whole, reducing repetition and increasing human/agent maintainability.

Closes Linear issue SDK-1189.

The new auth module verifies JWTs locally against the project's JWK Set (ES256, RS256 and EdDSA) with cached keys and rotation refetch, falling back to server verification through GetUser for projects still on legacy symmetric signing.

Enabling DRY tests for the new module, each integrationtest directory is now its own non-published module and the fixtures they share (stack credentials, end-user signup) live once in the new integrationsupport module, with the module boundary replacing the integration build tag.

Co-Authored-By: Claude <noreply@anthropic.com>
@QuintinWillison QuintinWillison self-assigned this Sep 9, 2026
@QuintinWillison QuintinWillison added enhancement auth Relates to the auth module. labels Sep 9, 2026
@QuintinWillison
QuintinWillison changed the base branch from main to core-refine September 9, 2026 19:36
QuintinWillison and others added 9 commits September 10, 2026 09:20
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
…achinery behind internal packages.

Claims, User and Identity documented immutability that any file in the auth package could legally violate. They now wrap opaque values from internal/token and internal/profile, the signing-key model and JWK Set retention move behind internal/key and internal/cache with fetching injected as a closure, and the tests go black-box with shared fixtures in internal/testkit. No public API change.

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
Base automatically changed from core-refine to main September 10, 2026 19:25
QuintinWillison and others added 5 commits September 11, 2026 13:36
It was causing gopls failures when a file was renamed locally but remained unstaged.
Confusing and unworkable!

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
…its claims from auth.Client.GetClaims.

Every sibling SDK returns the claims, header and signature triple from its get-claims capability, and the header has real operational uses, such as confirming during a signing-key rotation that freshly minted tokens carry the new key id. The envelope deliberately does not hang off Claims - transport metadata and identity assertions are separate concerns - so GetClaims now returns four values: the claims, an opaque JWTHeader carrying alg, kid and the newly decoded typ, a defensively copied signature and the error. Both verification routes return the envelope, the server fallback included, matching supabase-js behaviour.

This reshapes GetClaims ahead of any release, and sdk-compliance.yaml registers the new auth.JWTHeader symbols under auth.session.get_claims.

Co-Authored-By: Claude <noreply@anthropic.com>
@linear-code

linear-code Bot commented Sep 11, 2026

Copy link
Copy Markdown
SDK-1189 Block A.3.1 - JWT validation and client-from-existing-token

Part of RFC: Official Supabase Go SDK - Phased Implementation. This issue carries the full specification for its block from the RFC, so it can be worked without cross-referencing. The surrounding strategy - fixed constraints, module and repository structure, versioning policy and the release lifecycle - lives in the project overview.

A.3 - Server-side Auth and the composed root client. This completes the Alpha use-case (the validated RLS backend) and composes Auth into the root client first created back in the A.1 walking skeleton.

Goal

Validate end-user JWTs (via signing keys/JWKS) and construct an auth context from an externally-minted JWT, composing with the A.2 token option for validated RLS-scoped calls.

Capability IDs

auth.session.{get_user,get_claims}.

Rationale

The canonical Go backend middleware pattern and a directly-requested feature, anticipated demand item number two. It is the difference between trusting a forwarded token and verifying it, and it is the other half of the Alpha use-case.

Dependencies

Depends on Block A.2.3 - Per-request user-token option (RLS). Expressed as a native blocked-by relation on this issue.

Working state reached

A backend verifies a token, rejects bad ones and issues RLS-scoped database calls on behalf of the verified user.

Readiness signal

An integration test validates a fixture token, rejects a tampered one and performs an RLS-scoped query.

Cross-cutting bar

From the RFC's cross-cutting tracks, these hold for every block before it counts as done:

  • Meets the full standard and anti-pattern checklist from Go SDK Development: What Good Looks Like.
  • doc.go and runnable Example functions land with the block, not after.
  • sdk-compliance.yaml is updated as each feature lands, gated by matrix CI.
  • govulncheck stays green in CI and dependencies stay permissively licensed and minimal.

Risks

  • This block carries the SDK's first real security logic and the classic JWT failure modes apply: alg confusion (accepting none or an unexpected symmetric algorithm), missing audience/issuer checks and over-generous clock-skew tolerance. The allowed algorithm set should be pinned per project configuration rather than trusted from the token header.
  • Supabase projects exist in two signing worlds: the legacy shared HS256 JWT secret and the newer asymmetric signing keys with JWKS. Deciding which modes this block supports (and how a caller configures each) determines which real projects can adopt the Alpha, so the decision needs making explicitly rather than falling out of the implementation.
  • JWKS fetching introduces caching and rotation problems: a stale cache rejects tokens signed by a freshly-rotated key and an over-eager cache turns every request into a network call. Cache TTL, refresh-on-unknown-kid behaviour and failure semantics need a documented contract and tests.
  • Dependency selection is constrained: the standard demands minimal, permissively-licensed dependencies and no third-party types in the public surface, and JWT/JWKS libraries vary widely in quality. Whichever library (or standard-library-only approach) is chosen must stay behind the internal boundary.
  • get_user (a round-trip to the Auth server) and get_claims (local validation) imply different trust models and latency. The API should make the distinction impossible to confuse, because a caller who thinks a local parse was a server check has a security misunderstanding.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a strong first PR: auth's signature verification is bound to the JWK's own algorithm rather than to what the token header claims (key.Key.Verify in auth/internal/key/key.go), which closes the classic JWT "algorithm confusion" hole — and it's directly tested (TestVerifyAlgorithmBoundToKey). The 10-minute JWK cache TTL (auth/internal/cache/cache.go) exactly matches supabase/auth's Cache-Control: public, max-age=600 on /.well-known/jwks.json (verified against internal/api/jwks.go in that repo). Encapsulation via internal/ sub-packages with one-field wrapper types is clean and well documented, and test coverage of the security-sensitive paths (algorithm confusion, tampered signature, tampered signing input, key rotation, single-flight on a cold cache) is thorough.

Two inline findings below (JWKS-refetch amplification, unbounded response reads) are worth addressing before merge but aren't blockers. A couple of smaller things worth a look too:

  • GetClaims checks only exp, not aud or iss. Verification is scoped to the project's own published keys, so this isn't an auth bypass today, but the linked Linear issue's own risk list calls out audience handling — validating aud == "authenticated" (or documenting why that's intentionally left to the caller) would be good defense-in-depth against a token minted for a different purpose but signed with the same key.
  • configuration.Configuration.Retry() / WithRetry exists on the shared configuration, but nothing in auth reads it yet, so the retry option is currently a no-op for this module, and neither the JWKS fetch nor GetUser sets its own timeout — a caller on http.DefaultClient with no context deadline can hang indefinitely on a stalled connection. Worth confirming this is intentionally deferred to a follow-up rather than an oversight, since it's one of the things this review was asked to check.

Nice work getting an auth module this careful for a first PR in a new language.


Generated by Claude Code

Comment thread auth/internal/cache/cache.go Resolved
Comment thread auth/client.go Resolved
QuintinWillison added a commit to supabase/sdk that referenced this pull request Sep 14, 2026
…and `get_user` (#177)

Coming out of work I'm doing on the Go SDK (currently internal, will be
public later): supabase/supabase-go#78

I realised that there was a fair bit of complexity here, certainly in
terms of order of operations, without a single place I could look (or
could have looked) in to have it explained end to end. So this PR aims
to address that.

---

🤖 Claude's Analysis, which led me to raise this PR...

**What stood in for a spec**: the research plan grounded behaviour in
four independent source families and cross-checked them against each
other:

- All four sibling SDKs at pinned SHAs, with supabase-js treated as
canonical per its role as the prototype SDK. The check order (decode,
expiry, route, verify), the fallback condition, the 10-minute cache TTL
and the refetch-on-unknown-kid behaviour all agree across js, Swift and
Flutter.
- The serving side itself - `supabase/auth` source for the JWK Set
handler, key configuration and token issuance - so our verifier matches
what the server actually signs and publishes rather than what any client
assumes.
- The standards the wire format obeys (RFC 7517 for JWK Sets, RFC 7519
for claims, the IANA JOSE registry for algorithm names).
- A live Supabase stack in `auth/integrationtest`, including tamper
tests, proving the implementation and the real server agree.

Where the siblings were *not* consistent, the divergence was surfaced
and resolved deliberately rather than papered over: Swift binds the
verification algorithm from the matched JWK where js and Python dispatch
from the attacker-controlled token header (we chose Swift's stance,
which defeats algorithm confusion by construction), and Python's
exact-string `HS256` fallback check has a robustness gap an HS512 token
would fall through (we route on the supported-set instead).

**My take**: it was neither "obvious enough" nor "all consistent" - it
was consistent in the large, divergent in the security-relevant details,
and the research earned its keep precisely there. That said, a spec
*should* exist for `get_claims`: it is the most security-sensitive
capability in the session group and the one where sibling behaviour
genuinely differs. The matrix has a home for exactly this prose.

---------

Co-authored-by: Claude <noreply@anthropic.com>
QuintinWillison and others added 3 commits September 14, 2026 15:40
…ted key ids cannot force one discovery fetch per bogus token.
Co-Authored-By: Claude <noreply@anthropic.com>
@QuintinWillison

Copy link
Copy Markdown
Member Author

Regarding the Claude review's "smaller things"...

GetClaims checks only exp, not aud or iss. Verification is scoped to the project's own published keys, so this isn't an auth bypass today, but the linked Linear issue's own risk list calls out audience handling — validating aud == "authenticated" (or documenting why that's intentionally left to the caller) would be good defense-in-depth against a token minted for a different purpose but signed with the same key.

Deliberate, now documented on GetClaims (dd3425a). No sibling checks aud or iss (supabase-js validates exp only), the audience is deployment-configurable and third-party auth varies both, so a hardcoded check would reject tokens every other SDK accepts. Claim-value policy belongs to the caller via the Claims accessors.

configuration.Configuration.Retry() / WithRetry exists on the shared configuration, but nothing in auth reads it yet, so the retry option is currently a no-op for this module, and neither the JWKS fetch nor GetUser sets its own timeout — a caller on http.DefaultClient with no context deadline can hang indefinitely on a stalled connection. Worth confirming this is intentionally deferred to a follow-up rather than an oversight, since it's one of the things this review was asked to check.

Half intentional, half fair cop, both now documented on the module (16cc951).

intentional: Timeouts follow the standard Go split: context deadlines end to end, transport timeouts on the caller's http.Client via configuration.WithHTTPClient - an SDK-imposed default would fight caller deadlines.

fair cop: Retry: correct, auth is single-shot today. WithRetry already delegates the per-module contract, and retrying verification would amplify the same traffic the refetch backoff reduces. Whether auth eventually honours the option or it gets scoped to the database module is a follow-up.

@QuintinWillison
QuintinWillison merged commit 5921edf into main Sep 14, 2026
11 checks passed
@QuintinWillison
QuintinWillison deleted the auth-foundations branch September 14, 2026 15:13
QuintinWillison added a commit to supabase/sdk that referenced this pull request Sep 14, 2026
… Set refetches in the `get_claims` spec (#178)

## 🤖 Claude's Summary

Step 4 of the get_claims spec mandates a JWK Set refetch on any unknown
`kid` with no rate limit, so a storm of attacker-minted key ids can
drive one discovery fetch per bogus token against the project's JWKS
endpoint. Every SDK implementing the step as written inherits that
amplification, and supabase-js currently refetches unconditionally on
every miss.

The amendment recommends exponential backoff on forced refetches: while
consecutive forced fetches fail to resolve the `kid` that forced them,
the wait before the next one doubles (for example one second up to a
sixteen-second backstop), and a fetch that resolves its `kid` clears the
wait. Misses inside the wait resolve as unknown and take the existing
server-side verification fallback, so tokens signed by a freshly rotated
key keep verifying throughout.

Surfaced during review of the Go SDK's implementation in
supabase/supabase-go#78.

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auth Relates to the auth module.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants