Files
iam/internal/oidc/userinfo.go
zeekayandHanzo Dev 0b0b3941d4 A session-cookie write comes only from the issuer's own page, and a process with no issuer names none
The session cookie is SameSite=Lax, which keeps it off requests from other
sites but not from other hosts of the same site. Once hanzo.ai signs people
in, any page on any *.hanzo.ai host could post a form to /v1/iam/login with
type=device and approve an attacker's `hanzo login` code, or with type=code
mint an authorization code, or edit the account. sessions.Forgeable is now
the one rule for a write the cookie authorizes: Sec-Fetch-Site must be
same-origin or none, and a request with a body must carry it as JSON.
sessions.Writer resolves the session only past it, and every cookie write
goes through it: the login SSO and device branches, callerOf/callerFrom
(profile, password rotation, terms, consent, preferences, onboarding,
link, unlink, passkey enrollment), and invitation accept. A refused write
is 403 before the session is read. The passkey finish, which the challenge
cookie authorizes, asks the same rule. A bearer from a client that is not a
browser needs no fetch metadata, with or without a cookie riding along.

Signing out ends sessions, so sessions.Clear asks the rule too, with one
exception: a top-level navigation (Sec-Fetch-Mode navigate, Sec-Fetch-Dest
document), which is how a relying party signs a person out. An image, a
frame or a sibling's form ends nothing.

The federation binding cookie is __Host-hanzo_fed and only that name is
read; a test now pins that the bare hanzo_fed name is refused.

server.RequireIssuer is the boot check for issuers: it installs IAM_ISSUER
and IAM_ISSUER_MAP, then IAM_FEDERATION_ORIGIN_MAP, and returns an error for
an empty or non-https IAM_ISSUER (outside IAM_DEV_HOST_RELATIVE=1), a
malformed issuer map, or a sign-in map that would strand the binding. `iam
serve` calls it, and a host that embeds IAM must call it before NewApp.
devFallbackIssuer and the lazy env resolvers are gone: a process that never
installed an issuer has none, so every issuer read is an error, discovery
answers 503, no token is minted and none is accepted, where it used to
answer https://hanzo.id. No issuer value changes.

Co-authored-by: Hanzo Dev <[email protected]>
2026-10-17 19:45:43 -07:00

