Files
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

446 lines
18 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package oidc
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"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/internal/keyring"
"github.com/hanzoai/iam/pkg/schema"
"github.com/hanzoai/iam/pkg/store"
)
// Delegation: RFC 8693 token exchange with an ACTOR and no subject_token.
//
// A trusted orchestrator (cloud, as hanzo-cloud) runs work FOR a person in a
// process it does not trust: a sandbox executing a model's output. That process
// needs a credential for its model calls, and both credentials it could otherwise
// be handed are wrong. The orchestrator's own machine token bills the platform
// for every tenant's work and puts the deployment's identity in a box an attacker
// may control; the person's full token (tokens/issue) is everything the person may
// do. So the orchestrator asks for a third thing: a token whose subject is the
// person, in the one org the work bills, whose actor is the orchestrator, that
// reaches model inference and nothing else, and that dies with the work.
//
// POST /v1/iam/oauth/token
// grant_type=urn:ietf:params:oauth:grant-type:token-exchange
// client_id, client_secret the orchestrator, confidential
// actor_token=<its own access token> RFC 8693 §2.1
// requested_subject=<sub | owner/name> the person
// org=<slug> the org the work bills
// scope=ai:inference the one scope a delegation carries
// resource=https://api.hanzo.ai RFC 8707, on IAM_DELEGATION_AUDIENCES
// lifetime=<seconds> at most delegationTTL, one way
// run=<id> recorded, never signed
//
// There is no subject_token because the person is not present: a run a Slack
// message started holds no token of theirs. What stands in for that proof is the
// allow-list (IAM_DELEGATION_APPS: admin-owned clients only, fail closed), the
// membership IAM checks itself, and how little the token that comes back can do.
//
// What comes back is the person's token narrowed, and SIGNED BY A KEY NO PUBLIC
// VERIFIER HOLDS (schema.CertDelegation). That is the narrowing that holds outside
// cloud: every other resource server in the estate verifies against the public
// JWKS and reads none of the claims below, so a delegated token signed by a
// published key was the person to all of them. Under the delegation key its `kid`
// resolves nowhere they look, and they refuse it without understanding it. Cloud
// reads the key from PathDelegationKeys with the credential that asked for the
// token. Inside cloud, each remaining narrowing is a claim it already reads:
//
// orgs the one org asked for, as a member, so no org switch reaches
// another and no admin role rides along; the org is never a
// reserved one, so the token is never SuperAdmin
// scope ai:inference (schema.Confined): cloud serves it model calls only,
// and IAM accepts it as a bearer nowhere (verifyBearer)
// aud an https URI, never a client id, so no consumer that admits a
// token by its client (S3's federation) admits this one; azp is
// empty for the same reason
// exp the run's deadline, at most delegationTTL; no refresh token
//
// and `act` names the orchestrator, so every reader sees who acted.
// delegationTTL caps a delegated token's life, and is what a client that does not
// say how long its run lasts gets. It is the delegation's own bound, independent
// of the asking client's token lifetime.
const delegationTTL = 4 * time.Hour
// delegationAllowed reports whether app may obtain delegated tokens. Its own list,
// separate from IAM_TOKEN_EXCHANGE_APPS: a delegation reaches less than an
// exchange, and a client allowed the narrower act is not thereby allowed the
// wider. Same owner-pin as mintAllowed, so a tenant's colliding clientId acts for
// nobody. Unset, it allows nothing.
func delegationAllowed(app *schema.Application) bool {
return policy.IsSigningOwner(app.Owner) && appInList("IAM_DELEGATION_APPS", app.ClientId)
}
// delegate answers a token exchange that names its subject (requested_subject).
// client has already proved its secret.
func delegate(c *zip.Ctx, db orm.DB, client *schema.Application) error {
ctx := c.Context()
now := nowFunc()
// Until the client is known to be allowed to delegate, the row names the client
// and nothing it wrote: any tenant's confidential app reaches this branch, and a
// subject, org or run it chose would be its words filed as the platform's.
d := delegation{client: client.ClientId, ip: httpx.ClientIP(c), filed: client.Owner}
refuse := func(status int, code, desc string) error {
d.record(ctx, db, status, desc)
return tokenError(c, status, code, desc)
}
if !delegationAllowed(client) {
return refuse(403, "unauthorized_client", "client is not permitted to delegate")
}
// From here the client is trusted to name the person, the org and the run, and
// the row is filed where that org's tenant reads it.
d.subject = strings.TrimSpace(param(c, "requested_subject"))
d.org, d.run = param(c, "org"), param(c, "run")
if d.org == "" || len(d.org) > 128 || policy.HasUnsafeRune(d.org) {
return refuse(400, "invalid_request", "org is required")
}
d.filed = d.org
if param(c, "subject_token") != "" {
return refuse(400, "invalid_request", "a delegation names its subject and presents no subject_token")
}
if len(d.run) > 128 || policy.HasUnsafeRune(d.run) {
return refuse(400, "invalid_request", "run is not an identifier")
}
if rt := param(c, "requested_token_type"); rt != "" && rt != tokenTypeAccessToken {
return refuse(400, "invalid_request", "only an access_token may be requested")
}
actor, why := actorProof(ctx, db, c, client)
if why != "" {
return refuse(400, "invalid_grant", why)
}
scope := strings.TrimSpace(param(c, "scope"))
if scope != schema.Inference {
return refuse(400, "invalid_scope", "the one scope a delegation carries is "+schema.Inference)
}
aud := resourceOf(c)
if !delegationAudience(aud) {
return refuse(400, "invalid_target", "resource must be an API this IAM delegates to")
}
user, err := store.GetUserBySubject(ctx, db, d.subject)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
if user == nil || user.IsForbidden || user.IsDeleted || user.Machine() {
return refuse(400, "invalid_grant", "the subject is not a person who may be acted for")
}
d.subject = user.Owner + "/" + user.Name
// A reserved-org identity (every SuperAdmin) is never delegated: IAM reads its
// authority off the ROW, so a token naming it is the platform's authority in a
// box running model output, however narrow its claims. Its owner works in a
// tenant through their tenant account.
if policy.IsReservedOrg(user.Owner) {
return refuse(403, "access_denied", "a reserved-org identity is never delegated")
}
if policy.IsReservedOrg(d.org) {
return refuse(403, "access_denied", "a delegated token never acts in a reserved org")
}
ref, ok, err := membership(ctx, db, user, d.org)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
if !ok {
return refuse(403, "access_denied", "the subject is not a member of "+d.org)
}
if !store.Acts(d.org, user, ref.Role) {
return refuse(403, "access_denied", "the subject does not act in "+d.org)
}
// A caller may ask for less life than the cap and never more. The client's own
// token lifetime is NOT a bound: it says how long the orchestrator's identity
// lasts, not how long a person's run does, and reading it cut every run to an
// hour (hanzo-cloud declares none, so it takes the one-hour default).
ttl := delegationTTL
if want := seconds(param(c, "lifetime")); want > 0 && want < ttl {
ttl = want
}
d.ttl = ttl
// The person as their own token states them, narrowed to the one org. The
// billing claim names the HOME org's pool; acting anywhere else, the person's
// own token spends by the shape rule (account.Payer ignores a claim naming
// another org), so the delegated token carries none there and spends the same.
id := identityOf(ctx, db, user)
// Member, whatever the person's role there: a token delegated for model calls
// administers nothing, and a role it does not need is reach it should not carry.
id.Orgs = []schema.OrgRef{{Org: ref.Org, Role: store.RoleMember}}
if d.org != user.Owner {
id.Billing = ""
}
id.Act = &actor
iss, err := tokenIssuer(c)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
signer, err := delegationSigner(ctx, db, iss)
if errors.Is(err, ErrNoSigningCert) {
return refuse(503, "temporarily_unavailable", keyNotMounted)
}
if err != nil {
return tokenError(c, 500, "server_error", "")
}
access, err := signer.SignUserToken(id, d.org, aud, "", scope, ttl, now)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
row := &schema.Token{
Owner: d.org,
Application: client.Name,
Organization: d.org,
User: d.subject,
Scope: scope,
TokenType: "Bearer",
ExpiresIn: int(ttl.Seconds()),
AccessTokenHash: hashToken(access),
}
// 'dl-' beside 'tx-', 'iut-' and 'as-': revocable by the client that asked,
// and live to introspection while the row stands.
row.Name = "dl-" + hashToken(access)[:32]
if err := store.PersistToken(ctx, db, row); err != nil {
return tokenError(c, 500, "server_error", "")
}
d.record(ctx, db, 200, "")
// RFC 8693 §2.2. No refresh_token: the token ends with the work it was for.
return c.JSON(200, map[string]any{
"access_token": access,
"issued_token_type": tokenTypeAccessToken,
"token_type": "Bearer",
"expires_in": int(ttl.Seconds()),
"scope": scope,
})
}
// actorProof verifies the actor_token: the client's OWN machine credential, as
// client_credentials or the workload grant minted it, alive. Never a person's
// token, another client's, or one that is itself acted for or confined. The
// answer is the `act` the delegated token carries, or why it was refused.
func actorProof(ctx context.Context, db orm.DB, c *zip.Ctx, client *schema.Application) (Actor, string) {
raw := param(c, "actor_token")
if raw == "" {
return Actor{}, "actor_token is required"
}
if t := param(c, "actor_token_type"); t != "" && t != subjectTokenTypeAccess && t != subjectTokenTypeJWTToken {
return Actor{}, "unsupported actor_token_type"
}
claims, err := verifyBearer(ctx, db, raw)
if err != nil {
return Actor{}, "actor_token is invalid or expired"
}
if claims.Type != schema.Program || claims.Azp != client.ClientId || claims.Subject != client.GetId() ||
claims.Act != nil || claims.Imp {
return Actor{}, "actor_token is not this client's own credential"
}
if row, err := store.GetTokenByAccessTokenHash(ctx, db, hashToken(raw)); err != nil || row == nil {
return Actor{}, "actor_token is invalid or expired"
}
return Actor{Sub: claims.Subject, Owner: client.Owner, Name: client.Name}, ""
}
// delegationCerts is every delegation key this IAM holds the row for: platform
// owned, a signing algorithm, never TLS. The newest signs; all of them verify,
// so a rotation adds a key before it signs and keeps it until what it signed has
// expired.
func delegationCerts(ctx context.Context, db orm.DB) ([]*schema.Cert, error) {
certs, err := store.ListCerts(ctx, db)
if err != nil {
return nil, err
}
out := certs[:0]
for _, c := range certs {
if c.Delegates() && policy.IsSigningOwner(c.Owner) && !strings.EqualFold(c.Type, "SSL") &&
signingAlgs[strings.ToUpper(strings.ReplaceAll(c.CryptoAlgorithm, "-", ""))] {
out = append(out, c)
}
}
return out, nil
}
// delegationSigner signs with the newest delegation key the deployment mounted.
// None mounted is ErrNoSigningCert: a delegation is refused rather than signed
// under a key the public JWKS carries.
func delegationSigner(ctx context.Context, db orm.DB, issuer string) (*Signer, error) {
certs, err := delegationCerts(ctx, db)
if err != nil {
return nil, err
}
var newest *schema.Cert
for _, c := range certs {
if c.PrivateKey != "" && (newest == nil || c.CreatedTime > newest.CreatedTime) {
newest = c
}
}
if newest == nil {
return nil, ErrNoSigningCert
}
return NewSignerFromCert(newest, nil, issuer)
}
// keyNotMounted is what a delegation and the delegation key address answer while
// this process holds no delegation key: 503, because the fault is the deployment's
// and passes when the key is mounted, and in these words, so the run that could
// not start says why.
const keyNotMounted = "delegation key not mounted"
// DelegationReady is the boot question for delegation: when IAM_DELEGATION_APPS
// names a client, this process signs delegated tokens, so a delegation key must be
// mounted HERE. nil when delegation is off or the key is there; otherwise an error
// naming the certificate it lacks and the directory its PEM goes in.
//
// It takes down DELEGATION, never identity. A missing delegation key costs coding
// runs — each refused with keyNotMounted, never handed anything else — and must not
// cost a single sign-in, so the boot reports it loudly (server.RequireSigning) and
// serves, and the two delegation addresses answer 503 until the key is mounted.
//
// How the key reaches the mount is the deployment's business; this asks only that
// it is there.
func DelegationReady(ctx context.Context, db orm.DB) error {
if strings.TrimSpace(os.Getenv("IAM_DELEGATION_APPS")) == "" {
return nil
}
certs, err := delegationCerts(ctx, db)
if err != nil {
return fmt.Errorf("delegation key: %w", err)
}
var keyless []string
for _, c := range certs {
if c.PrivateKey != "" {
return nil
}
keyless = append(keyless, c.Name)
}
if len(keyless) == 0 {
return fmt.Errorf("delegation key: IAM_DELEGATION_APPS is set and no certificate is declared with scope %q — "+
"declare cert-delegation (owner admin, scope %q) and mount its PEM as cert-delegation in the directory $%s names",
schema.CertDelegation, schema.CertDelegation, keyring.EnvDir)
}
return fmt.Errorf("delegation key: IAM_DELEGATION_APPS is set and no key is mounted for %s — "+
"mount its PEM, named %s, in the directory $%s names",
strings.Join(keyless, ", "), keyless[0], keyring.EnvDir)
}
// delegationKeysHandler serves the public half of every delegation key, as a
// JWKS, to a confidential client allowed to delegate — the one resource server
// that verifies what it is handed, reading with the credential it delegates with.
// To anyone else it answers as the token endpoint does: who are you, or not you.
//
// The key is not a secret; publishing it is the hazard. A verifier that fetches
// the public JWKS and trusts what verifies would admit a delegated token as the
// person. So it is not in that document, and this one is not an address a relying
// party is ever pointed at.
func delegationKeysHandler(db orm.DB) zip.Handler {
return func(c *zip.Ctx) error {
c.SetHeader("Cache-Control", "no-store")
ctx := c.Context()
id, secret := clientAuth(c)
if id == "" {
return tokenErrorClient(c, "client authentication required")
}
app, err := store.GetApplicationByClientId(ctx, db, id)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
if app == nil || app.ClientSecret == "" || !app.Proves(secret) {
return tokenErrorClient(c, "client authentication failed")
}
if !delegationAllowed(app) {
return tokenError(c, 403, "unauthorized_client", "client is not permitted to delegate")
}
certs, err := delegationCerts(ctx, db)
if err != nil {
return tokenError(c, 500, "server_error", "")
}
keys := make([]any, 0, len(certs))
for _, cert := range certs {
if jwk, err := certToJWK(cert); err == nil {
keys = append(keys, jwk)
}
}
if len(keys) == 0 {
return tokenError(c, 503, "temporarily_unavailable", keyNotMounted)
}
return c.JSON(200, map[string]any{"keys": keys})
}
}
// membership is the person's standing in org as their own token states it: the
// home org or a membership row (store.MemberOrgRefs), in an org that exists.
func membership(ctx context.Context, db orm.DB, user *schema.User, org string) (schema.OrgRef, bool, error) {
o, err := store.GetOrganizationByName(ctx, db, org)
if err != nil || o == nil {
return schema.OrgRef{}, false, err
}
for _, r := range store.MemberOrgRefs(ctx, db, user) {
if r.Org == org {
return r, true, nil
}
}
return schema.OrgRef{}, false, nil
}
// delegationAudience reports whether s is an API a delegated token may be
// addressed to: an https origin named, exactly, on IAM_DELEGATION_AUDIENCES —
// the API host that serves model calls (https://api.hanzo.ai). Unset, it names
// none and every delegation is refused.
//
// The allowed client chooses the person, the org and the lifetime; it does not
// choose which service the token is for. A token addressed to some other
// service's audience is the shape that service's own audience check admits.
func delegationAudience(s string) bool {
u, err := url.Parse(s)
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil ||
(u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" {
return false
}
return appInList("IAM_DELEGATION_AUDIENCES", s)
}
// delegation is one attempt's audit row: the person, the org asked for, the
// client that acts, the run, the lifetime granted and the answer.
type delegation struct {
client, subject, org, run, ip string
// filed is the org the row is filed under: the client's own until it is
// known to be allowed to name an org, then the org it named.
filed string
ttl time.Duration
}
// record writes the row. A failed write never fails the act; this is a record.
func (d delegation) record(ctx context.Context, db orm.DB, status int, why string) {
object, _ := json.Marshal(struct {
Actor string `json:"actor"`
Org string `json:"org,omitempty"`
Run string `json:"run,omitempty"`
TTL int `json:"ttl,omitempty"`
}{d.client, clip(d.org, 128), clip(d.run, 128), int(d.ttl / time.Second)})
store.Record(ctx, db, &schema.AuditLog{
Owner: d.filed,
Organization: d.filed,
User: clip(d.subject, 256),
ClientIp: d.ip,
Method: "POST",
RequestUri: PathToken,
Action: schema.ActionDelegate,
Object: string(object),
Response: why,
StatusCode: status,
})
}