Repository Public
1package api_test23// Shared test harness: a real control-api HTTP server on a throwaway4// database, plus HTTP clients that behave like a browser (cookie jar, Origin,5// CSRF header) or like a native app (bearer tokens), using the software6// WebAuthn authenticator.78import (9 "bytes"10 "context"11 "encoding/json"12 "io"13 "net/http"14 "net/http/cookiejar"15 "net/http/httptest"16 "strings"17 "testing"18 "time"1920 "github.com/jackc/pgx/v5/pgxpool"2122 "clustr.spboucher.ai/mcc/internal/api"23 "clustr.spboucher.ai/mcc/internal/config"24 "clustr.spboucher.ai/mcc/internal/events"25 "clustr.spboucher.ai/mcc/internal/identity"26 "clustr.spboucher.ai/mcc/internal/identity/vauth"27 "clustr.spboucher.ai/mcc/internal/testdb"28)2930type harness struct {31 t *testing.T32 URL string // origin, e.g. http://localhost:5432133 Pool *pgxpool.Pool34 Ident *identity.Service35 Cfg *config.Config36 Server *api.Server37 DBURL string38}3940func newHarness(t *testing.T) *harness {41 t.Helper()42 pool, dbURL := testdb.New(t)43 ts := httptest.NewUnstartedServer(nil)44 origin := "http://localhost:" + ts.Listener.Addr().String()[strings.LastIndex(ts.Listener.Addr().String(), ":")+1:]45 cfg := &config.Config{Env: config.Test, PublicOrigin: origin, RPID: "localhost", SecretsDir: t.TempDir(), TrustedProxies: nil,46 SessionIdle: 30 * time.Minute, SessionAbsolute: 12 * time.Hour, AccessTTL: 10 * time.Minute, RefreshTTL: 30 * 24 * time.Hour,47 StepUpWindow: 5 * time.Minute, FreshAfter: 30 * time.Second, OfflineAfter: 120 * time.Second,48 RetainRaw: 7 * 24 * time.Hour, Retain1m: 30 * 24 * time.Hour, Retain1h: 400 * 24 * time.Hour,49 AppleAppIDs: []string{"TEAMID0000.ai.example.app"}}50 ident, err := identity.New(pool, cfg)51 if err != nil {52 t.Fatal(err)53 }54 hub := events.NewHub(pool)55 ctx, cancel := context.WithCancel(context.Background())56 go hub.Run(ctx)57 srv := api.NewServer(api.Deps{Pool: pool, Cfg: cfg, Identity: ident, Hub: hub})58 ts.Config.Handler = srv.Handler()59 ts.Start()60 t.Cleanup(func() { cancel(); ts.CloseClientConnections(); ts.Close() })61 return &harness{t: t, URL: origin, Pool: pool, Ident: ident, Cfg: cfg, Server: srv, DBURL: dbURL}62}6364// client is one user agent.65type client struct {66 h *harness67 http *http.Client68 auth *vauth.Authenticator69 browser bool70 csrf string71 access string72 refresh string73 device string74 setupTx string75 Origin string // Origin header sent by a browser client (override to simulate cross-site requests)76}7778func (h *harness) browser() *client {79 jar, _ := cookiejar.New(nil)80 return &client{h: h, http: &http.Client{Jar: jar, Timeout: 15 * time.Second}, auth: vauth.New(h.URL), browser: true, Origin: h.URL}81}8283func (h *harness) native() *client {84 return &client{h: h, http: &http.Client{Timeout: 15 * time.Second}, auth: vauth.New(h.URL)}85}8687type resp struct {88 Status int89 Header http.Header90 Raw []byte91}9293func (r resp) json(t *testing.T, dst any) {94 t.Helper()95 if err := json.Unmarshal(r.Raw, dst); err != nil {96 t.Fatalf("decode %q: %v", r.Raw, err)97 }98}99100func (r resp) code() string {101 var e struct {102 Error struct{ Code string } `json:"error"`103 }104 json.Unmarshal(r.Raw, &e)105 return e.Error.Code106}107108// do sends a request the way this kind of client would.109func (c *client) do(method, path string, body any, hdr ...string) resp {110 c.h.t.Helper()111 var rd io.Reader112 if body != nil {113 b, _ := json.Marshal(body)114 rd = bytes.NewReader(b)115 }116 req, err := http.NewRequest(method, c.h.URL+"/api/v1"+path, rd)117 if err != nil {118 c.h.t.Fatal(err)119 }120 if body != nil {121 req.Header.Set("Content-Type", "application/json")122 }123 if c.browser {124 if method != "GET" && c.Origin != "" {125 req.Header.Set("Origin", c.Origin)126 }127 if method != "GET" && c.csrf != "" {128 req.Header.Set("X-MCC-CSRF", c.csrf)129 }130 } else {131 if c.access != "" {132 req.Header.Set("Authorization", "Bearer "+c.access)133 }134 if c.setupTx != "" {135 req.Header.Set("X-MCC-Setup-Transaction", c.setupTx)136 }137 }138 for i := 0; i+1 < len(hdr); i += 2 {139 if hdr[i+1] == "" {140 req.Header.Del(hdr[i])141 } else {142 req.Header.Set(hdr[i], hdr[i+1])143 }144 }145 res, err := c.http.Do(req)146 if err != nil {147 c.h.t.Fatalf("%s %s: %v", method, path, err)148 }149 defer res.Body.Close()150 raw, _ := io.ReadAll(res.Body)151 return resp{Status: res.StatusCode, Header: res.Header, Raw: raw}152}153154func (c *client) must(method, path string, body any, want int) resp {155 c.h.t.Helper()156 r := c.do(method, path, body)157 if r.Status != want {158 c.h.t.Fatalf("%s %s: status %d (%s), want %d", method, path, r.Status, r.Raw, want)159 }160 return r161}162163func (c *client) kind() string {164 if c.browser {165 return "web"166 }167 return "macos"168}169170func (c *client) clientInfo() map[string]any {171 ci := map[string]any{"kind": c.kind(), "label": "test " + c.kind()}172 if c.device != "" && !c.browser {173 ci["device_id"] = c.device174 }175 return ci176}177178func (c *client) absorb(auth map[string]any) {179 if v, ok := auth["csrf_token"].(string); ok {180 c.csrf = v181 }182 if v, ok := auth["access_token"].(string); ok {183 c.access = v184 }185 if v, ok := auth["refresh_token"].(string); ok {186 c.refresh = v187 }188 if v, ok := auth["device_id"].(string); ok {189 c.device = v190 }191}192193// setup completes an invitation: exchange, passkey registration, first session.194func (c *client) setup(token string) {195 c.h.t.Helper()196 r := c.must("POST", "/invitations/exchange", map[string]any{"token": token, "client": c.clientInfo()}, 200)197 var tx map[string]any198 r.json(c.h.t, &tx)199 if !c.browser {200 c.setupTx, _ = tx["transaction_token"].(string)201 if c.setupTx == "" {202 c.h.t.Fatal("native client did not receive a transaction token")203 }204 } else if _, leaked := tx["transaction_token"]; leaked {205 c.h.t.Fatal("web client must not receive the transaction token in the body")206 }207 var ch struct {208 ChallengeID string `json:"challenge_id"`209 PublicKey json.RawMessage `json:"public_key"`210 }211 c.must("POST", "/auth/webauthn/registration/begin", map[string]any{}, 200).json(c.h.t, &ch)212 cred, err := c.auth.Create([]byte(`{"publicKey":` + string(ch.PublicKey) + `}`))213 if err != nil {214 c.h.t.Fatal(err)215 }216 var out struct {217 Auth map[string]any `json:"auth"`218 }219 c.must("POST", "/auth/webauthn/registration/finish", map[string]any{"challenge_id": ch.ChallengeID,220 "credential": json.RawMessage(cred), "client": c.clientInfo()}, 200).json(c.h.t, &out)221 if out.Auth == nil {222 c.h.t.Fatal("setup did not open a session")223 }224 c.setupTx = ""225 c.absorb(out.Auth)226}227228// login signs in with the client's passkey.229func (c *client) login() resp {230 c.h.t.Helper()231 var ch struct {232 ChallengeID string `json:"challenge_id"`233 PublicKey json.RawMessage `json:"public_key"`234 }235 c.access = ""236 c.must("POST", "/auth/webauthn/authentication/begin", nil, 200).json(c.h.t, &ch)237 as, err := c.auth.Get([]byte(`{"publicKey":` + string(ch.PublicKey) + `}`))238 if err != nil {239 c.h.t.Fatal(err)240 }241 r := c.do("POST", "/auth/webauthn/authentication/finish", map[string]any{"challenge_id": ch.ChallengeID,242 "credential": json.RawMessage(as), "client": c.clientInfo()})243 if r.Status == 200 {244 var auth map[string]any245 r.json(c.h.t, &auth)246 c.absorb(auth)247 }248 return r249}250251// stepUp performs a fresh passkey verification on the current session.252func (c *client) stepUp() {253 c.h.t.Helper()254 var ch struct {255 ChallengeID string `json:"challenge_id"`256 PublicKey json.RawMessage `json:"public_key"`257 }258 c.must("POST", "/auth/stepup/begin", nil, 200).json(c.h.t, &ch)259 as, _ := c.auth.Get([]byte(`{"publicKey":` + string(ch.PublicKey) + `}`))260 c.must("POST", "/auth/stepup/finish", map[string]any{"challenge_id": ch.ChallengeID, "credential": json.RawMessage(as)}, 200)261}262263// owner bootstraps the first owner out of band and returns its browser client.264func (h *harness) owner() *client {265 h.t.Helper()266 _, token, err := h.Ident.BootstrapOwner(context.Background(), "root", "Root Owner", 15*time.Minute)267 if err != nil {268 h.t.Fatal(err)269 }270 c := h.browser()271 c.setup(token)272 return c273}274275// invite makes `by` create an invitation and returns a new client of the276// requested kind that completed it.277func (h *harness) member(by *client, role, handle string, native bool) *client {278 h.t.Helper()279 var out struct {280 Token string `json:"token"`281 SetupURL string `json:"setup_url"`282 }283 by.must("POST", "/invitations", map[string]any{"role": role, "handle": handle, "display_name": "User " + handle}, 201).json(h.t, &out)284 c := h.browser()285 if native {286 c = h.native()287 }288 c.setup(out.Token)289 return c290}291292// expireStepUp ages the step-up of every session of handle.293func (h *harness) expireStepUp(handle string) {294 h.t.Helper()295 if _, err := h.Pool.Exec(context.Background(), `update sessions set authenticated_at = now() - interval '1 hour'296 where user_id = (select id from users where handle=$1)`, handle); err != nil {297 h.t.Fatal(err)298 }299}300301func (h *harness) count(sql string, args ...any) int {302 h.t.Helper()303 var n int304 if err := h.Pool.QueryRow(context.Background(), sql, args...).Scan(&n); err != nil {305 h.t.Fatal(err)306 }307 return n308}309