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

198 lines
5.9 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package oidc
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"github.com/hanzoai/orm"
"github.com/zap-proto/zip"
"github.com/hanzoai/iam/internal/keyring"
"github.com/hanzoai/iam/pkg/schema"
"github.com/hanzoai/iam/internal/testhttp"
)
// HTTP-level test harness: register the whole OIDC surface on a fresh store and
// drive it through the real router (app.Fiber().Test), so every test exercises
// the HTTP contract a client sees — status codes, headers, redirects, bodies.
// sharedKey is one RSA key reused across tests (keygen is the slow part; the
// crypto under test is identical regardless of which key it is).
var (
sharedKeyOnce sync.Once
sharedKeyVal *rsa.PrivateKey
)
func sharedKey(t *testing.T) *rsa.PrivateKey {
t.Helper()
sharedKeyOnce.Do(func() {
k, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
sharedKeyVal = k
})
return sharedKeyVal
}
// appOpts configures a seeded OAuth application.
type appOpts struct {
clientID string
secret string // "" → public (PKCE) client
redirectURIs []string
refreshHours float64
shared bool // IsShared → accepts users from any org
signup bool // EnableSignUp → the app allows new-account creation
codeSignin bool // EnableCodeSignin → the app allows sign-in by emailed/texted code
orgChoice string // OrgChoiceMode → "" none, "create" = self-serve org creation
grants []string // declared OAuth grants; a grant absent here is refused
}
// tctx is the background context used by the test seed helpers.
func tctx() context.Context { return context.Background() }
// newServer registers the full OIDC surface on a fresh SQLite store.
func newServer(t *testing.T) (*zip.App, orm.DB) {
t.Helper()
db := openTestDB(t)
app := zip.New(zip.Config{AppName: "iam-test", DisableStartupMessage: true})
// The whole OIDC surface is the pre-authentication PUBLIC group; a root
// (empty-prefix) router registers it at its absolute paths, no Guard.
Route(app.Group(""), db)
return app, db
}
// seedRSACert creates a named RS256 signing cert holding the shared key.
func seedRSACert(t *testing.T, db orm.DB, name string) {
t.Helper()
c := orm.New[schema.Cert](db)
c.Owner = "admin"
c.Name = name
c.CryptoAlgorithm = "RS256"
keyring.Set(name, rsaKeyToPEM(t, sharedKey(t))) // deployment-supplied; the row never carries it
c.SetId("admin/" + name)
if err := c.CreateCtx(context.Background()); err != nil {
t.Fatalf("seed cert: %v", err)
}
}
// seedApp creates an application (org "hanzo") with the given options and a
// shared RS256 cert.
func seedApp(t *testing.T, db orm.DB, o appOpts) *schema.Application {
t.Helper()
seedRSACert(t, db, "cert-"+o.clientID)
a := orm.New[schema.Application](db)
a.Owner = "admin"
a.Name = o.clientID
a.ClientId = o.clientID
a.ClientSecret = o.secret
a.Organization = "hanzo"
a.Cert = "cert-" + o.clientID
a.EnablePassword = true
a.EnableSignUp = o.signup
a.EnableCodeSignin = o.codeSignin
a.ExpireInHours = 1
a.RefreshExpireInHours = o.refreshHours
a.RedirectUris = o.redirectURIs
a.IsShared = o.shared
a.OrgChoiceMode = o.orgChoice
a.GrantTypes = o.grants
a.SetId("admin/" + o.clientID)
if err := a.CreateCtx(context.Background()); err != nil {
t.Fatalf("seed app: %v", err)
}
return a
}
// --- HTTP helpers ---
func formReq(method, path string, form url.Values) *http.Request {
req := httptest.NewRequest(method, path, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Host = "hanzo.id"
return req
}
func formReqNoBody(method, path string) *http.Request {
req := httptest.NewRequest(method, path, nil)
req.Host = "hanzo.id"
return req
}
func jsonReq(method, path string, body any) *http.Request {
b, _ := json.Marshal(body)
req := httptest.NewRequest(method, path, bytes.NewReader(b))
req.Header.Set("Content-Type", "application/json")
req.Host = "hanzo.id"
return req
}
// fromPage marks req as a browser marks a request the issuer's own page makes:
// same-origin fetch metadata, which sessions.Forgeable requires before the session
// cookie may authorize a write.
func fromPage(req *http.Request) *http.Request {
req.Header.Set("Sec-Fetch-Site", "same-origin")
return req
}
// navigate marks req as a top-level browser navigation another site sent the
// browser on — a relying party's sign-out link.
func navigate(req *http.Request) *http.Request {
req.Header.Set("Sec-Fetch-Site", "cross-site")
req.Header.Set("Sec-Fetch-Mode", "navigate")
req.Header.Set("Sec-Fetch-Dest", "document")
return req
}
func do(t *testing.T, app *zip.App, req *http.Request) (*http.Response, []byte) {
t.Helper()
resp, err := testhttp.Do(app, req)
if err != nil {
t.Fatalf("test request %s %s: %v", req.Method, req.URL.Path, err)
}
body, _ := io.ReadAll(resp.Body)
return resp, body
}
func decode(t *testing.T, body []byte) map[string]any {
t.Helper()
var m map[string]any
if err := json.Unmarshal(body, &m); err != nil {
t.Fatalf("decode json %q: %v", string(body), err)
}
return m
}
// loginForCode drives POST /v1/iam/login (type=code) and returns the minted
// authorization code from the Response envelope.
func loginForCode(t *testing.T, app *zip.App, f map[string]string) (string, *http.Response, []byte) {
t.Helper()
f["type"] = "code"
resp, body := do(t, app, jsonReq("POST", PathLogin, f))
m := decode(t, body)
code, _ := m["data"].(string)
return code, resp, body
}
// exchangeCode drives POST /v1/iam/oauth/token for the authorization_code grant.
func exchangeCode(t *testing.T, app *zip.App, form url.Values) (*http.Response, map[string]any) {
t.Helper()
form.Set("grant_type", "authorization_code")
resp, body := do(t, app, formReq("POST", PathToken, form))
return resp, decode(t, body)
}