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

243 lines
9.9 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package oidc
import (
"errors"
"net/http"
"strings"
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/sessions"
"github.com/hanzoai/iam/pkg/schema"
)
// POST /v1/iam/onboard — org onboarding. A signed-in person creates an org (named,
// or a one-click `<username>` personal org) and owns it by membership. Their own
// account is not touched: who they are and how they sign in are the same before and
// after, and they reach the org through the signed `orgs` claim of their next token
// and the org switch. The org IS a billing account, so the same call provisions its
// ONE org-scoped API key, held by the founder.
//
// Idempotent + retry-safe: the whole converge (org + owner + key) runs through the
// provision() primitive, which ensures each resource atomically — a retry or a
// partial failure re-drives to the SAME org + owner + key, never a duplicate.
//
// The response is the console's own {org}/{error} contract (NOT the casibase
// envelope): {"org":"<slug>", ...key} on success, an {"error":"..."} with a 4xx/5xx
// status on failure — the OrgOnboarding client reads json.org / json.error directly.
// On the FIRST provision the response also carries the key's secret (shown once);
// an idempotent replay returns the publishable accessKey without re-revealing it.
//
// Self-scoped: the caller is resolved from its session/bearer (callerOf), never from
// the body, so onboarding only ever moves the caller — its own identity, its own org.
// PathOnboard is the canonical first-run onboarding endpoint.
const PathOnboard = "/v1/iam/onboard"
// Org slug bounds are the organization-name bound internal/organizations holds
// every org to (2 to 55 characters), so an org founded here is one every org
// surface accepts.
const (
minOrgSlug = 2
maxOrgSlug = 55
)
// The names a customer org may never take are ONE list, policy.IsHeldOrg: the
// system owners (admin/built-in are signing-cert owners, app owns system
// principals, and admin is the SuperAdmin org), the brands, the orgs funded by
// name, and the estate's own namespaces. Onboarding, provisioning, the seed and
// cloud all read it, so the set cannot drift between surfaces.
// onboardForm is the request body: a name for the org, and whether the org is the
// caller's OWN. Neither implies the other — a name with no `personal` founds a
// shared org, `personal` with no name founds the one-click `<username>` one, and
// both together found a named org that belongs to the caller.
type onboardForm struct {
Name string `json:"name"`
Personal bool `json:"personal"`
}
// onboardHandler finishes setting up the account of whoever is calling — it
// creates their organization if they have none and puts them in it, so a person
// who has just signed up lands somewhere they can work.
//
// It always acts on the caller and never on somebody named in the request, so
// there is no way to onboard another person's account through it.
func onboardHandler(db orm.DB) zip.Handler {
return func(c *zip.Ctx) error {
owner, name, err := callerOf(c.Context(), c, db)
if errors.Is(err, sessions.ErrForgeable) {
return onboardErr(c, http.StatusForbidden, err.Error())
}
if err != nil {
return onboardErr(c, 401, "please sign in first")
}
var f onboardForm
_ = c.Bind(&f)
// The slug resolves the ONE way it resolves on the service-token path: the
// name the caller GAVE wins, and the one-click <username> is derived only
// when they gave none.
//
// `personal` then rides through whichever of the two named the org. It says
// WHOSE the org is, not how it got its name — so a person may name their own
// org and still own it. Reading it as "derive the slug" made the two
// inseparable: naming an org forced it to belong to nobody in particular, and
// owning one forced it to be called <username>.
slug, display := slugifyOrg(f.Name), strings.TrimSpace(f.Name)
if slug == "" && f.Personal {
slug, display = personalOrgSlug(name), name
}
// provisionAndRespond validates the slug (length + policy.IsReservedOrg) and
// drives the ONE atomic provision — org + owner membership + hashed metered
// credential — with no orphan on a mid-flight fault, resumable via the
// Founder stamp.
return provisionAndRespond(c, db, owner, name, slug, display, f.Personal)
}
}
// PathProvision is the service-token admin provisioning endpoint: the ONE atomic
// op a platform service drives on behalf of a named user, so it converges to one
// org + owner + credential exactly like the self-service endpoint, with no
// partial-failure orphan between two calls.
const PathProvision = "/v1/iam/admin/provision"
// provisionForm is the service-token provision body: the target identity to
// provision (owner, name) and the org to land it in. orgSlug is the ALREADY-RESOLVED
// slug the caller chose (it owns its own uniqueness policy — e.g. cloud's numeric
// auto-suffix — so provision honors it verbatim rather than re-deriving); personal
// marks it a personal org (and, absent an explicit orgSlug, derives <username>).
type provisionForm struct {
Owner string `json:"owner"`
Name string `json:"name"`
OrgSlug string `json:"orgSlug"`
Personal bool `json:"personal"`
}
// provisionServiceHandler founds an org on someone's behalf — the same onboarding
// a person gets themselves, driven by one of your own services instead of by
// them. The person keeps their account and owns the org by membership.
//
// It authenticates as your service rather than as a person, which is why the
// person to provision is named in the request. The setup it performs is
// identical to self-service onboarding; there is one provisioning path, not
// two that can drift.
func provisionServiceHandler(db orm.DB) zip.Handler {
return func(c *zip.Ctx) error {
if !httpx.ServiceTokenAuth(c) {
return c.JSON(401, map[string]string{"error": "a valid service token is required"})
}
var f provisionForm
if err := c.Bind(&f); err != nil {
return onboardErr(c, 400, "invalid request body")
}
owner, name := strings.TrimSpace(f.Owner), strings.TrimSpace(f.Name)
if owner == "" || name == "" {
return onboardErr(c, 400, "owner and name are required")
}
// Honor the caller's resolved slug verbatim; fall back to the derived personal
// slug only when the caller supplied none.
slug, display := slugifyOrg(f.OrgSlug), strings.TrimSpace(f.OrgSlug)
if slug == "" && f.Personal {
slug, display = personalOrgSlug(name), name
}
return provisionAndRespond(c, db, owner, name, slug, display, f.Personal)
}
}
// provisionAndRespond drives the idempotent provision() converge for an
// already-resolved (slug, display, personal) and renders the {org, accessKey,
// accessSecret?}/{error} contract. Shared by the self-service onboard (caller from
// session) and the service-token admin provision (caller from body) so both paths
// behave identically once the slug is resolved.
func provisionAndRespond(c *zip.Ctx, db orm.DB, owner, name, slug, display string, personal bool) error {
if len(slug) < minOrgSlug {
return onboardErr(c, 400, "use at least 2 letters or numbers")
}
if policy.IsHeldOrg(slug) {
return onboardErr(c, 400, "\""+slug+"\" is reserved. choose a different name")
}
display, err := schema.OrgDisplayName(display)
if err != nil {
return onboardErr(c, 400, err.Error())
}
if display == "" {
display = slug
}
out, err := provision(c.Context(), db, claim{
owner: owner, name: name,
slug: slug, display: display, personal: personal,
})
if err != nil {
if ft, ok := err.(*fault); ok {
return onboardErr(c, ft.status, ft.msg)
}
return onboardErr(c, 500, "server_error")
}
// A converge that MOVED the caller re-keys the identity, so the session cookie
// the browser is holding names a user that no longer exists, and the very next
// request would read as signed OUT. Carry the live session across to the new key
// (a no-op on the bearer path, whose subject is a stable UUID the re-key does not
// touch). Onboarding moves nobody, so it has nothing to carry.
if out.movedFrom != "" && out.movedFrom != out.org {
sessions.Rekey(c.Context(), c.Fiber(), db, out.org)
}
resp := map[string]any{"org": out.org, "accessKey": out.accessKey}
if out.accessSecret != "" {
resp["accessSecret"] = out.accessSecret
}
return c.JSON(200, resp)
}
// onboardErr writes the console's {"error":...} shape with an HTTP status the
// client treats as failure (res.ok=false), never the casibase 200 envelope.
func onboardErr(c *zip.Ctx, status int, msg string) error {
return c.JSON(status, map[string]string{"error": msg})
}
// slugifyOrg normalizes a human org name into an IAM slug — lowercase ASCII
// alphanumerics, every other run collapsed to a single '-', trimmed, capped at
// maxOrgSlug. Mirrors the console's slugifyOrg for ASCII (the common case); a
// non-ASCII rune becomes '-' rather than its NFKD base letter (no stdlib NFKD), so
// an accented name yields a valid but possibly different slug than the client preview
// — the server slug is authoritative and get-account reports the real org.
func slugifyOrg(input string) string {
var b strings.Builder
dash := false
for _, r := range strings.ToLower(input) {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
b.WriteRune(r)
dash = false
continue
}
if !dash {
b.WriteByte('-')
dash = true
}
}
s := strings.Trim(b.String(), "-")
if len(s) > maxOrgSlug {
s = s[:maxOrgSlug]
}
return strings.TrimRight(s, "-")
}
// personalOrgSlug is the default one-click org slug for a user: the local part of an
// email-like username ([email protected] → dave), slugified — so a personal org reads as the
// person, not their address. Mirrors the console's personalOrgSlug.
func personalOrgSlug(username string) string {
base := username
if i := strings.IndexByte(username, '@'); i > 0 {
base = username[:i]
}
return slugifyOrg(base)
}