Files
summercms/modules/wristband/consent_path_test.go
Jakub Zych 7ecfa6087d test(32.2-05): unit tests for administrator MCP grants, admin consent, account items and access revocation
- wristband: TestAuthorizeConsentPath, TestAuthorizeDefaultScopes
- pier: TestBackendOnlyGrant, TestLinkedGrantNoScopeLimit (Docker)
- cabana: TestTokenScopeNames, TestMCPAdminConsent, TestAccountContributionItems,
  TestBackendAccessRevokedEvent (Docker); export_test.go exposes the event
  helper for the de-duplication case
2026-11-21 02:00:16 +01:00

205 lines
8.4 KiB
Go

package wristband
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"slices"
"strings"
"testing"
)
// consentPathServer builds a server on issuer with one public client "cli"
// at authorizeTestRedirect; mutate may change the options first.
func consentPathServer(t *testing.T, issuer string, mutate func(*Options)) *Server {
t.Helper()
backend := newMemoryBackend()
opts := DefaultOptions()
opts.Issuer = issuer
opts.Resource = issuer + "/mcp"
if mutate != nil {
mutate(&opts)
}
srv := NewServer(opts)
srv.SetBackend(backend)
insertAuthorizeTestClient(backend, "cli", []string{authorizeTestRedirect}, nil)
return srv
}
// consentPathAuthorize runs one authorize request. scope nil sends no scope
// parameter; a non-nil scope (empty included) sends it as given. It answers
// the recorder of a 302.
func consentPathAuthorize(t *testing.T, srv *Server, scope *string) *httptest.ResponseRecorder {
t.Helper()
_, challenge := s256Pair(t)
q := url.Values{}
q.Set("client_id", "cli")
q.Set("redirect_uri", authorizeTestRedirect)
q.Set("response_type", "code")
q.Set("code_challenge", challenge)
q.Set("code_challenge_method", "S256")
if scope != nil {
q.Set("scope", *scope)
}
rec := httptest.NewRecorder()
srv.Authorize(rec, httptest.NewRequest(http.MethodGet, "/oauth/mcp/authorize?"+q.Encode(), nil))
if rec.Code != http.StatusFound {
t.Fatalf("authorize status = %d %s, want 302", rec.Code, rec.Body.String())
}
return rec
}
// handoffRequest answers the request id of a handoff Location that must
// start with prefix and carry nothing but the escaped id after it.
func handoffRequest(t *testing.T, location, prefix string) string {
t.Helper()
if !strings.HasPrefix(location, prefix) {
t.Fatalf("Location = %q, want prefix %q", location, prefix)
}
escaped := strings.TrimPrefix(location, prefix)
id, err := url.QueryUnescape(escaped)
if err != nil || id == "" || strings.ContainsAny(escaped, "?&#/") {
t.Fatalf("Location = %q carries no plain request id", location)
}
if rfc3986Escape(id) != escaped {
t.Fatalf("request id %q is not RFC 3986 escaped in %q", id, location)
}
return id
}
// TestAuthorizeConsentPath locks the authorize handoff (SC-1, D-04): with
// Options.ConsentPath empty the Location is byte for byte the PHP
// {issuer}/connect?request=<RFC 3986 escaped id>, with the PHP headers; a
// set path replaces /connect on the same issuer; an issuer with a path
// segment keeps it in front of the consent path.
func TestAuthorizeConsentPath(t *testing.T) {
read := "read"
cases := []struct {
name, issuer, path, prefix string
}{
{"empty path is the PHP /connect", "https://issuer.example.test", "", "https://issuer.example.test/connect?request="},
{"a set path replaces /connect", "https://issuer.example.test", "/backend/connect", "https://issuer.example.test/backend/connect?request="},
{"an issuer path segment is kept", "https://issuer.example.test/tenant", "", "https://issuer.example.test/tenant/connect?request="},
{"an issuer path segment with a set path", "https://issuer.example.test/tenant", "/gfadmin/connect", "https://issuer.example.test/tenant/gfadmin/connect?request="},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
srv := consentPathServer(t, tc.issuer, func(o *Options) { o.ConsentPath = tc.path })
rec := consentPathAuthorize(t, srv, &read)
location := rec.Header().Get("Location")
id := handoffRequest(t, location, tc.prefix)
if location != tc.issuer+srv.consentPath()+"?request="+rfc3986Escape(id) {
t.Fatalf("Location %q is not issuer + consent path + escaped id", location)
}
if got := rec.Header().Get("Cache-Control"); got != "no-store, private" {
t.Fatalf("Cache-Control = %q, want the PHP no-store, private", got)
}
if _, err := srv.PendingRequest(context.Background(), id, 1); err != nil {
t.Fatalf("the handed-off request is not pending: %v", err)
}
})
}
t.Run("the default options leave the path empty", func(t *testing.T) {
if DefaultOptions().ConsentPath != "" || len(DefaultOptions().DefaultScopes) != 0 {
t.Fatalf("DefaultOptions sets ConsentPath %q DefaultScopes %v", DefaultOptions().ConsentPath, DefaultOptions().DefaultScopes)
}
srv := consentPathServer(t, "https://issuer.example.test", nil)
if srv.consentPath() != "/connect" {
t.Fatalf("consentPath = %q, want /connect", srv.consentPath())
}
})
t.Run("empty and explicit /connect answer the same bytes", func(t *testing.T) {
empty := consentPathServer(t, "https://issuer.example.test", nil)
explicit := consentPathServer(t, "https://issuer.example.test", func(o *Options) { o.ConsentPath = "/connect" })
a := consentPathAuthorize(t, empty, &read)
b := consentPathAuthorize(t, explicit, &read)
idA := handoffRequest(t, a.Header().Get("Location"), "https://issuer.example.test/connect?request=")
idB := handoffRequest(t, b.Header().Get("Location"), "https://issuer.example.test/connect?request=")
bodyA := strings.ReplaceAll(a.Body.String(), rfc3986Escape(idA), "ID")
bodyB := strings.ReplaceAll(b.Body.String(), rfc3986Escape(idB), "ID")
if bodyA != bodyB || !strings.Contains(bodyA, "/connect?request=ID") {
t.Fatalf("redirect bodies differ:\n%s\n%s", bodyA, bodyB)
}
})
}
// TestAuthorizeDefaultScopes locks the scope fallback of an authorize
// request (SC-1, D-04): an absent, empty or identity-only scope value gets
// Options.DefaultScopes; entries outside the accepted set, identity scopes
// and repeats are dropped from it; empty DefaultScopes (or nothing left)
// keeps the PHP read; an explicit data scope is never replaced.
func TestAuthorizeDefaultScopes(t *testing.T) {
const issuer = "https://issuer.example.test"
str := func(s string) *string { return &s }
stored := func(t *testing.T, srv *Server, scope *string) []string {
t.Helper()
rec := consentPathAuthorize(t, srv, scope)
id := handoffRequest(t, rec.Header().Get("Location"), issuer+"/connect?request=")
view, err := srv.PendingRequest(context.Background(), id, 1)
if err != nil {
t.Fatal(err)
}
return view.ScopesRequested
}
withCatalog := func(defaults ...string) func(*Options) {
return func(o *Options) {
o.ScopesSupported = []string{"*", "admin:read", "acme", "acme:read", "offline_access"}
o.DefaultScopes = defaults
}
}
t.Run("absent, empty and identity-only values get the default scopes", func(t *testing.T) {
srv := consentPathServer(t, issuer, withCatalog("*", "admin:read", "acme", "acme:read"))
for name, scope := range map[string]*string{
"absent": nil,
"empty": str(""),
"blank": str(" "),
"identity only": str("openid profile email"),
} {
if got := stored(t, srv, scope); !slices.Equal(got, []string{"*", "admin:read", "acme", "acme:read"}) {
t.Fatalf("%s scope stored %v, want the default scopes in order", name, got)
}
}
})
t.Run("defaults outside the accepted set, identity scopes and repeats are dropped", func(t *testing.T) {
srv := consentPathServer(t, issuer, withCatalog(" acme ", "openid", "unknown", "acme", "", "acme:read"))
if got := stored(t, srv, nil); !slices.Equal(got, []string{"acme", "acme:read"}) {
t.Fatalf("stored %v, want [acme acme:read]", got)
}
})
t.Run("empty default scopes keep read", func(t *testing.T) {
srv := consentPathServer(t, issuer, nil)
for _, scope := range []*string{nil, str(""), str("openid")} {
if got := stored(t, srv, scope); !slices.Equal(got, []string{"read"}) {
t.Fatalf("stored %v, want [read]", got)
}
}
})
t.Run("defaults with nothing accepted keep read", func(t *testing.T) {
srv := consentPathServer(t, issuer, func(o *Options) { o.DefaultScopes = []string{"acme", "openid"} })
if got := stored(t, srv, nil); !slices.Equal(got, []string{"read"}) {
t.Fatalf("stored %v, want [read]", got)
}
})
t.Run("an explicit scope is not replaced", func(t *testing.T) {
srv := consentPathServer(t, issuer, withCatalog("*", "acme"))
if got := stored(t, srv, str("acme:read")); !slices.Equal(got, []string{"acme:read"}) {
t.Fatalf("stored %v, want [acme:read]", got)
}
if got := stored(t, srv, str("openid acme:read")); !slices.Equal(got, []string{"acme:read"}) {
t.Fatalf("identity plus data scope stored %v, want [acme:read]", got)
}
plain := consentPathServer(t, issuer, func(o *Options) { o.DefaultScopes = []string{"write"} })
if got := stored(t, plain, str("read")); !slices.Equal(got, []string{"read"}) {
t.Fatalf("explicit read stored %v, want [read]", got)
}
})
}