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

179 lines
5.7 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package oidc
import (
"context"
"crypto/rsa"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/hanzoai/orm"
ormdb "github.com/hanzoai/orm/db"
"github.com/hanzoai/iam/internal/keyring"
"github.com/hanzoai/iam/pkg/pkce"
"github.com/hanzoai/iam/pkg/schema"
"github.com/hanzoai/iam/pkg/store"
)
// openTestDB opens a fresh SQLite store; the schema init registers the kinds.
func openTestDB(t *testing.T) orm.DB {
t.Helper()
_ = schema.Kinds() // force the schema package init() (kind registration)
if addr := os.Getenv("IAM_SQL_ADDR"); addr != "" {
return sqlScratchDB(t, strings.TrimPrefix(addr, "sql://"))
}
dir := t.TempDir()
db, err := orm.OpenSQLite(&ormdb.SQLiteDBConfig{
Path: filepath.Join(dir, "iamtest.db"),
Config: ormdb.SQLiteConfig{BusyTimeout: 5000, JournalMode: "WAL"},
})
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
t.Cleanup(func() { _ = db.Close() })
return db
}
// seedAppWithCert creates a confidential app (hanzo-console) + its RSA cert.
func seedAppWithCert(t *testing.T, db orm.DB, key *rsa.PrivateKey) *schema.Application {
t.Helper()
ctx := context.Background()
// Cert row: identity only. The PEM is deployment-supplied, held in memory.
c := orm.New[schema.Cert](db)
c.Owner = "admin"
c.Name = "cert-hanzo"
c.CryptoAlgorithm = "RS256"
keyring.Set(c.Name, rsaKeyToPEM(t, key))
c.SetId("admin/cert-hanzo")
if err := c.CreateCtx(ctx); err != nil {
t.Fatalf("seed cert: %v", err)
}
a := orm.New[schema.Application](db)
a.Owner = "admin"
a.Name = "hanzo-console"
a.ClientId = "hanzo-console"
a.ClientSecret = "" // public client (PKCE) for this test
a.Organization = "hanzo"
a.Cert = "cert-hanzo"
a.EnablePassword = true
a.ExpireInHours = 1
a.SetId("admin/hanzo-console")
if err := a.CreateCtx(ctx); err != nil {
t.Fatalf("seed app: %v", err)
}
return a
}
// TestTokenExchange_EndToEnd mints an authorization code (authorize side),
// persists it, then redeems it through the exchange path and verifies the signed
// JWT. Proves the full code→token flow over a real store, and that replay fails.
func TestTokenExchange_EndToEnd(t *testing.T) {
db := openTestDB(t)
key := mustGenRSA(t)
app := seedAppWithCert(t, db, key)
ctx := context.Background()
now := time.Unix(1_800_000_000, 0)
// The code below is minted for hanzo/alice, so hanzo/alice must EXIST. This
// fixture used to omit her and still get a signed token, because a subject that
// resolved to no user row was minted as a bare `sub` with every other claim
// empty. That is the defect userClaims now refuses: nameless is not "unknown
// profile", it is a credential account.Payer reads as "not a person" and bills
// to the signup org's own balance. Seeding her makes this exercise the real
// resolution (identityOf) rather than the fallback that replaced it.
alice := orm.New[schema.User](db)
alice.Owner = "hanzo"
alice.Name = "alice"
alice.SetId("hanzo/alice")
if err := alice.CreateCtx(ctx); err != nil {
t.Fatalf("seed hanzo/alice: %v", err)
}
// --- authorize side: mint a PKCE-bound code and persist it ---
verifier := "e2e-verifier-000000000000000000000000000000000000"
code, err := MintCode(app, "hanzo/alice", "openid profile", pkce.Challenge(verifier), "S256", "", now)
if err != nil {
t.Fatal(err)
}
if err := store.PersistToken(ctx, db, code); err != nil {
t.Fatalf("persist code: %v", err)
}
// --- token side: redeem via the same guards the handler uses ---
got, err := store.GetTokenByCode(ctx, db, code.Code)
if err != nil || got == nil {
t.Fatalf("get by code: %v (nil=%v)", err, got == nil)
}
if err := RedeemCode(got, app.Name, verifier, now.Add(time.Second)); err != nil {
t.Fatalf("redeem: %v", err)
}
ttl := appTTL(app)
if err := IssueAccessToken(got, int(ttl.Seconds()), now); err != nil {
t.Fatal(err)
}
signed, err := signAccessToken(ctx, db, app, got, "https://iam.hanzo.ai", ttl, now)
if err != nil {
t.Fatalf("sign: %v", err)
}
if err := store.SaveToken(ctx, db, got); err != nil {
t.Fatalf("save: %v", err)
}
// The signed JWT verifies under the cert key with the right claims.
var claims Claims
pub := &key.PublicKey
parsed, err := jwt.ParseWithClaims(signed, &claims, func(*jwt.Token) (any, error) { return pub, nil },
jwt.WithValidMethods([]string{"RS256"}), jwt.WithTimeFunc(func() time.Time { return now.Add(time.Minute) }))
if err != nil || !parsed.Valid {
t.Fatalf("verify signed token: %v", err)
}
if claims.Subject != "hanzo/alice" || claims.Owner != "hanzo" ||
len(claims.Audience) != 1 || claims.Audience[0] != "hanzo-console" {
t.Fatalf("claims wrong: sub=%q owner=%q aud=%v", claims.Subject, claims.Owner, claims.Audience)
}
// --- replay: the persisted code is now used; a second redeem fails ---
again, _ := store.GetTokenByCode(ctx, db, code.Code)
if err := RedeemCode(again, app.Name, verifier, now.Add(2*time.Second)); err != ErrCodeUsed {
t.Fatalf("replay after persist: got %v, want ErrCodeUsed", err)
}
}
// --- helpers ---
func mustGenRSA(t *testing.T) *rsa.PrivateKey {
t.Helper()
k, err := rsaGenTest()
if err != nil {
t.Fatal(err)
}
return k
}
// TestMain boots the package the way a server boots (server.RequireIssuer): the
// issuer is https://hanzo.id and no host signs in anywhere else. A test that
// needs other issuers installs them for itself and restores these.
func TestMain(m *testing.M) {
os.Setenv("IAM_ISSUER", "https://hanzo.id")
for _, k := range []string{"IAM_ISSUER_MAP", "IAM_FEDERATION_ORIGIN_MAP", "IAM_FEDERATION_ORIGIN", "IAM_DEV_HOST_RELATIVE"} {
os.Unsetenv(k)
}
if err := InitIssuerResolver(); err != nil {
panic(err)
}
if err := InitFederationResolver(); err != nil {
panic(err)
}
os.Exit(m.Run())
}