Files
summercms/modules/wristband/example_test.go

252 lines
9.4 KiB
Go

package wristband_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/wristband"
)
// newServer builds the authorization server of an application served at
// https://blog.example.com. The application sets Issuer and Resource for
// its own deployment; the defaults cover everything else.
func newServer(backend wristband.Backend) *wristband.Server {
opts := wristband.DefaultOptions()
opts.Issuer = "https://blog.example.com" // app URL without a trailing slash
opts.Resource = "https://blog.example.com/mcp"
opts.ScopesSupported = []string{"read", "write", "offline_access"}
srv := wristband.NewServer(opts)
srv.SetBackend(backend) // the application's transactional store adapter
return srv
}
// routes mounts the RFC endpoints in a raw group: no JSON envelope middleware.
func routes(r pact.Router, srv *wristband.Server) {
r.GroupRaw("", nil, func(g pact.Router) {
g.Get("/.well-known/oauth-authorization-server", srv.Metadata)
g.Get("/oauth/mcp/authorize", srv.Authorize)
g.Post("/oauth/mcp/token", srv.Token)
g.Post("/oauth/mcp/register", srv.Register)
})
}
// approve is called by the application's consent handler for a signed-in user.
func approve(ctx context.Context, w http.ResponseWriter, srv *wristband.Server, requestID string, userID uint) error {
redirectTo, err := srv.IssueCode(ctx, requestID, userID, []string{"read"}, nil)
if err != nil {
return err // wristband.ErrPendingNotFound, wristband.ErrNoGrantableScopes, ...
}
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(map[string]string{"redirect_to": redirectTo})
}
func ExampleServer_Metadata() {
// The metadata document does not need the application's stores.
srv := newServer(nil)
rec := httptest.NewRecorder()
srv.Metadata(rec, httptest.NewRequest("GET", "/.well-known/oauth-authorization-server", nil))
var doc map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &doc); err != nil {
fmt.Println(err)
return
}
for _, key := range []string{
"issuer",
"authorization_endpoint",
"token_endpoint",
"registration_endpoint",
"scopes_supported",
"grant_types_supported",
"code_challenge_methods_supported",
} {
fmt.Println(key, doc[key])
}
// Output:
// issuer https://blog.example.com
// authorization_endpoint https://blog.example.com/oauth/mcp/authorize
// token_endpoint https://blog.example.com/oauth/mcp/token
// registration_endpoint https://blog.example.com/oauth/mcp/register
// scopes_supported [read write offline_access]
// grant_types_supported [authorization_code refresh_token]
// code_challenge_methods_supported [S256]
}
func ExampleRejectRedirectURI() {
for _, uri := range []string{
"https://client.example.org/callback",
"http://127.0.0.1:33418/callback",
"http://client.example.org/callback",
} {
if reason := wristband.RejectRedirectURI(uri); reason != "" {
fmt.Println("rejected:", reason)
continue
}
fmt.Println("accepted:", uri)
}
// Output:
// accepted: https://client.example.org/callback
// accepted: http://127.0.0.1:33418/callback
// rejected: Redirect URI must be https:// or loopback http://127.0.0.1 / http://localhost: http://client.example.org/callback
}
func ExampleIssueClientCredentials() {
// A confidential client gets a secret, shown once; store only the hash.
id, secret, hash, err := wristband.IssueClientCredentials("client_secret_post")
fmt.Println(id != "", secret != "", hash != nil && *hash != secret, err)
// A public client (PKCE only) gets no secret.
_, secret, hash, err = wristband.IssueClientCredentials("none")
fmt.Println(secret == "", hash == nil, err)
// Output:
// true true true <nil>
// true true <nil>
}
// newOIDCServer builds the OpenID Connect provider of an application served
// at https://id.example.com. The host application supplies storage, the
// signing-key ring and its pages; SetOIDCBackend refuses a nil one.
func newOIDCServer(backend wristband.OIDCBackend, keys wristband.KeyStore, host wristband.OIDCHost) (*wristband.Server, error) {
opts := wristband.DefaultOptions()
opts.Issuer = "https://id.example.com"
oidc := wristband.DefaultOIDCOptions()
oidc.LoginURL = "/account/login" // anonymous users land here with ?redirect=<resume path>
oidc.RefreshEnabled = true // only clients with OfflineAccess get refresh tokens
srv := wristband.NewOIDCServer(opts, oidc)
if err := srv.SetOIDCBackend(backend, keys, host); err != nil {
return nil, err // nil argument, or called on an MCP server
}
return srv, nil
}
func ExampleNewOIDCServer() {
// Without storage, keys and a host the server refuses to start.
_, err := newOIDCServer(nil, nil, nil)
fmt.Println(err)
// An OIDC server serves discovery instead of the MCP metadata document.
srv := wristband.NewOIDCServer(wristband.DefaultOptions(), wristband.DefaultOIDCOptions())
rec := httptest.NewRecorder()
srv.Metadata(rec, httptest.NewRequest("GET", "/.well-known/oauth-authorization-server", nil))
fmt.Println("metadata", rec.Code)
defaults := wristband.DefaultOIDCOptions()
fmt.Println(defaults.ScopesSupported, defaults.CodeTTL, defaults.RefreshEnabled)
// Output:
// wristband: OIDC backend is nil
// metadata 404
// [openid profile email] 1m0s false
}
// providerRoutes mounts the OpenID Connect endpoints at the paths discovery
// advertises.
func providerRoutes(r pact.Router, srv *wristband.Server) {
r.GroupRaw("", nil, func(g pact.Router) {
g.Get("/.well-known/openid-configuration", srv.Discovery)
g.Get("/oauth/jwks", srv.JWKS)
g.Get("/oauth/authorize", srv.Authorize) // start
g.Post("/oauth/authorize", srv.Authorize) // consent decision
g.Get("/oauth/authorize/resume/{request}", srv.Resume)
g.Post("/oauth/authorize/switch-account", srv.SwitchAccount)
g.Post("/oauth/token", srv.Token)
g.Get("/oauth/userinfo", srv.UserInfo)
})
}
// muxRouter is a minimal pact.Router over http.ServeMux, standing in for
// surf's router in these tests. Middleware names are ignored.
type muxRouter struct {
mux *http.ServeMux
prefix string
}
func (m muxRouter) handle(method, path string, h http.HandlerFunc) {
m.mux.HandleFunc(method+" "+m.prefix+path, h)
}
func (m muxRouter) Group(prefix string, _ []string, fn func(pact.Router)) {
fn(muxRouter{m.mux, m.prefix + prefix})
}
func (m muxRouter) GroupRaw(prefix string, mw []string, fn func(pact.Router)) {
m.Group(prefix, mw, fn)
}
func (m muxRouter) Get(path string, h http.HandlerFunc, _ ...string) { m.handle("GET", path, h) }
func (m muxRouter) Post(path string, h http.HandlerFunc, _ ...string) { m.handle("POST", path, h) }
func (m muxRouter) Put(path string, h http.HandlerFunc, _ ...string) { m.handle("PUT", path, h) }
func (m muxRouter) Patch(path string, h http.HandlerFunc, _ ...string) { m.handle("PATCH", path, h) }
func (m muxRouter) Delete(path string, h http.HandlerFunc, _ ...string) { m.handle("DELETE", path, h) }
func (muxRouter) Where(string, string) {}
func (muxRouter) WhereIn(string, ...string) {}
func serve(t *testing.T, mux http.Handler, method, path string) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(method, path, nil))
return rec
}
// TestDocsRoutes mounts the README's MCP and OpenID Connect routes and calls
// the metadata, discovery and JWKS endpoints through them.
func TestDocsRoutes(t *testing.T) {
backend, _ := wristband.DocsBackend(t)
mux := http.NewServeMux()
routes(muxRouter{mux: mux}, newServer(backend))
rec := serve(t, mux, http.MethodGet, "/.well-known/oauth-authorization-server")
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"issuer":"https://blog.example.com"`) {
t.Fatalf("metadata: %d %s", rec.Code, rec.Body)
}
provider, err := newOIDCServer(wristband.DocsOIDC(t))
if err != nil {
t.Fatal(err)
}
oidcMux := http.NewServeMux()
providerRoutes(muxRouter{mux: oidcMux}, provider)
rec = serve(t, oidcMux, http.MethodGet, "/.well-known/openid-configuration")
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"issuer":"https://id.example.com"`) {
t.Fatalf("discovery: %d %s", rec.Code, rec.Body)
}
rec = serve(t, oidcMux, http.MethodGet, "/oauth/jwks")
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"keys"`) {
t.Fatalf("jwks: %d %s", rec.Code, rec.Body)
}
}
// TestDocsApprove grants a pending request through approve and checks the
// redirect it returns; a second approval finds the request used.
func TestDocsApprove(t *testing.T) {
backend, requestID := wristband.DocsBackend(t)
srv := newServer(backend)
rec := httptest.NewRecorder()
if err := approve(context.Background(), rec, srv, requestID, 7); err != nil {
t.Fatal(err)
}
var body map[string]string
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
redirect, err := url.Parse(body["redirect_to"])
if err != nil {
t.Fatal(err)
}
q := redirect.Query()
if redirect.Host != "client.example.org" || q.Get("code") == "" || q.Get("iss") != "https://blog.example.com" || q.Get("state") != "docs-state" {
t.Fatalf("redirect_to = %q", body["redirect_to"])
}
if err := approve(context.Background(), httptest.NewRecorder(), srv, requestID, 7); !errors.Is(err, wristband.ErrPendingNotFound) {
t.Fatalf("second approve: %v, want ErrPendingNotFound", err)
}
}