Files
iam/internal/oidc/jwt.go
zeekay 2bbb0db654 A brand org is no tenant of its plain members, and a key dies with its holder
A key resolves only while its holder may sign in: a suspended or deleted
account's keys answer key_holder_disabled, its org's default key included. An
org the platform runs (authz.IsPlatformOrg) is a tenant only of its owners and
admins, its own machines and a SuperAdmin, and a brand's directory of no one:
store.Acts is that rule asked of one row, and the key resolver
(key_not_tenant), the user-key mint (403, no key filed that acts for no one) and
the delegation read it. principal.Scope and ScopeRead require MemberOf, the org
listing filters by it, and the registry gives a person a token only as an admin
of a candidate org.

A delegated token (as(), naming its actor in act) founds no org and writes no
account. A suspended account resolves nobody on its session or its bearer, and
founds nothing. An act key names its holder and mints only while that holder
runs the key's org. A machine signs in as an application or with its key: it is
refused a password grant, a form sign-in and an invitation. The groups claim
carries the orgs a person is a tenant of, so a relying party that maps groups
onto access sees no directory and no brand org held as a plain member. A name a
removed org still holds draws the answer a standing one does.

authz v1.10.47.
2026-10-17 04:07:47 -07:00

535 lines
24 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package oidc
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
policy "github.com/hanzoai/authz"
"github.com/hanzoai/iam/pkg/schema"
)
// JWT token signing. The signing algorithm is a property of the signing Cert's
// key, not a global: an RSA cert signs RS256 (the interoperable default that the
// live hanzo.id JWKS serves), an EC cert signs ES256/384/512, and a post-quantum
// ML-DSA-65 cert signs MLDSA65 (mldsa.go, behind the same jwt.SigningMethod
// seam). The classical path is the load-bearing interop path — every existing
// verifier reads the RS256 keys published in the JWKS; ML-DSA is additive and
// inert until an ML-DSA Cert is configured.
//
// A Signer's key arrives on the Cert the store hands it. The Cert ROW carries
// only the key's identity — the `kid`, the algorithm; the private half is not
// stored and is filled in on load, in memory, from the material the deployment
// mounts (internal/keyring).
// Claims is the iam token claim set: the standard registered claims plus the
// Hanzo first-class claims the SDK and downstream validators read. owner and
// organization are the tenant (both the org slug); scope carries the granted
// scopes; nonce is echoed into the id_token; tokenType distinguishes an
// access-token from an id-token. A field is emitted only when populated, so one
// struct serves both token shapes without leaking empty claims.
type Claims struct {
jwt.RegisteredClaims
Scope string `json:"scope,omitempty"`
Owner string `json:"owner,omitempty"`
Organization string `json:"organization,omitempty"`
Email string `json:"email,omitempty"`
// Name is the IAM USERNAME (the `<name>` half of `<owner>/<name>`, e.g. "z"),
// never a display name. With Owner it forms the ONE address every Hanzo surface
// names a principal by — `hanzo auth login` files its credential under
// `owner/name` read straight off these claims, so whatever lands here IS the
// principal downstream believes it holds.
//
// OIDC gives `name` display semantics and this token used to honour that,
// carrying DisplayName ("Grace Hopper") while the account was "z". Adding
// preferred_username gave the username somewhere to live but left `name`
// display-sourced, so the wrong-principal reading stayed on the wire for every
// consumer that reads `name` — the CLI among them. The display name now has its
// own claim (Display) and `name` states the username, always. That is a
// deliberate divergence from OIDC's display reading of `name`, taken because
// one address for a principal beats two spellings that disagree.
Name string `json:"name,omitempty"`
// PreferredUsername is the OIDC-standard spelling of the same username, kept
// because discovery advertises it in claims_supported and cloud's money path
// already reads it: a wallet is addressed `<org>/<username>`, and when the only
// username-shaped claim was a display-sourced `name` it addressed
// `hanzo/Grace Hopper` — a wallet no funding path can name — while the balance
// sat in `hanzo/z`. It is sourced from the SAME field as Name (Identity.Name),
// so the two cannot drift apart the way `name` drifted from the account.
PreferredUsername string `json:"preferred_username,omitempty"`
// Display is the human-facing name — what a console greets you by. It is
// profile data, never an address: nothing may resolve a principal from it.
// `displayName` is the spelling schema.User, SCIM and whoami already use, so
// this value keeps its one name across every surface that carries it.
Display string `json:"displayName,omitempty"`
// BillingAccount names WHICH LEDGER this token spends from — the org pool, or
// empty to let the consumer's shape rule pick. account.Payer honours it above
// every other signal precisely because it is SIGNED: a caller cannot name its
// own payer, so this is IAM stating who is entitled to spend what.
//
// Empty is meaningful, not missing: it means "no explicit entitlement", and
// the consumer falls back to the behaviour it already had.
BillingAccount string `json:"billing_account,omitempty"`
// Type is the principal's identity CLASS — schema.Program for a token
// the client_credentials grant minted, absent for a person. It is the same fact
// billing_account already states, said as identity rather than as money, and
// it is stated for the same reason: IAM resolves it from the GRANT SHAPE, so
// only IAM can say it and a caller cannot forge it.
//
// A consumer needs both because they answer different questions. Money asks
// which ledger (the org pool); attribution asks whose spend this is, and a
// program's spend is nobody's — it belongs in an agent column with the person
// column left empty. Without this claim a consumer had to INFER the class,
// and the available inference (the token's audience equals its name) is true
// only while the app is single-tenant: audienceFor qualifies a SHARED app's
// audience with its org, so the inference silently reports every shared app's
// machine as a person.
Type string `json:"type,omitempty"`
Nonce string `json:"nonce,omitempty"`
Azp string `json:"azp,omitempty"`
TokenType string `json:"tokenType,omitempty"`
// Orgs is the membership set — the tenancy the identity may act in, home org
// first — a resource server reads to authorize an org-switch (X-Org-Id ∈ orgs)
// with no round-trip. omitempty ⇒ a nil set omits the claim entirely (a machine
// token, which has no membership, never carries it), so one struct still serves
// both an app token and a user token without emitting an empty claim.
Orgs []schema.OrgRef `json:"orgs,omitempty"`
// Act names the ACTOR a delegated token was minted BY — the org key behind
// as(), or the SuperAdmin impersonating the subject. RFC 8693 §4.1: a nested
// object a resource server reads to see WHO acted for the subject, kept
// distinct from the subject the token authorizes. It attributes; it never
// authorizes — authority is the subject's. Absent on every ordinary token.
// An exchange carries it forward only from an impersonated subject_token.
Act *Actor `json:"act,omitempty"`
// Imp marks an IMPERSONATED token: a platform operator signed in as the
// subject, named in Act. A client shows a banner on it; a resource server
// refuses it any durable credential or money act. Absent everywhere else.
Imp bool `json:"imp,omitempty"`
// Assumed names the organization a platform operator has stepped into
// (/v1/iam/assume). Absent on every ordinary token.
//
// It does not replace anybody. Subject, owner and name remain the operator's
// own, so the act is attributed to the person who performed it and metering
// bills the account that did the work; this claim says WHERE they were
// working. `orgs` carries the tenant beside it, which is how the assumed
// organization is reached — through the org switch a resource server already
// implements, rather than a second one taught to every consumer.
//
// It is a LABEL, not a sandbox. An operator keeps the authority they already
// held: IAM resolves SuperAdmin from the membership rows, never from a token
// claim, so a claim could not withdraw it here and pretending otherwise
// downstream would mean two answers to one question.
Assumed string `json:"assumed,omitempty"`
// Groups is the same membership set as flat names, under the name OIDC
// consumers already read. `orgs` carries a role per org, which is what our own
// resource servers need and what a generic consumer cannot parse: a relying
// party that maps a groups claim reads strings, so an object list stringifies
// to `map[Org:admin Role:admin]` and matches nothing.
//
// It is DERIVED from Orgs at the one place Orgs is set, so the two cannot
// disagree about who belongs where — a second list assembled from a second
// query is how a consumer comes to grant on stale membership.
//
// It lists MEMBERSHIP, so "admin" among a person's groups says they belong to
// the reserved org, not that they are a SuperAdmin: a brand org's person added
// to it appears here too. SuperAdmin is the person's own org being "admin",
// which is the FIRST entry of `orgs` (authz.Claims.Sudo). A relying party that
// grants platform authority on `groups` grants it by membership.
Groups []string `json:"groups,omitempty"`
// Wallets is the chain-qualified addresses this person has PROVED control
// of — each one the result of a CAIP-122 challenge IAM minted, bound to its
// issuing host, and verified against a burned single-use nonce
// (internal/wallet). A relying party reading it is reading IAM's assertion
// that the holder controlled that key, at some point, to this issuer.
//
// It is stated in the token because the alternative is every service that
// cares about a wallet asking IAM at request time, or worse, accepting an
// address the client names. A signed claim removes both.
//
// What it is NOT: proof the holder controls the key RIGHT NOW. A key can be
// sold, lost, or compromised between the link and this token; the claim is
// as fresh as the token's lifetime and no fresher. A payment authorization
// wants its own signature, not this.
Wallets []schema.WalletRef `json:"wallets,omitempty"`
// DID is the account's decentralized identifier, `did:lux:<subject>`,
// derived from `sub` (schema.DID) rather than stored beside it. It is
// present on every user token — deriving it needs no registry, and a
// deployment that anchors documents on chain (internal/did) writes the same
// string this claim carries. Absent only for a subject the derivation
// refuses, and on machine tokens, which have no person to name.
DID string `json:"did,omitempty"`
}
// Identity is WHO a token speaks for: the caller-resolved values every mint
// path turns into claims. It exists because those values used to travel as six
// adjacent positional strings, two of which — the username and the display name
// — are both human-readable and were therefore swappable at the call site. They
// were swapped, on all three mint paths at once, and the swap type-checks.
//
// One field per value, resolved in ONE place (identityOf), makes the swap
// unrepresentable: Name is the username, Display is the human's name, and no
// call site restates the difference. Zero value = no principal profile (a
// machine token, or a since-deleted user); every claim it feeds is omitempty, so
// the token omits them rather than emitting them empty.
type Identity struct {
Id string // the OIDC `sub` — stable and opaque
Email string
Name string // the IAM USERNAME, the `<name>` half of `<owner>/<name>`
Display string // the human-facing name; never an address
Billing string
Type string // the identity CLASS; empty for a person (schema.Program)
Orgs []schema.OrgRef
Assumed string // the organization a platform operator has stepped into
// Wallets is the set of chain-qualified addresses the person has proved
// control of, and DID is the identifier derived from Id (schema.DID). Both
// are resolved in identityOf beside everything else, so a mint path cannot
// state one of them differently from another path.
Wallets []schema.WalletRef
DID string
// Act and Imp are who is ACTING for this identity, when it is not the
// person: an operator impersonating them (Imp). Nil and false for a person
// acting as themselves.
Act *Actor
Imp bool
}
// Actor is the RFC 8693 `act` claim value: the identity that requested a
// delegated token. `sub` is the actor's own subject; an operator impersonating
// someone is also named by `owner`/`name`, the address a banner and an audit
// trail print. A longer delegation chain nests another Actor the same way, if
// one is ever needed.
type Actor struct {
Sub string `json:"sub,omitempty"`
Owner string `json:"owner,omitempty"`
Name string `json:"name,omitempty"`
}
// Signer signs tokens with one key under one algorithm. Immutable after
// construction; the (method, key, kid, alg) tuple is fixed to the Cert it was
// built from so a token can never be signed under a key/alg mismatch.
type Signer struct {
method jwt.SigningMethod
key any // *rsa.PrivateKey | *ecdsa.PrivateKey | *mldsa65.PrivateKey
kid string // JWKS key id — the Cert name
alg string // JOSE alg — "RS256" | "ES256" | … | "MLDSA65"
issuer string
}
// NewSignerFromCert builds a Signer from a Cert, selecting the algorithm from
// the cert's key type: RSA → RS256 (or RS512 when the app pins it), EC → ES256/
// ES384/ES512 by curve, ML-DSA → MLDSA65. issuer is the canonical OIDC issuer
// (https://<host>) that discovery advertises; it is pinned into every token so
// id_token `iss` matches the discovery document. app may be nil (the method is
// then chosen purely from the key type).
func NewSignerFromCert(cert *schema.Cert, app *schema.Application, issuer string) (*Signer, error) {
if cert == nil {
return nil, errors.New("jwt: nil cert")
}
// Post-quantum ML-DSA-65 cert: raw key material, own signing method.
if isMLDSACert(cert) {
key, err := parseMLDSA65PrivateKey(cert.PrivateKey)
if err != nil {
return nil, err
}
return &Signer{method: SigningMethodMLDSA65, key: key, kid: cert.Name, alg: algMLDSA65, issuer: issuer}, nil
}
if cert.PrivateKey == "" {
return nil, errors.New("jwt: cert has no private key")
}
key, err := parsePrivateKeyPEM(cert.PrivateKey)
if err != nil {
return nil, err
}
method, alg, err := methodForKey(key, pinnedMethod(app))
if err != nil {
return nil, err
}
return &Signer{method: method, key: key, kid: cert.Name, alg: alg, issuer: issuer}, nil
}
// NewRSASignerFromCert builds an RS256 Signer from a Cert whose PrivateKey is a
// PEM RSA key. Retained as the explicit RSA constructor; NewSignerFromCert is
// the general dispatch used by the token endpoint.
func NewRSASignerFromCert(cert *schema.Cert, issuer string) (*Signer, error) {
if cert == nil || cert.PrivateKey == "" {
return nil, errors.New("jwt: cert has no private key")
}
key, err := parseRSAPrivateKeyPEM(cert.PrivateKey)
if err != nil {
return nil, err
}
return &Signer{method: jwt.SigningMethodRS256, key: key, kid: cert.Name, alg: "RS256", issuer: issuer}, nil
}
// NewRSASigner builds an RS256 Signer directly from an RSA key, for a test that
// wants to sign with a key it holds rather than one a Cert names.
func NewRSASigner(key *rsa.PrivateKey, kid, issuer string) *Signer {
return &Signer{method: jwt.SigningMethodRS256, key: key, kid: kid, alg: "RS256", issuer: issuer}
}
// claims is the ONE place an Identity becomes a claim set. Every mint path goes
// through it, so `name`, `preferred_username` and `displayName` are sourced from
// the same two fields on every token shape and cannot be filled differently by
// one path than another. The caller supplies only what genuinely differs between
// shapes: the tenant, the audience, the acting client, and the token type.
func (s *Signer) claims(id Identity, owner string, aud jwt.ClaimStrings, azp, scope, kind string, ttl time.Duration, now time.Time) (Claims, error) {
jti, err := newOpaqueToken()
if err != nil {
return Claims{}, err
}
return Claims{
RegisteredClaims: jwt.RegisteredClaims{
Issuer: s.issuer,
Subject: id.Id,
Audience: aud,
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
NotBefore: jwt.NewNumericDate(now),
IssuedAt: jwt.NewNumericDate(now),
ID: jti,
},
Scope: scope,
Owner: owner,
Organization: owner,
Email: id.Email,
Name: id.Name,
PreferredUsername: id.Name,
Display: id.Display,
BillingAccount: id.Billing,
Type: id.Type,
Azp: azp,
TokenType: kind,
Orgs: id.Orgs,
Groups: groupsOf(id.Orgs, id.Type),
Assumed: id.Assumed,
Wallets: id.Wallets,
DID: id.DID,
Act: id.Act,
Imp: id.Imp,
}, nil
}
// groupsOf flattens the membership set to the names a groups claim carries. A
// relying party maps a group onto access, so a membership that makes no one a
// tenant is no group: a brand's directory, and an org the platform runs held as a
// plain member (authz Claims.Tenancy says the same of both). A machine's set is
// its explicit grants and is carried whole. The admin org is carried as it is
// held, which is how a federated app sees the operator. Nil in, nil out, so a
// machine token omits the claim exactly as it omits orgs.
func groupsOf(orgs []schema.OrgRef, typ string) []string {
if len(orgs) == 0 {
return nil
}
out := make([]string, 0, len(orgs))
for _, o := range orgs {
if o.Org == "" {
continue
}
if typ != schema.Program && (policy.IsDirectory(o.Org) ||
(policy.IsPlatformOrg(o.Org) && !policy.Role(o.Role).Admits(policy.Write))) {
continue
}
out = append(out, o.Org)
}
return out
}
// Sign issues a signed access token for (app, identity) with the given scope. now
// is injected for testability; ttl is the token lifetime. The audience is the
// app's clientId (validators fail closed when aud != clientId). The owner claim is
// the APP's org. id.Orgs is the caller-resolved membership set — home org first for
// a user (store.MemberOrgRefs), the explicit grants for a machine (granted) — and
// nil omits the claim. The Signer stays decoupled from schema.User; the caller
// resolves the tenancy and passes it.
func (s *Signer) Sign(app *schema.Application, id Identity, scope, resource string, ttl time.Duration, now time.Time) (string, error) {
if s == nil {
return "", errors.New("jwt: nil signer")
}
claims, err := s.claims(id, app.Organization, audienceFor(app, resource), app.ClientId, scope, "access-token", ttl, now)
if err != nil {
return "", err
}
return s.signClaims(claims)
}
// SignUserToken mints an access token a confidential client issues ON BEHALF OF a
// target user — the RFC 8693 Token Exchange grant. Unlike Sign (which stamps the
// APP's org as the owner claim), every authority claim here is the TARGET USER's:
// the subject and owner are the user's, so a resource server that scopes on the
// validated `owner` claim (cloud's SanitizeIdentity) scopes to the USER's tenant,
// never the minting client's. `aud` is the caller-resolved audience (an explicit
// RFC 8707 resource, else the user's own app) and `azp` records the minting
// client. Signed under this signer's trusted cert + canonical issuer, so the same
// JWKS verifies it — the token is indistinguishable from one the user obtained
// directly, which is the point. The Signer stays decoupled from schema.User: the
// handler resolves and passes the values it authorized.
func (s *Signer) SignUserToken(id Identity, owner, aud, azp, scope string, ttl time.Duration, now time.Time) (string, error) {
if s == nil {
return "", errors.New("jwt: nil signer")
}
claims, err := s.claims(id, owner, jwt.ClaimStrings{aud}, azp, scope, "access-token", ttl, now)
if err != nil {
return "", err
}
return s.signClaims(claims)
}
// SignAct mints a user-bound access token that ALSO records the actor that
// requested it — the credential behind as(). It is SignUserToken plus the RFC 8693
// `act` claim: every authority claim is the TARGET USER's (subject, owner), so a
// resource server scopes to the user's tenant exactly as for a token the user
// obtained directly, while `act` names, separately, the org key that acted for
// them. `azp` records the party the token is authorized to; scope is empty (an
// as() token carries the user's full authority, narrowed only by its short life).
// SignUserToken stays act-less, so token exchange is unchanged.
func (s *Signer) SignAct(id Identity, owner, aud, azp string, act Actor, ttl time.Duration, now time.Time) (string, error) {
if s == nil {
return "", errors.New("jwt: nil signer")
}
claims, err := s.claims(id, owner, jwt.ClaimStrings{aud}, azp, "", "access-token", ttl, now)
if err != nil {
return "", err
}
claims.Act = &act
return s.signClaims(claims)
}
// SignID issues an OIDC id_token for (app, user). It differs from the access
// token by carrying the echoed nonce and by declaring tokenType "id-token"; the
// audience is the client the token was minted for (the RP), and iss matches the
// discovery issuer so a standard OIDC client validates it.
func (s *Signer) SignID(app *schema.Application, id Identity, scope, nonce string, ttl time.Duration, now time.Time) (string, error) {
if s == nil {
return "", errors.New("jwt: nil signer")
}
claims, err := s.claims(id, app.Organization, jwt.ClaimStrings{app.ClientId}, app.ClientId, scope, "id-token", ttl, now)
if err != nil {
return "", err
}
claims.Nonce = nonce
return s.signClaims(claims)
}
// signClaims is the single choke point that turns a claim set into a signed
// compact JWS under this signer's fixed (method, key, kid).
func (s *Signer) signClaims(claims Claims) (string, error) {
tok := jwt.NewWithClaims(s.method, claims)
if s.kid != "" {
tok.Header["kid"] = s.kid
}
return tok.SignedString(s.key)
}
// PublicKey returns the signer's RSA public key, or nil for a non-RSA signer
// (JWKS + verification read the public key from the Cert, not the Signer).
func (s *Signer) PublicKey() *rsa.PublicKey {
if k, ok := s.key.(*rsa.PrivateKey); ok {
return &k.PublicKey
}
return nil
}
// Kid returns the key id (the Cert name).
func (s *Signer) Kid() string { return s.kid }
// Alg returns the JOSE algorithm this signer uses (matches the JWKS `alg`).
func (s *Signer) Alg() string { return s.alg }
// audienceFor computes the token audience per RFC 8707: an explicit resource
// indicator wins; a shared application scopes the audience to the org; otherwise
// the audience is the client id (the value validators check).
func audienceFor(app *schema.Application, resource string) jwt.ClaimStrings {
if resource != "" {
return jwt.ClaimStrings{resource}
}
if app.IsShared && app.Organization != "" {
return jwt.ClaimStrings{app.ClientId + "-org-" + app.Organization}
}
return jwt.ClaimStrings{app.ClientId}
}
// pinnedMethod is the app's requested signing method (TokenSigningMethod), or ""
// to let the key type decide.
func pinnedMethod(app *schema.Application) string {
if app == nil {
return ""
}
return app.TokenSigningMethod
}
// methodForKey maps a parsed private key (and an optional app-pinned method
// within the same family) to a jwt.SigningMethod and its JOSE alg name.
func methodForKey(key any, pinned string) (jwt.SigningMethod, string, error) {
switch k := key.(type) {
case *rsa.PrivateKey:
if pinned == "RS512" {
return jwt.SigningMethodRS512, "RS512", nil
}
return jwt.SigningMethodRS256, "RS256", nil
case *ecdsa.PrivateKey:
switch k.Curve.Params().BitSize {
case 256:
return jwt.SigningMethodES256, "ES256", nil
case 384:
return jwt.SigningMethodES384, "ES384", nil
case 521:
return jwt.SigningMethodES512, "ES512", nil
}
return nil, "", fmt.Errorf("jwt: unsupported EC curve bit size %d", k.Curve.Params().BitSize)
default:
return nil, "", errors.New("jwt: unsupported private key type")
}
}
// parsePrivateKeyPEM decodes a classical (RSA or EC) PEM private key.
func parsePrivateKeyPEM(pemText string) (crypto.Signer, error) {
block, _ := pem.Decode([]byte(pemText))
if block == nil {
return nil, errors.New("jwt: private key is not valid PEM")
}
if k, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
return k, nil
}
if k, err := x509.ParseECPrivateKey(block.Bytes); err == nil {
return k, nil
}
k8, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("jwt: parse private key: %w", err)
}
signer, ok := k8.(crypto.Signer)
if !ok {
return nil, errors.New("jwt: PKCS#8 key is not a signing key")
}
return signer, nil
}
// parseRSAPrivateKeyPEM decodes a PEM RSA private key (PKCS#1 or PKCS#8).
func parseRSAPrivateKeyPEM(pemText string) (*rsa.PrivateKey, error) {
block, _ := pem.Decode([]byte(pemText))
if block == nil {
return nil, errors.New("jwt: private key is not valid PEM")
}
if k, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
return k, nil
}
k8, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("jwt: parse private key: %w", err)
}
rk, ok := k8.(*rsa.PrivateKey)
if !ok {
return nil, errors.New("jwt: private key is not RSA")
}
return rk, nil
}