Files
iam/internal/oidc/authorize_test.go
Darkhorse7starsandGitHub ea652e4561 oidc: answer prompt=none on a sign-in origin for apps that share one sign-out (D6) (#40)
On a sign-in origin that is not the issuer's host (hanzo.ai signing in for
hanzo.id) authorize never answered silently, because a sign-out elsewhere could
leave that origin's session alive and a silent answer would revive it. That no
longer holds for the platform's own applications on IAM_SIGNOUT_APPS: leaving
any of them retires the grant to all of them, and a navigating sign-out ends
the session on every sign-in origin of the issuer (nextSignout).

So prompt=none there is answered from the session for an application owned by
a reserved signing owner and listed on IAM_SIGNOUT_APPS (silentAtSigninOrigin,
the mintAllowed owner pin). A request with no prompt keeps the hosted "continue
as" page; any other application, a tenant's lookalike clientId included, is
still login_required, and an unset list answers nothing silently.
2026-11-11 03:11:53 -08:00

435 lines
19 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. So
// authorize there never answers silently from it for an application whose sign-out
// is not shared (off IAM_SIGNOUT_APPS, which is unset here): the page asks, and
// prompt=none, which allows no page, is login_required. At the issuer the same
// session answers as it always has. The shared-sign-out case is
// TestAuthorize_FirstPartySilentAtSigninOrigin.
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"))
}
}
// An application's signinUrl is an organization's to write, and authorize redirects to
// it: followed only where IAM itself signs people in, never to wherever it says. The
// issuer was an open redirector for any tenant's application.
func TestAuthorize_SigninUrlIsFollowedOnlyWhereIamSignsPeopleIn(t *testing.T) {
app, db := newServer(t)
installIssuerResolver(t, "https://hanzo.id", testIssuerMap)
installFederationResolver(t, `{"hanzo.ai":"https://hanzo.ai"}`)
for _, c := range []struct{ client, signin, want string }{
{"acme-1", "https://evil.example/phish", hostedLoginPath + "?"},
{"acme-2", "http://hanzo.ai/login", hostedLoginPath + "?"},
{"acme-3", "https://[email protected]/login", hostedLoginPath + "?"},
{"acme-4", "https://hanzo.ai.evil.example/login", hostedLoginPath + "?"},
{"acme-5", "https://lux.id/login", hostedLoginPath + "?"},
{"hanzo-cli", "https://hanzo.ai/login", "https://hanzo.ai/login?"},
{"hanzo-id", "https://hanzo.id/login/custom", "https://hanzo.id/login/custom?"},
{"plain", "", hostedLoginPath + "?"},
} {
seedApp(t, db, appOpts{clientID: c.client, redirectURIs: []string{testRedirect}, signin: c.signin})
q := url.Values{
"response_type": {"code"}, "client_id": {c.client}, "redirect_uri": {testRedirect},
"state": {"s"}, "code_challenge": {pkce.Challenge("verifier-abcdefghijklmnopqrstuvwxyz-012345")},
}
req := formReqNoBody("GET", authorizeURL(q))
resp, _ := do(t, app, req)
if loc := resp.Header.Get("Location"); resp.StatusCode != 302 || !strings.HasPrefix(loc, c.want) {
t.Errorf("%s with signinUrl %q: %d to %q, want a 302 to %q", c.client, c.signin, resp.StatusCode, loc, c.want)
}
}
}