mirror of
https://github.com/hanzoai/iam.git
synced 2026-11-19 18:37:16 +00:00
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]>
402 lines
17 KiB
Go
402 lines
17 KiB
Go
// Copyright 2026 Hanzo AI, Inc.
|
|
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
|
|
package oidc
|
|
|
|
import (
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/hanzoai/iam/pkg/pkce"
|
|
)
|
|
|
|
const testRedirect = "https://app.example/callback"
|
|
|
|
func authorizeURL(q url.Values) string {
|
|
return PathAuthorize + "?" + q.Encode()
|
|
}
|
|
|
|
// The authorize endpoint validates the client and redirect_uri BEFORE it will
|
|
// redirect anywhere: an unknown client or an unregistered redirect_uri is
|
|
// answered in place (never bounced), closing the open-redirect surface.
|
|
func TestAuthorize_RefusesToRedirectOnBadClientOrRedirect(t *testing.T) {
|
|
app, db := newServer(t)
|
|
seedApp(t, db, appOpts{clientID: "pub", redirectURIs: []string{testRedirect}})
|
|
|
|
cases := []struct {
|
|
name string
|
|
q url.Values
|
|
}{
|
|
{"missing client_id", url.Values{"response_type": {"code"}, "redirect_uri": {testRedirect}}},
|
|
{"unknown client_id", url.Values{"response_type": {"code"}, "client_id": {"ghost"}, "redirect_uri": {testRedirect}}},
|
|
{"missing redirect_uri", url.Values{"response_type": {"code"}, "client_id": {"pub"}}},
|
|
{"unregistered redirect_uri", url.Values{"response_type": {"code"}, "client_id": {"pub"}, "redirect_uri": {"https://evil.example/steal"}}},
|
|
{"redirect near-match", url.Values{"response_type": {"code"}, "client_id": {"pub"}, "redirect_uri": {testRedirect + "/.."}}},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
resp, _ := do(t, app, formReqNoBody("GET", authorizeURL(tc.q)))
|
|
if resp.StatusCode != 400 {
|
|
t.Fatalf("status = %d, want 400", resp.StatusCode)
|
|
}
|
|
if loc := resp.Header.Get("Location"); loc != "" {
|
|
t.Fatalf("must NOT redirect on bad client/redirect; got Location %q", loc)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// Once the client + redirect_uri are validated, a protocol error bounces back to
|
|
// the (trusted) redirect_uri with error + state.
|
|
func TestAuthorize_ProtocolErrorRedirectsToClient(t *testing.T) {
|
|
app, db := newServer(t)
|
|
seedApp(t, db, appOpts{clientID: "pub", redirectURIs: []string{testRedirect}})
|
|
|
|
t.Run("unsupported response_type", func(t *testing.T) {
|
|
q := url.Values{"response_type": {"token"}, "client_id": {"pub"}, "redirect_uri": {testRedirect}, "state": {"xyz"}, "code_challenge": {"abc"}}
|
|
resp, _ := do(t, app, formReqNoBody("GET", authorizeURL(q)))
|
|
loc := requireRedirect(t, resp, testRedirect)
|
|
if !strings.Contains(loc, "error=unsupported_response_type") || !strings.Contains(loc, "state=xyz") {
|
|
t.Fatalf("Location = %q", loc)
|
|
}
|
|
})
|
|
|
|
t.Run("public client without PKCE", func(t *testing.T) {
|
|
q := url.Values{"response_type": {"code"}, "client_id": {"pub"}, "redirect_uri": {testRedirect}, "state": {"s1"}}
|
|
resp, _ := do(t, app, formReqNoBody("GET", authorizeURL(q)))
|
|
loc := requireRedirect(t, resp, testRedirect)
|
|
if !strings.Contains(loc, "error=invalid_request") {
|
|
t.Fatalf("public client without PKCE should error; Location = %q", loc)
|
|
}
|
|
})
|
|
|
|
t.Run("plain PKCE rejected", func(t *testing.T) {
|
|
q := url.Values{"response_type": {"code"}, "client_id": {"pub"}, "redirect_uri": {testRedirect}, "code_challenge": {"abc"}, "code_challenge_method": {"plain"}}
|
|
resp, _ := do(t, app, formReqNoBody("GET", authorizeURL(q)))
|
|
loc := requireRedirect(t, resp, testRedirect)
|
|
if !strings.Contains(loc, "error=invalid_request") {
|
|
t.Fatalf("plain PKCE should be rejected; Location = %q", loc)
|
|
}
|
|
})
|
|
}
|
|
|
|
// A well-formed request is delegated to the hosted login with the (re-encoded)
|
|
// request preserved.
|
|
func TestAuthorize_DelegatesValidRequest(t *testing.T) {
|
|
app, db := newServer(t)
|
|
seedApp(t, db, appOpts{clientID: "pub", redirectURIs: []string{testRedirect}})
|
|
|
|
challenge := pkce.Challenge("verifier-abcdefghijklmnopqrstuvwxyz-012345")
|
|
q := url.Values{
|
|
"response_type": {"code"},
|
|
"client_id": {"pub"},
|
|
"redirect_uri": {testRedirect},
|
|
"scope": {"openid profile"},
|
|
"state": {"state-1"},
|
|
"nonce": {"nonce-1"},
|
|
"code_challenge": {challenge},
|
|
}
|
|
resp, _ := do(t, app, formReqNoBody("GET", authorizeURL(q)))
|
|
if resp.StatusCode != 302 {
|
|
t.Fatalf("status = %d, want 302", resp.StatusCode)
|
|
}
|
|
loc := resp.Header.Get("Location")
|
|
if !strings.HasPrefix(loc, hostedLoginPath+"?") {
|
|
t.Fatalf("Location = %q, want hosted-login delegate", loc)
|
|
}
|
|
forwarded, err := url.Parse(loc)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
fq := forwarded.Query()
|
|
if fq.Get("client_id") != "pub" || fq.Get("redirect_uri") != testRedirect ||
|
|
fq.Get("code_challenge") != challenge || fq.Get("code_challenge_method") != "S256" ||
|
|
fq.Get("state") != "state-1" || fq.Get("nonce") != "nonce-1" {
|
|
t.Fatalf("delegated query missing/incorrect: %v", fq)
|
|
}
|
|
}
|
|
|
|
// A sign-in must run AT its brand's pinned issuer: the __Host-hanzo_fed browser
|
|
// binding and the session are host-only cookies, while the IdP callback and
|
|
// `iss` live at the issuer. An authorize served on an alias host (iam.hanzo.ai
|
|
// folding into hanzo.id) is therefore answered with the SAME request relocated
|
|
// to the issuer — 307, query intact, before anything is minted or set. Measured
|
|
// live before this hop: a begin on iam.hanzo.ai set the cookie there and
|
|
// registered the Google callback at hanzo.id, so every social sign-in on the
|
|
// alias failed closed at the callback with "the federation session could not
|
|
// be verified".
|
|
func TestAuthorize_AliasHostRelocatesToIssuer(t *testing.T) {
|
|
app, db := newServer(t)
|
|
seedApp(t, db, appOpts{clientID: "pub", redirectURIs: []string{testRedirect}})
|
|
installIssuerResolver(t, "https://hanzo.id", testIssuerMap)
|
|
|
|
q := url.Values{
|
|
"response_type": {"code"},
|
|
"client_id": {"pub"},
|
|
"redirect_uri": {testRedirect},
|
|
"state": {"s-alias"},
|
|
"code_challenge": {pkce.Challenge("verifier-abcdefghijklmnopqrstuvwxyz-012345")},
|
|
"provider": {"provider-google"},
|
|
}
|
|
target := authorizeURL(q)
|
|
|
|
t.Run("alias relocates, method kept, nothing set", func(t *testing.T) {
|
|
// Every alias, not one: api.hanzo.ai is the host `hanzo auth login`
|
|
// opens, and when it is missing from the map nothing relocates — the
|
|
// hosted-login redirect is relative, so it resolves on api.hanzo.ai,
|
|
// where the Cloud Console answers with its own "No such page" and a 200.
|
|
// The sign-in ends looking like a broken link, having reported success
|
|
// at every hop.
|
|
for _, alias := range hanzoAliases {
|
|
for _, method := range []string{"GET", "POST"} {
|
|
req := formReqNoBody(method, target)
|
|
req.Host = alias
|
|
resp, _ := do(t, app, req)
|
|
if resp.StatusCode != 307 {
|
|
t.Fatalf("%s status = %d, want 307", method, resp.StatusCode)
|
|
}
|
|
if loc := resp.Header.Get("Location"); loc != "https://hanzo.id"+target {
|
|
t.Fatalf("%s on %s: Location = %q, want %q", method, alias, loc, "https://hanzo.id"+target)
|
|
}
|
|
// Relocation precedes every mint: a cookie set here would be the
|
|
// stranded-cookie bug this hop exists to close.
|
|
if sc := resp.Header.Get("Set-Cookie"); sc != "" {
|
|
t.Fatalf("%s relocation must set nothing; Set-Cookie = %q", method, sc)
|
|
}
|
|
}
|
|
}
|
|
})
|
|
|
|
t.Run("issuer host is terminal", func(t *testing.T) {
|
|
req := formReqNoBody("GET", target)
|
|
req.Host = "hanzo.id"
|
|
resp, _ := do(t, app, req)
|
|
if resp.StatusCode == 307 {
|
|
t.Fatalf("issuer host must not relocate; got 307 to %q", resp.Header.Get("Location"))
|
|
}
|
|
})
|
|
|
|
t.Run("unknown host folds to the default issuer", func(t *testing.T) {
|
|
req := formReqNoBody("GET", target)
|
|
req.Host = "www.zoolabs.id" // deliberately absent from testIssuerMap
|
|
resp, _ := do(t, app, req)
|
|
if resp.StatusCode != 307 {
|
|
t.Fatalf("status = %d, want 307", resp.StatusCode)
|
|
}
|
|
if loc := resp.Header.Get("Location"); loc != "https://hanzo.id"+target {
|
|
t.Fatalf("Location = %q, want fold to the default issuer", loc)
|
|
}
|
|
})
|
|
|
|
t.Run("a non-idempotent map must not steer", func(t *testing.T) {
|
|
installIssuerResolver(t, "https://a.example",
|
|
`{"x.example":"https://a.example","a.example":"https://b.example"}`)
|
|
req := formReqNoBody("GET", target)
|
|
req.Host = "x.example"
|
|
resp, _ := do(t, app, req)
|
|
if resp.StatusCode == 307 {
|
|
t.Fatalf("ping-pong map must serve in place; got 307 to %q", resp.Header.Get("Location"))
|
|
}
|
|
})
|
|
}
|
|
|
|
// A host that is its own sign-in origin is answered IN PLACE, and a host folded
|
|
// onto it is relocated to it — while every host the map does not name relocates
|
|
// to its issuer exactly as before. The issuer is not what decides where a
|
|
// browser signs in; the sign-in origin is.
|
|
func TestAuthorize_SigninOriginDecidesTheRelocation(t *testing.T) {
|
|
app, db := newServer(t)
|
|
seedApp(t, db, appOpts{clientID: "pub", redirectURIs: []string{testRedirect}})
|
|
installIssuerResolver(t, "https://hanzo.id", testIssuerMap)
|
|
installFederationResolver(t, `{"hanzo.ai":"https://hanzo.ai","www.hanzo.ai":"https://hanzo.ai"}`)
|
|
|
|
q := url.Values{
|
|
"response_type": {"code"},
|
|
"client_id": {"pub"},
|
|
"redirect_uri": {testRedirect},
|
|
"state": {"s-signin"},
|
|
"code_challenge": {pkce.Challenge("verifier-abcdefghijklmnopqrstuvwxyz-012345")},
|
|
}
|
|
target := authorizeURL(q)
|
|
for host, want := range map[string]string{
|
|
"hanzo.ai": "", // its own origin: answered here
|
|
"HANZO.AI:443": "", // the same address
|
|
"www.hanzo.ai": "https://hanzo.ai" + target, // folded onto hanzo.ai
|
|
"hanzo.ai.": "https://hanzo.ai" + target, // another host to a cookie jar
|
|
"iam.hanzo.ai": "https://hanzo.id" + target, // unnamed: its issuer, as before
|
|
"hanzo.id": "",
|
|
} {
|
|
req := formReqNoBody("GET", target)
|
|
req.Host = host
|
|
resp, _ := do(t, app, req)
|
|
if want == "" {
|
|
// Answered here means the hosted login, on this host: relative, so it
|
|
// resolves to hanzo.ai's own page on hanzo.ai and hanzo.id's on hanzo.id.
|
|
if loc := resp.Header.Get("Location"); resp.StatusCode != 302 || !strings.HasPrefix(loc, hostedLoginPath+"?") {
|
|
t.Errorf("%s: %d to %q, want 302 to its own %s", host, resp.StatusCode, loc, hostedLoginPath)
|
|
}
|
|
continue
|
|
}
|
|
if resp.StatusCode != 307 || resp.Header.Get("Location") != want {
|
|
t.Errorf("%s: %d to %q, want 307 to %q", host, resp.StatusCode, resp.Header.Get("Location"), want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// A sign-in origin that is not its issuer's host holds a session of its own, which
|
|
// the issuer's sign-out does not end. So authorize there never answers silently
|
|
// from it: the page asks, and prompt=none, which allows no page, is login_required.
|
|
// At the issuer the same session answers as it always has.
|
|
func TestAuthorize_NoSilentGrantAtADelegatedSigninOrigin(t *testing.T) {
|
|
app, db := newServer(t)
|
|
twoApps(t, db)
|
|
installIssuerResolver(t, "https://hanzo.id", testIssuerMap)
|
|
installFederationResolver(t, `{"hanzo.ai":"https://hanzo.ai"}`)
|
|
cookie := signIn(t, app, "portal")
|
|
|
|
ask := func(host string, q url.Values) *http.Response {
|
|
req := formReqNoBody("GET", authorizeURL(q))
|
|
req.Host = host
|
|
req.Header.Set("Cookie", cookie)
|
|
req.Header.Set("Sec-Fetch-Mode", "navigate")
|
|
req.Header.Set("Sec-Fetch-Site", "cross-site")
|
|
req.Header.Set("Sec-Fetch-Dest", "document")
|
|
resp, _ := do(t, app, req)
|
|
return resp
|
|
}
|
|
verifier := "verifier-second-app-0123456789012345678901234567890123"
|
|
|
|
// The issuer's own host answers from the session, straight to the callback.
|
|
if loc := requireRedirect(t, ask("hanzo.id", silentQuery(verifier)), secondRedirect); !strings.Contains(loc, "code=") {
|
|
t.Fatalf("hanzo.id should answer from its session; got %q", loc)
|
|
}
|
|
// hanzo.ai asks first: its own hosted page, no code.
|
|
resp := ask("hanzo.ai", silentQuery(verifier))
|
|
if loc := resp.Header.Get("Location"); resp.StatusCode != 302 || !strings.HasPrefix(loc, hostedLoginPath+"?") || strings.Contains(loc, "code=") {
|
|
t.Fatalf("hanzo.ai must ask before minting; %d to %q", resp.StatusCode, loc)
|
|
}
|
|
// prompt=none there is refused, to the client.
|
|
q := silentQuery(verifier)
|
|
q.Set("prompt", "none")
|
|
loc := requireRedirect(t, ask("hanzo.ai", q), secondRedirect)
|
|
if !strings.Contains(loc, "error=login_required") || strings.Contains(loc, "code=") {
|
|
t.Fatalf("prompt=none on hanzo.ai = %q, want error=login_required and no code", loc)
|
|
}
|
|
}
|
|
|
|
// A sign-in origin that would send the request on again is never steered to,
|
|
// even when such a resolver is installed past the boot check.
|
|
func TestAuthorize_NonTerminalSigninOriginServesInPlace(t *testing.T) {
|
|
app, db := newServer(t)
|
|
seedApp(t, db, appOpts{clientID: "pub", redirectURIs: []string{testRedirect}})
|
|
installIssuerResolver(t, "https://hanzo.id", testIssuerMap)
|
|
installFederationResolver(t, `{"a.example":"https://b.example","b.example":"https://c.example"}`)
|
|
|
|
q := url.Values{"response_type": {"code"}, "client_id": {"pub"}, "redirect_uri": {testRedirect},
|
|
"code_challenge": {pkce.Challenge("verifier-abcdefghijklmnopqrstuvwxyz-012345")}}
|
|
req := formReqNoBody("GET", authorizeURL(q))
|
|
req.Host = "a.example"
|
|
resp, _ := do(t, app, req)
|
|
if loc := resp.Header.Get("Location"); resp.StatusCode != 302 || !strings.HasPrefix(loc, hostedLoginPath+"?") {
|
|
t.Fatalf("a ping-pong map must serve in place; got %d to %q", resp.StatusCode, loc)
|
|
}
|
|
}
|
|
|
|
// A map the boot refuses costs the move and nothing else: the server still comes
|
|
// up, and every host signs in at its issuer.
|
|
func TestRoute_RefusedSigninMapLeavesEveryHostAtItsIssuer(t *testing.T) {
|
|
installIssuerResolver(t, "https://hanzo.id", testIssuerMap)
|
|
t.Setenv("IAM_FEDERATION_ORIGIN_MAP", `{"hanzo.ai":"http://hanzo.ai"}`)
|
|
prev := activeFederationResolver.Swap(nil)
|
|
t.Cleanup(func() { activeFederationResolver.Store(prev) })
|
|
app, db := newServer(t) // registers the routes, which judge the map
|
|
seedApp(t, db, appOpts{clientID: "pub", redirectURIs: []string{testRedirect}})
|
|
if activeFederationResolver.Load() != nil {
|
|
t.Fatal("a refused map was installed")
|
|
}
|
|
q := url.Values{"response_type": {"code"}, "client_id": {"pub"}, "redirect_uri": {testRedirect},
|
|
"code_challenge": {pkce.Challenge("verifier-abcdefghijklmnopqrstuvwxyz-012345")}}
|
|
req := formReqNoBody("GET", authorizeURL(q))
|
|
req.Host = "hanzo.ai"
|
|
resp, _ := do(t, app, req)
|
|
if want := "https://hanzo.id" + authorizeURL(q); resp.StatusCode != 307 || resp.Header.Get("Location") != want {
|
|
t.Fatalf("refused map: hanzo.ai %d to %q, want 307 to its issuer", resp.StatusCode, resp.Header.Get("Location"))
|
|
}
|
|
}
|
|
|
|
// A confidential client may authorize without PKCE (it authenticates with its
|
|
// secret at the token endpoint).
|
|
func TestAuthorize_ConfidentialWithoutPKCEDelegates(t *testing.T) {
|
|
app, db := newServer(t)
|
|
seedApp(t, db, appOpts{clientID: "conf", secret: "s3cret", redirectURIs: []string{testRedirect}})
|
|
|
|
q := url.Values{"response_type": {"code"}, "client_id": {"conf"}, "redirect_uri": {testRedirect}, "scope": {"openid"}}
|
|
resp, _ := do(t, app, formReqNoBody("GET", authorizeURL(q)))
|
|
if resp.StatusCode != 302 || !strings.HasPrefix(resp.Header.Get("Location"), hostedLoginPath+"?") {
|
|
t.Fatalf("confidential authorize: status=%d loc=%q", resp.StatusCode, resp.Header.Get("Location"))
|
|
}
|
|
}
|
|
|
|
// requireRedirect asserts a 302 whose Location targets wantPrefix and returns it.
|
|
func requireRedirect(t *testing.T, resp *http.Response, wantPrefix string) string {
|
|
t.Helper()
|
|
if resp.StatusCode != 302 {
|
|
t.Fatalf("status = %d, want 302", resp.StatusCode)
|
|
}
|
|
loc := resp.Header.Get("Location")
|
|
if !strings.HasPrefix(loc, wantPrefix) {
|
|
t.Fatalf("Location = %q, want prefix %q", loc, wantPrefix)
|
|
}
|
|
return loc
|
|
}
|
|
|
|
// "Get started" and "Sign in" are the same OAuth request, differing only in
|
|
// which screen the person should land on. The hosted login is what draws that
|
|
// screen, and this endpoint rebuilds the query from named parameters, so the
|
|
// flag reaches the page only if it is one of them — otherwise an application
|
|
// sending someone to create an account gets the credential form instead, and
|
|
// the request that carried the intent looks identical to one that never had it.
|
|
func TestAuthorize_CarriesSignupToTheHostedLogin(t *testing.T) {
|
|
app, db := newServer(t)
|
|
seedApp(t, db, appOpts{clientID: "pub", redirectURIs: []string{testRedirect}})
|
|
|
|
base := url.Values{
|
|
"response_type": {"code"},
|
|
"client_id": {"pub"},
|
|
"redirect_uri": {testRedirect},
|
|
"code_challenge": {pkce.Challenge("verifier-abcdefghijklmnopqrstuvwxyz-012345")},
|
|
}
|
|
forwarded := func(signup string) url.Values {
|
|
q := url.Values{}
|
|
for k, v := range base {
|
|
q[k] = v
|
|
}
|
|
if signup != "" {
|
|
q.Set("signup", signup)
|
|
}
|
|
resp, _ := do(t, app, formReqNoBody("GET", authorizeURL(q)))
|
|
if resp.StatusCode != 302 {
|
|
t.Fatalf("signup=%q: status = %d, want 302", signup, resp.StatusCode)
|
|
}
|
|
loc, err := url.Parse(resp.Header.Get("Location"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return loc.Query()
|
|
}
|
|
|
|
if got := forwarded("true").Get("signup"); got != "true" {
|
|
t.Fatalf("signup=true forwarded as %q, want \"true\"", got)
|
|
}
|
|
// Sign-in is the default, and only the literal reaches the page: the flag is
|
|
// re-encoded from the parsed value, never echoed.
|
|
if got := forwarded("").Get("signup"); got != "" {
|
|
t.Fatalf("no signup forwarded as %q, want empty", got)
|
|
}
|
|
if got := forwarded("yes"); got.Get("signup") != "" {
|
|
t.Fatalf("signup=yes forwarded as %q, want empty", got.Get("signup"))
|
|
}
|
|
}
|