Repository Public
1package api_test23import (4 "bufio"5 "context"6 "net/http"7 "strings"8 "testing"9 "time"1011 "clustr.spboucher.ai/mcc/internal/events"12)1314func TestHTTPSetupLoginCookiesAndCSRF(t *testing.T) {15 h := newHarness(t)16 guest := h.browser()17 if r := guest.do("GET", "/me", nil); r.Status != 401 || r.code() != "unauthenticated" {18 t.Fatalf("anonymous /me: %d %s", r.Status, r.Raw)19 }20 if r := guest.do("GET", "/me", nil); r.Header.Get("X-Correlation-Id") == "" || r.Header.Get("X-Content-Type-Options") != "nosniff" {21 t.Fatal("missing correlation id or security headers")22 }2324 root := h.owner()25 var me struct {26 User struct{ Handle, Role string }27 Permissions []string28 CsrfToken string `json:"csrf_token"`29 }30 root.must("GET", "/me", nil, 200).json(t, &me)31 if me.User.Handle != "root" || me.User.Role != "owner" || len(me.Permissions) < 20 || me.CsrfToken != root.csrf {32 t.Fatalf("unexpected /me: %+v", me)33 }3435 // Cookie attributes.36 r := root.login()37 if r.Status != 200 {38 t.Fatalf("login: %d %s", r.Status, r.Raw)39 }40 var sawSession bool41 for _, ck := range r.Header.Values("Set-Cookie") {42 if strings.HasPrefix(ck, "mcc_session=") {43 sawSession = true44 for _, attr := range []string{"HttpOnly", "SameSite=Strict", "Path=/"} {45 if !strings.Contains(ck, attr) {46 t.Errorf("session cookie lacks %s: %s", attr, ck)47 }48 }49 if strings.Contains(ck, "Max-Age") || strings.Contains(ck, "Expires") {50 t.Errorf("session cookie must not persist: %s", ck)51 }52 }53 }54 if !sawSession {55 t.Fatal("no session cookie set")56 }57 if strings.Contains(string(r.Raw), "access_token") || strings.Contains(string(r.Raw), "refresh_token") {58 t.Fatal("web sign-in must not return bearer tokens")59 }6061 // CSRF: a cookie alone is not enough to change state.62 body := map[string]any{"display_name": "Root Renamed"}63 if r := root.do("PATCH", "/me", body, "X-MCC-CSRF", ""); r.Status != 403 || r.code() != "csrf_failed" {64 t.Fatalf("missing CSRF header: %d %s", r.Status, r.Raw)65 }66 if r := root.do("PATCH", "/me", body, "X-MCC-CSRF", "forged"); r.code() != "csrf_failed" {67 t.Fatalf("forged CSRF header: %s", r.Raw)68 }69 if r := root.do("PATCH", "/me", body, "Origin", "https://evil.example"); r.code() != "csrf_failed" {70 t.Fatalf("cross-origin request with a valid token: %s", r.Raw)71 }72 if r := root.do("PATCH", "/me", body, "Origin", ""); r.code() != "csrf_failed" {73 t.Fatalf("cookie request without Origin: %s", r.Raw)74 }75 other := h.member(root, "viewer", "vera", false)76 if r := root.do("PATCH", "/me", body, "X-MCC-CSRF", other.csrf); r.code() != "csrf_failed" {77 t.Fatalf("another session's CSRF token accepted: %s", r.Raw)78 }79 if h.count(`select count(*) from users where display_name='Root Renamed'`) != 0 {80 t.Fatal("a refused request changed state")81 }82 root.must("PATCH", "/me", body, 200)8384 // Cross-origin sign-in attempts from a browser are refused too.85 evil := h.browser()86 evil.Origin = "https://evil.example"87 if r := evil.do("POST", "/auth/webauthn/authentication/begin", nil); r.code() != "csrf_failed" {88 t.Fatalf("cross-origin begin: %s", r.Raw)89 }9091 // Logout kills the session server-side.92 root.must("POST", "/auth/logout", nil, 204)93 if r := root.do("GET", "/me", nil); r.Status != 401 {94 t.Fatalf("after logout: %d", r.Status)95 }96}9798func TestHTTPAuthorizationAndStepUp(t *testing.T) {99 h := newHarness(t)100 root := h.owner()101 viewer := h.member(root, "viewer", "vera", false)102 operator := h.member(root, "operator", "oscar", true)103104 // Insufficient role: refused by the server and audited.105 inv := map[string]any{"role": "viewer", "handle": "x1", "display_name": "X"}106 for _, c := range []*client{viewer, operator} {107 if r := c.do("POST", "/invitations", inv); r.Status != 403 || r.code() != "forbidden" {108 t.Fatalf("invitation by non-admin: %d %s", r.Status, r.Raw)109 }110 if r := c.do("GET", "/invitations", nil); r.Status != 403 {111 t.Fatalf("list invitations by non-admin: %d", r.Status)112 }113 }114 if n := h.count(`select count(*) from audit_log where action='authz.denied'`); n != 4 {115 t.Fatalf("%d denials audited, want 4", n)116 }117118 // Step-up: required for sensitive operations once the last ceremony is too old.119 h.expireStepUp("root")120 if r := root.do("POST", "/invitations", inv); r.Status != 403 || r.code() != "step_up_required" {121 t.Fatalf("stale step-up: %d %s", r.Status, r.Raw)122 }123 root.must("GET", "/invitations", nil, 200) // reading does not need it124 root.stepUp()125 var created struct {126 Token string `json:"token"`127 SetupURL string `json:"setup_url"`128 Invitation struct{ ID string }129 }130 root.must("POST", "/invitations", inv, 201).json(t, &created)131 if !strings.HasPrefix(created.SetupURL, h.URL+"/setup#") || !strings.HasSuffix(created.SetupURL, created.Token) {132 t.Fatalf("setup url must carry the token in the fragment: %s", created.SetupURL)133 }134 // The token is never listed, logged in audit params, or stored in clear.135 if r := root.must("GET", "/invitations", nil, 200); strings.Contains(string(r.Raw), created.Token) {136 t.Fatal("invitation list leaks the token")137 }138 if h.count(`select count(*) from audit_log where params::text like '%'||$1||'%' or detail like '%'||$1||'%'`, created.Token) != 0 {139 t.Fatal("audit log contains the token")140 }141142 // Admin cannot create an owner even with a fresh step-up.143 admin := h.member(root, "admin", "ada", false)144 if r := admin.do("POST", "/invitations", map[string]any{"role": "owner", "handle": "o2", "display_name": "O"}); r.Status != 403 {145 t.Fatalf("admin minting an owner: %d %s", r.Status, r.Raw)146 }147148 // Removing one's last passkey is refused; deleting needs step-up.149 var keys struct{ Items []struct{ ID string } }150 root.must("GET", "/me/passkeys", nil, 200).json(t, &keys)151 if r := root.do("DELETE", "/me/passkeys/"+keys.Items[0].ID, nil); r.Status != 409 || r.code() != "last_passkey" {152 t.Fatalf("delete last passkey: %d %s", r.Status, r.Raw)153 }154 h.expireStepUp("root")155 if r := root.do("DELETE", "/me/passkeys/"+keys.Items[0].ID, nil); r.code() != "step_up_required" {156 t.Fatalf("delete passkey without step-up: %s", r.Raw)157 }158}159160func TestHTTPInvitationAbuse(t *testing.T) {161 h := newHarness(t)162 root := h.owner()163 var created struct{ Token string }164 root.must("POST", "/invitations", map[string]any{"role": "viewer", "handle": "once", "display_name": "Once"}, 201).json(t, &created)165166 a, b := h.browser(), h.browser()167 a.must("POST", "/invitations/exchange", map[string]any{"token": created.Token}, 200)168 if r := b.do("POST", "/invitations/exchange", map[string]any{"token": created.Token}); r.Status != 410 || r.code() != "invitation_invalid" {169 t.Fatalf("second exchange: %d %s", r.Status, r.Raw)170 }171 // Without the setup cookie the transaction is unreachable.172 if r := b.do("GET", "/invitations/transaction", nil); r.Status != 410 {173 t.Fatalf("transaction without cookie: %d", r.Status)174 }175 if r := b.do("POST", "/auth/webauthn/registration/begin", map[string]any{}); r.Status != 401 {176 t.Fatalf("registration without session or transaction: %d %s", r.Status, r.Raw)177 }178 // Setup endpoints are protected against cross-site use as well.179 if r := a.do("POST", "/auth/webauthn/registration/begin", map[string]any{}, "Origin", "https://evil.example"); r.code() != "csrf_failed" {180 t.Fatalf("cross-origin setup: %s", r.Raw)181 }182 // Abandon: nothing can be registered afterwards.183 a.must("DELETE", "/invitations/transaction", nil, 204)184 if r := a.do("POST", "/auth/webauthn/registration/begin", map[string]any{}); r.Status == 200 {185 t.Fatal("abandoned transaction still usable")186 }187 if h.count(`select count(*) from users where handle='once'`) != 0 {188 t.Fatal("account created from an abandoned invitation")189 }190 // Revoked invitation.191 var c2 struct {192 Token string193 Invitation struct{ ID string }194 }195 root.must("POST", "/invitations", map[string]any{"role": "viewer", "handle": "rev", "display_name": "Rev"}, 201).json(t, &c2)196 root.must("DELETE", "/invitations/"+c2.Invitation.ID, nil, 204)197 if r := h.browser().do("POST", "/invitations/exchange", map[string]any{"token": c2.Token}); r.Status != 410 {198 t.Fatalf("revoked invitation: %d", r.Status)199 }200}201202func TestHTTPNativeBearerRefreshAndDeviceRevocation(t *testing.T) {203 h := newHarness(t)204 root := h.owner()205 mac := h.member(root, "operator", "oscar", true)206 if mac.access == "" || mac.refresh == "" || mac.device == "" {207 t.Fatal("native client did not get tokens")208 }209 mac.must("GET", "/me", nil, 200)210 // Malformed Authorization headers are refused outright (no fallback to cookies).211 if r := mac.do("GET", "/me", nil, "Authorization", "Basic abc"); r.Status != 401 {212 t.Fatalf("basic auth accepted: %d", r.Status)213 }214215 // Rotation, then replay of the old refresh token revokes the session.216 old := mac.refresh217 var pair map[string]any218 mac.must("POST", "/auth/refresh", map[string]any{"refresh_token": old}, 200).json(t, &pair)219 mac.absorb(pair)220 mac.must("GET", "/me", nil, 200)221 if r := mac.do("POST", "/auth/refresh", map[string]any{"refresh_token": old}); r.Status != 401 || r.code() != "refresh_rejected" {222 t.Fatalf("refresh replay: %d %s", r.Status, r.Raw)223 }224 if r := mac.do("GET", "/me", nil); r.Status != 401 {225 t.Fatal("session survived a refresh-token replay")226 }227228 // Sign in again on the same device id, then revoke the device from the web session.229 if r := mac.login(); r.Status != 200 {230 t.Fatalf("native login: %d %s", r.Status, r.Raw)231 }232 deviceID := mac.device233 web := h.browser()234 web.auth = mac.auth235 if r := web.login(); r.Status != 200 {236 t.Fatalf("web login with the same passkey: %d %s", r.Status, r.Raw)237 }238 var devs struct {239 Items []struct {240 ID string241 Kind string242 Current bool243 }244 }245 web.must("GET", "/me/devices", nil, 200).json(t, &devs)246 if len(devs.Items) != 2 {247 t.Fatalf("want 2 devices (one native reused, one web), got %d", len(devs.Items))248 }249 web.must("DELETE", "/me/devices/"+deviceID, nil, 204)250 if r := mac.do("GET", "/me", nil); r.Status != 401 {251 t.Fatal("revoked device still authenticated")252 }253 if r := mac.do("POST", "/auth/refresh", map[string]any{"refresh_token": mac.refresh}); r.Status != 401 {254 t.Fatal("revoked device could refresh")255 }256 web.must("GET", "/me", nil, 200)257 // Another user's device or session id is indistinguishable from a missing one.258 var rootDevs struct{ Items []struct{ ID string } }259 root.must("GET", "/me/devices", nil, 200).json(t, &rootDevs)260 if r := web.do("DELETE", "/me/devices/"+rootDevs.Items[0].ID, nil); r.Status != 404 {261 t.Fatalf("revoking someone else's device: %d", r.Status)262 }263264 // Session expiry.265 h.Pool.Exec(context.Background(), `update sessions set idle_expires_at = now() - interval '1 second' where user_id=(select id from users where handle='oscar')`)266 if r := web.do("GET", "/me", nil); r.Status != 401 {267 t.Fatal("expired session accepted")268 }269}270271func TestHTTPEnvelopeFallbackAndRateLimit(t *testing.T) {272 h := newHarness(t)273 root := h.owner()274 if r := root.do("GET", "/definitely/not/a/route", nil); r.Status != 404 || r.code() != "not_found" {275 t.Fatalf("unknown route: %d %s", r.Status, r.Raw)276 }277 if r := root.do("POST", "/auth/webauthn/authentication/finish", map[string]any{"challenge_id": "not-a-uuid"}); r.Status != 400 || r.code() != "validation_failed" {278 t.Fatalf("malformed body: %d %s", r.Status, r.Raw)279 }280 big := strings.Repeat("x", 2<<20)281 if r := root.do("PATCH", "/me", map[string]any{"display_name": big}); r.Status < 400 {282 t.Fatalf("oversized body accepted: %d", r.Status)283 }284 // Apple association file.285 res, err := http.Get(h.URL + "/.well-known/apple-app-site-association")286 if err != nil || res.StatusCode != 200 || !strings.HasPrefix(res.Header.Get("Content-Type"), "application/json") {287 t.Fatalf("AASA: %v %v", err, res)288 }289 res.Body.Close()290291 // Unauthenticated ceremonies are rate-limited per IP.292 limited := false293 for i := 0; i < 60; i++ {294 r := h.browser().do("POST", "/auth/webauthn/authentication/begin", nil)295 if r.Status == 429 {296 if r.Header.Get("Retry-After") == "" || r.code() != "rate_limited" {297 t.Fatalf("429 without Retry-After: %s", r.Raw)298 }299 limited = true300 break301 }302 }303 if !limited {304 t.Fatal("public endpoint was never rate-limited")305 }306}307308func TestHTTPEventStream(t *testing.T) {309 h := newHarness(t)310 root := h.owner()311 viewer := h.member(root, "viewer", "vera", false)312 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)313 defer cancel()314315 open := func(c *client, lastID string) (*bufio.Scanner, func()) {316 req, _ := http.NewRequestWithContext(ctx, "GET", h.URL+"/api/v1/events", nil)317 if lastID != "" {318 req.Header.Set("Last-Event-ID", lastID)319 }320 streamer := &http.Client{Jar: c.http.Jar}321 res, err := streamer.Do(req)322 if err != nil {323 t.Fatal(err)324 }325 if res.StatusCode != 200 || !strings.HasPrefix(res.Header.Get("Content-Type"), "text/event-stream") {326 t.Fatalf("stream: %d %s", res.StatusCode, res.Header.Get("Content-Type"))327 }328 return bufio.NewScanner(res.Body), func() { res.Body.Close() }329 }330 // next returns the next (id, event) frame, skipping comments.331 next := func(sc *bufio.Scanner) (id, event, data string) {332 for sc.Scan() {333 line := sc.Text()334 switch {335 case strings.HasPrefix(line, "id: "):336 id = line[4:]337 case strings.HasPrefix(line, "event: "):338 event = line[7:]339 case strings.HasPrefix(line, "data: "):340 data = line[6:]341 case line == "" && event != "":342 return343 }344 }345 t.Fatalf("stream ended: %v", sc.Err())346 return347 }348349 if res, _ := http.Get(h.URL + "/api/v1/events"); res.StatusCode != 401 {350 t.Fatalf("anonymous stream: %d", res.StatusCode)351 }352353 rs, closeRoot := open(root, "")354 vs, closeViewer := open(viewer, "")355 defer closeViewer()356 if _, ev, _ := next(rs); ev != "hello" {357 t.Fatalf("first frame %q", ev)358 }359 next(vs)360361 pub := func(topic string, v any) {362 if err := events.Publish(ctx, h.Pool, topic, v); err != nil {363 t.Fatal(err)364 }365 }366 pub("audit.appended", map[string]int{"seq": 1}) // owner only367 pub("node.state", map[string]string{"node_id": "n1"})368 id1, ev, _ := next(rs)369 if ev != "audit.appended" {370 t.Fatalf("owner should receive audit events, got %q", ev)371 }372 id2, ev, data := next(rs)373 if ev != "node.state" || !strings.Contains(data, "n1") || id2 <= id1 {374 t.Fatalf("owner frame 2: %s %s %s", id2, ev, data)375 }376 if _, ev, _ := next(vs); ev != "node.state" {377 t.Fatalf("viewer must not see audit events; got %q first", ev)378 }379380 // Resume: events published while disconnected are delivered exactly once, in order.381 closeRoot()382 pub("node.state", map[string]string{"node_id": "n2"})383 pub("node.state", map[string]string{"node_id": "n3"})384 rs2, close2 := open(root, id2)385 defer close2()386 next(rs2) // hello387 if _, _, d := next(rs2); !strings.Contains(d, "n2") {388 t.Fatalf("resume lost an event: %s", d)389 }390 if _, _, d := next(rs2); !strings.Contains(d, "n3") {391 t.Fatalf("resume out of order: %s", d)392 }393394 // A position that was pruned yields an explicit resync.395 h.Pool.Exec(ctx, `update events_outbox set ts = now() - interval '2 hours'`)396 events.Prune(ctx, h.Pool)397 pub("node.state", map[string]string{"node_id": "n4"})398 rs3, close3 := open(root, id1)399 defer close3()400 next(rs3)401 if _, ev, _ := next(rs3); ev != "resync" {402 t.Fatalf("expected resync, got %q", ev)403 }404}405