Files
zeekayandGitHub d7ea42d4e2 oidc: IAM_ACCEPTED_ISSUERS, the platform issuers IAM verifies and never mints under (#45)
IAM_ACCEPTED_ISSUERS names platform issuers (https origins) whose tokens IAM verifies and
never mints under, so the platform issuer can move from hanzo.id to hanzo.ai while tokens
under the old one are in flight: bearer tokens, agent identity assertions (seven days) and
workload ServiceAccount audiences. resolveIssuer never returns a listed issuer, a credential
replacing one under it is minted under the default issuer, discovery never mentions the set,
and an organization's issuer is never accepted through it. The tenant origin may itself be a
platform issuer; a platform issuer under `<tenant origin>/` is refused at boot.

Testing: go generate, go vet ./... and go test ./... pass; CI test-amd64 and cicd pass. New
TestAcceptedIssuers_* are mutation-checked. TestLogin_MemberMissTakesAsLongAsAWrongPassword
is a timing test that flakes on a loaded box and passes alone.
Risk: inert while IAM_ACCEPTED_ISSUERS is unset; set, it widens verification to the listed
origins' platform-signed tokens only.
How to revert: revert this commit.

Claude-Session: https://claude.ai/code/session_015XYKLn69gF4x75RWePpDBV
2026-11-20 21:44:21 -08:00

208 lines
8.6 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")
}
// A tenant's own relying party calls this with a token under its organization's
// issuer; the platform-authority paths verify the platform's alone.
claims, err := verifyIssuedBearer(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"})
}
if _, own := tenantOrgOf(claims.Issuer); own {
iss = claims.Issuer // already verified to be the organization's exact issuer
} else if acceptedOnly(claims.Issuer) {
iss = normalizeIssuer(claims.Issuer) // the issuer the relying party holds a token under
}
// 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
// Relies on the stored EmailVerified bit (OTP prove, verified federation
// link, or backfill). Callers that require proof must read this claim.
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})
}