199 lines
8.0 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package oidc
import (
"github.com/hanzoai/orm"
"github.com/zap-proto/zip"
"github.com/hanzoai/iam/internal/httpx"
"github.com/hanzoai/iam/pkg/schema"
"github.com/hanzoai/iam/pkg/store"
)
// The userinfo endpoint: GET/POST /v1/iam/oauth/userinfo. A bearer must satisfy
// two independent checks — the grant still exists (the token row is looked up by
// the SHA-256 hash of the presented token, so a revoked or rotated grant is
// already dead) AND the JWT signature verifies under the issuing cert. It then
// returns exactly the OIDC claims the token's granted scopes authorize; the
// subject is taken from the signed `sub`, so the response can only ever describe
// the token's own principal (no cross-tenant read).
// userinfoHandler returns the profile claims for whoever the access token
// belongs to — the standard OpenID Connect way to find out who is calling you
// without your application storing anything itself.
//
// The token must still be live: revoke it and this stops answering.
func userinfoHandler(db orm.DB) zip.Handler {
return func(c *zip.Ctx) error {
bearer := httpx.Bearer(c)
if bearer == "" {
return userinfoUnauthorized(c, "a bearer access token is required")
}
ctx := c.Context()
row, err := store.GetTokenByAccessTokenHash(ctx, db, hashToken(bearer))
if err != nil {
return c.JSON(500, map[string]string{"error": "server_error"})
}
if row == nil {
return userinfoUnauthorized(c, "the access token is invalid or revoked")
}
claims, err := verifyBearer(ctx, db, bearer)
if err != nil {
return userinfoUnauthorized(c, "the access token is invalid")
}
if claims.Imp {
if _, err := Operator(ctx, db, claims); err != nil {
return userinfoUnauthorized(c, "the impersonation has ended")
}
}
// Resolve the token's principal from its `sub` (a stable UUID for a v2 token,
// or owner/name pre-cutover). The response `sub` is the signed claims.Subject
// itself, so userinfo reports the SAME subject the token carries.
user, err := store.GetUserBySubject(ctx, db, claims.Subject)
if err != nil {
return c.JSON(500, map[string]string{"error": "server_error"})
}
iss, err := tokenIssuer(c)
if err != nil {
return c.JSON(500, map[string]string{"error": "server_error"})
}
// The membership set is read from the store, not echoed from the token, for
// the reason isAdmin is: a grant revoked a minute ago must stop counting now
// rather than when the token lapses.
// Wallets are read from the store beside the memberships, and for the
// identical reason: a wallet unlinked a minute ago must stop counting
// now rather than when the token lapses.
return c.JSON(200, buildUserinfo(user, claims, row, iss,
store.MemberOrgRefs(ctx, db, user), store.WalletRefs(ctx, db, user)))
}
}
// buildUserinfo assembles the scope-gated claim set. The identifiers (sub, iss,
// aud, owner, organization) are always present; every profile/email/address/
// phone claim appears only when its scope was granted and the field is set.
func buildUserinfo(u *schema.User, claims *Claims, row *schema.Token, iss string, orgs []schema.OrgRef, wallets []schema.WalletRef) map[string]any {
aud := ""
if len(claims.Audience) > 0 {
aud = claims.Audience[0]
}
info := map[string]any{
"sub": claims.Subject,
"iss": iss,
"aud": aud,
"owner": claims.Owner,
}
if claims.Organization != "" {
info["organization"] = claims.Organization
}
// Who is acting, when it is not the subject: the operator impersonating them
// (`imp`), or the key acting for them. Read from the signed token, because it
// is a fact about this credential and not about the person — a client draws
// its "signed in as" banner from these two.
if claims.Act != nil {
info["act"] = claims.Act
}
if claims.Imp {
info["imp"] = true
}
// A client_credentials token (or a since-deleted user) has no profile.
if u == nil {
return info
}
// isAdmin is the SuperAdmin-predicate input the gateway admin-guard derives its
// decision from (with owner==adminOrg). It describes the token's OWN principal —
// read from the loaded user record (authoritative, never a token claim, matching
// the authz Principal) — so UserInfo is a drop-in for the retired get-account
// security contract. Emitted regardless of scope (it is identity, not profile),
// as `isAdmin` — the exact key the admin-guard + @hanzo/iam SDK read.
info["isAdmin"] = u.IsAdmin
// The membership set, home org first — the same value and the same shape the
// access token carries, so a client that reads one and a client that reads the
// other cannot reach two different answers about the same person.
//
// Its first entry is the org the account lives in, which is what platform
// authority is read from: authz.Claims.Sudo holds for a person whose first
// entry is the reserved admin org, and a later admin-org entry — a membership
// held from another org — confers nothing. Emitted regardless of scope,
// because it is identity rather than profile.
if len(orgs) > 0 {
info["orgs"] = orgs
}
// type distinguishes a real account from an auto-created anonymous session (the
// console's `type === "anonymous-user"` check); always present.
if u.Type != "" {
info["type"] = u.Type
}
// The wallet set and the DID, in the token's shapes and under the token's
// names. They are identity rather than profile — the same reasoning that
// puts orgs and isAdmin above the scope gate — and a client that reads one
// surface must not get a different answer from the other. The DID is derived
// from the LOADED row's subject, not echoed from the token, so it stays the
// same value identityOf would compute now.
if len(wallets) > 0 {
info["wallets"] = wallets
}
if id := schema.DID(subjectOf(u)); id != "" {
info["did"] = id
}
scope := row.Scope
if hasScope(scope, "profile") {
// `name` is the USERNAME here, matching the token claim exactly. UserInfo and
// the access token answer the same question — who is this principal — so they
// must not answer it with two different strings: a client that reads `name`
// from whichever it has in hand would otherwise hold a different identity
// depending on which call it made. The human's name has its own claim.
putIf(info, "preferred_username", u.Name)
putIf(info, "name", u.Name)
putIf(info, "displayName", u.DisplayName)
// The Gravatar fallback is a hash of the address, so it rides only with the
// email scope: a client granted profile alone learns nothing new from it.
picture := u.Avatar
if hasScope(scope, "email") {
picture = u.Picture()
}
putIf(info, "picture", picture)
putIf(info, "real_name", u.RealName)
// groups is the membership set flattened to bare organization names — the
// SAME source, and the same value, the access token's groups claim carries.
// One question about who a person belongs to has one answer, whichever call a
// relying party makes; a second source would let the two disagree, and a
// relying party that maps groups onto access would follow whichever it read.
if g := groupsOf(orgs, ""); len(g) > 0 {
info["groups"] = g
}
if u.IsVerified {
info["is_verified"] = true
}
}
if hasScope(scope, "email") && u.Email != "" {
info["email"] = u.Email
info["email_verified"] = u.EmailVerified
}
if hasScope(scope, "address") && u.Location != "" {
info["address"] = u.Location
}
if hasScope(scope, "phone") && u.Phone != "" {
info["phone"] = u.Phone
}
return info
}
// putIf sets key only when v is non-empty (omitempty for a map).
func putIf(m map[string]any, key, v string) {
if v != "" {
m[key] = v
}
}
// userinfoUnauthorized answers an invalid/absent bearer with the OIDC 401 shape
// and the Bearer challenge, leaking nothing about why beyond the token being
// unusable.
func userinfoUnauthorized(c *zip.Ctx, desc string) error {
c.SetHeader("WWW-Authenticate", `Bearer error="invalid_token", error_description="`+desc+`"`)
return c.JSON(401, map[string]string{"error": "invalid_token", "error_description": desc})
}