Files
iam/internal/oidc/token_exchange.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

207 lines
8.5 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package oidc
import (
"strconv"
"strings"
"time"
policy "github.com/hanzoai/authz"
"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"
)
// RFC 8693 OAuth 2.0 Token Exchange — the standard delegation / act-on-behalf-of
// flow, and the replacement for the the legacy surface `issue-user-token` verb (HIP-0111).
// A trusted, allow-listed confidential client presents a `subject_token`
// identifying the end user it acts for and receives a fresh access token bound to
// that user and re-scoped (RFC 8707 `resource`/`audience`) to a downstream
// resource server — indistinguishable from a token the user obtained directly, so
// a BFF can forward it and the resource server scopes on the validated `owner`.
//
// It reuses the same red-hardened controls as the other on-behalf-of primitives:
// the mint allow-list is matched by the globally-unique clientId ONLY, acting for
// a reserved-org (`admin`/`built-in`) subject needs the separate admin capability,
// and every exchange is audit-logged.
const (
grantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"
tokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token"
subjectTokenTypeAccess = "urn:ietf:params:oauth:token-type:access_token"
subjectTokenTypeIDToken = "urn:ietf:params:oauth:token-type:id_token"
subjectTokenTypeJWTToken = "urn:ietf:params:oauth:token-type:jwt"
)
// tokenExchangeGrant handles grant_type=urn:ietf:params:oauth:grant-type:token-exchange.
func tokenExchangeGrant(c *zip.Ctx, db orm.DB) error {
ctx := c.Context()
now := nowFunc()
// 1) Authenticate the acting client and enforce the exchange capability. A
// public client can never exchange; the allow-list is keyed on clientId only.
clientID, clientSecret := clientAuth(c)
if clientID == "" {
return tokenErrorClient(c, "client authentication required")
}
clientApp, err := store.GetApplicationByClientId(ctx, db, clientID)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
if clientApp == nil || clientApp.ClientSecret == "" || !clientApp.Proves(clientSecret) {
return tokenErrorClient(c, "client authentication failed")
}
// A delegation names its subject rather than proving it (delegate.go). It has
// its own allow-list and its own rules, and nothing below applies to it.
if param(c, "requested_subject") != "" {
return delegate(c, db, clientApp)
}
if !mintAllowed(clientApp) {
return tokenError(c, 403, "unauthorized_client", "client is not permitted for token exchange")
}
// 2) The subject_token identifies the user to act for (RFC 8693 §2.1, required).
// Its type, if given, must be a token type we verify.
subjectToken := param(c, "subject_token")
if subjectToken == "" {
return tokenError(c, 400, "invalid_request", "subject_token is required")
}
if st := param(c, "subject_token_type"); st != "" &&
st != subjectTokenTypeAccess && st != subjectTokenTypeIDToken && st != subjectTokenTypeJWTToken {
return tokenError(c, 400, "invalid_request", "unsupported subject_token_type")
}
claims, err := verifyToken(ctx, db, subjectToken)
if err != nil {
return tokenError(c, 400, "invalid_grant", "subject_token is invalid or expired")
}
if claims.Subject == "" {
return tokenError(c, 400, "invalid_grant", "subject_token carries no subject")
}
// A confined token is exchanged for nothing: the exchange would hand back the
// person's whole authority for a credential that was given model calls only.
if schema.Confined(claims.Scope) {
return tokenError(c, 400, "invalid_grant", "a confined token is not exchanged")
}
// Resolve the acted-for user from the subject_token's `sub` — which is now the
// stable UUID for a v2-minted token (store.GetUserBySubject decodes Id-or-name).
user, err := store.GetUserBySubject(ctx, db, claims.Subject)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
if user == nil || user.IsForbidden || user.IsDeleted {
return tokenError(c, 400, "invalid_grant", "the subject is unknown or forbidden")
}
// Every authority claim is the TARGET USER's, read from the resolved row —
// never split from the (now-opaque) subject.
owner := user.Owner
natural := user.Owner + "/" + user.Name
// 3) A reserved-org subject — every SuperAdmin (schema.User.SuperAdmin) lives
// in one — is a cross-tenant identity: gate it behind the separate
// admin-exchange capability. The owner is read off the RESOLVED row, never
// split from the subject.
if policy.IsSigningOwner(owner) && !adminMintAllowed(clientApp) {
return tokenError(c, 403, "access_denied", "not permitted to act for a reserved-org subject")
}
// 4) The requested audience (RFC 8707) — resource wins, then audience, else the
// subject's own app. requested_token_type, if given, must be an access token.
if rt := param(c, "requested_token_type"); rt != "" && rt != tokenTypeAccessToken {
return tokenError(c, 400, "invalid_request", "only an access_token may be requested")
}
aud := resourceOf(c)
if aud == "" {
aud = defaultUserAudience(ctx, db, user, clientApp)
}
// 5) Mint for the subject, scoped to the requested audience, azp = the acting
// client (records who exchanged). Signed under the trusted cert + issuer.
iss, err := tokenIssuer(c)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
signer, err := signerFor(ctx, db, clientApp, iss)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
// A caller may ask for LESS life than the application declares and never more.
// A credential handed to a process that ends — a leased sandbox, one job — should
// die no later than the process does, and the client is the only party that knows
// when that is. The clamp runs one way, so the request can shorten the token and
// nothing about it can lengthen the application's own lifetime.
ttl := appTTL(clientApp)
if want := seconds(param(c, "lifetime")); want > 0 && want < ttl {
ttl = want
}
scope := param(c, "scope")
id := identityOf(ctx, db, user) // the ONE user→claims resolution
// An impersonated subject_token stays impersonated: the operator rides forward
// in `act` beside `imp`, and the new token dies no later than the one it was
// exchanged for. An exchange is never how an impersonation sheds its mark or
// its clock.
actor := ""
if claims.Imp {
if actor, err = Operator(ctx, db, claims); err != nil {
trail{actor: actorKey(claims.Act), target: natural, client: clientApp.ClientId, ip: httpx.ClientIP(c),
method: "POST", uri: PathToken, org: owner}.record(ctx, db, 400, "the impersonation is no longer permitted")
return tokenError(c, 400, "invalid_grant", "the impersonation is no longer permitted")
}
id.Act, id.Imp = claims.Act, true
ttl = min(ttl, impersonationTTL)
if claims.ExpiresAt != nil {
ttl = min(ttl, claims.ExpiresAt.Sub(now))
}
}
access, err := signer.SignUserToken(id, owner, aud, clientApp.ClientId, scope, ttl, now)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
row := &schema.Token{
Owner: owner,
Application: clientApp.Name,
Organization: owner,
User: natural, // the row's User stays the (owner/name) key
Scope: scope,
TokenType: "Bearer",
ExpiresIn: int(ttl.Seconds()),
AccessTokenHash: hashToken(access),
Actor: actor,
}
row.Name = "tx-" + hashToken(access)[:32]
if err := store.PersistToken(ctx, db, row); err != nil {
return tokenError(c, 500, "server_error", "")
}
auditMint(ctx, db, c, schema.ActionTokenExchange, clientApp.ClientId, natural)
if actor != "" {
trail{actor: actor, target: natural, client: clientApp.ClientId, ip: httpx.ClientIP(c),
method: "POST", uri: PathToken, org: owner, ttl: ttl}.record(ctx, db, 200, "")
}
// 6) RFC 8693 §2.2 response.
return c.JSON(200, map[string]any{
"access_token": access,
"issued_token_type": tokenTypeAccessToken,
"token_type": "Bearer",
"expires_in": int(ttl.Seconds()),
"scope": scope,
})
}
// seconds reads a requested duration in whole seconds. Absent, unparseable or
// non-positive all mean the caller asked for nothing, which leaves the
// application's own lifetime standing rather than failing the exchange over a
// field that only ever narrows what it already grants.
func seconds(s string) time.Duration {
n, err := strconv.Atoi(strings.TrimSpace(s))
if err != nil || n <= 0 {
return 0
}
return time.Duration(n) * time.Second
}