| 1 | package equipo |
| 2 | |
| 3 | // Adversarial cases supplied by Fable, retained as permanent regressions. |
| 4 | // Adapted to the approved per-task Host cookie and relative lifetime contract. |
| 5 | |
| 6 | import ( |
| 7 | "database/sql" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "fmt" |
| 11 | "net/http" |
| 12 | "net/http/httptest" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/rastrillo/rastrillo/sessions" |
| 18 | "gorm.io/gorm" |
| 19 | ) |
| 20 | |
| 21 | func reviewFlow(t *testing.T, r *previewPassRig, h http.Handler) (previewPass, *http.Cookie) { |
| 22 | t.Helper() |
| 23 | minted := agentRequest(h, "POST", "/api/v1/tasks/tk_preview/preview-pass", `{"candidate_sha":"`+passCandidate+`"}`, r.credential.Token) |
| 24 | if minted.Code != 201 { |
| 25 | t.Fatalf("mint: %d %s", minted.Code, minted.Body) |
| 26 | } |
| 27 | var pass previewPass |
| 28 | if e := json.Unmarshal(minted.Body.Bytes(), &pass); e != nil { |
| 29 | t.Fatal(e) |
| 30 | } |
| 31 | if pass.ExpiresIn < 1 || pass.ExpiresIn > 60 || pass.GrantExpiresIn < pass.ExpiresIn || pass.GrantExpiresIn > 900 { |
| 32 | t.Fatal("unbounded relative lifetime") |
| 33 | } |
| 34 | w := httptest.NewRecorder() |
| 35 | h.ServeHTTP(w, passExchangeRequest(pass.Pass, "tk_preview", passCandidate)) |
| 36 | if w.Code != 303 { |
| 37 | t.Fatalf("exchange: %d %s", w.Code, w.Body) |
| 38 | } |
| 39 | return pass, w.Result().Cookies()[0] |
| 40 | } |
| 41 | |
| 42 | func reviewGet(h http.Handler, method, path string, cookie *http.Cookie) *httptest.ResponseRecorder { |
| 43 | req := httptest.NewRequest(method, "https://equipo.example"+path, nil) |
| 44 | if cookie != nil { |
| 45 | req.AddCookie(cookie) |
| 46 | } |
| 47 | if method != "GET" && method != "HEAD" { |
| 48 | req.Header.Set("Origin", "https://equipo.example") |
| 49 | } |
| 50 | w := httptest.NewRecorder() |
| 51 | h.ServeHTTP(w, req) |
| 52 | return w |
| 53 | } |
| 54 | |
| 55 | func TestReviewPathTricks(t *testing.T) { |
| 56 | r := newPreviewPassRig(t) |
| 57 | h := previewPassRouter(t, r) |
| 58 | _, cookie := reviewFlow(t, r, h) |
| 59 | if w := reviewGet(h, "GET", "/tasks/tk_preview/preview", cookie); w.Code != 200 { |
| 60 | t.Fatalf("baseline %d", w.Code) |
| 61 | } |
| 62 | for _, c := range []struct{ method, path string }{ |
| 63 | {"GET", "/tasks/tk_preview/preview/"}, |
| 64 | {"GET", "/tasks/tk_preview/preview/.."}, |
| 65 | {"GET", "/tasks/tk_preview/preview/../../tk_preview"}, |
| 66 | {"GET", "/tasks/tk_preview/preview/../rendered-change"}, |
| 67 | {"GET", "/tasks/tk_preview/preview-evil"}, |
| 68 | {"GET", "/tasks/tk_preview%2Fpreview"}, |
| 69 | {"GET", "/tasks/tk%5Fpreview/preview"}, |
| 70 | {"GET", "/tasks/tk_preview/preview%2F..%2F..%2Ftk_preview"}, |
| 71 | {"GET", "/tasks/tk_preview/preview?x=1"}, |
| 72 | {"GET", "/tasks/tk_preview/preview;x"}, |
| 73 | {"GET", "//tasks/tk_preview/preview"}, |
| 74 | {"GET", "/tasks/tk_preview/./preview"}, |
| 75 | {"GET", "/tasks/tk_preview/%70review"}, |
| 76 | {"GET", "/tasks/tk_preview/preview%00"}, |
| 77 | {"GET", "/tasks/tk_preview/rendered-change"}, |
| 78 | {"GET", "/tasks/tk_preview/files/x"}, |
| 79 | {"GET", "/tasks/tk_preview/move"}, |
| 80 | {"GET", "/tasks"}, |
| 81 | {"GET", "/conversation"}, |
| 82 | {"GET", "/live"}, |
| 83 | {"GET", "/api/v1/me"}, |
| 84 | {"GET", "/api/v1/tasks"}, |
| 85 | {"GET", "/api/v1/tasks/tk_preview"}, |
| 86 | {"POST", "/api/v1/tasks/tk_preview/preview-pass"}, |
| 87 | {"POST", "/tasks/tk_preview/preview"}, |
| 88 | {"POST", "/tasks/tk_preview/notes"}, |
| 89 | {"HEAD", "/tasks/tk_preview/preview"}, |
| 90 | {"PUT", "/tasks/tk_preview/preview"}, |
| 91 | {"DELETE", "/tasks/tk_preview/preview"}, |
| 92 | } { |
| 93 | w := reviewGet(h, c.method, c.path, cookie) |
| 94 | leaked := strings.Contains(w.Body.String(), "eq-preview.example.test") || strings.Contains(w.Body.String(), "<iframe") |
| 95 | t.Logf("%-6s %-55s -> %d leaked=%v loc=%q", c.method, c.path, w.Code, leaked, w.Header().Get("Location")) |
| 96 | if (w.Code >= 200 && w.Code < 300) || leaked { |
| 97 | t.Errorf("grant escaped: %s %s -> %d", c.method, c.path, w.Code) |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | func TestReviewStateChangesBetweenWrapperReads(t *testing.T) { |
| 103 | for _, kind := range []string{"epoch", "revoked", "device-expired", "native-session", "member", "member-removed", "redeploy-url", "redeploy-digest", "unsafe", "final", "candidate", "new-preview-step", "task-deleted"} { |
| 104 | t.Run(kind, func(t *testing.T) { |
| 105 | r := newPreviewPassRig(t) |
| 106 | h := previewPassRouter(t, r) |
| 107 | _, cookie := reviewFlow(t, r, h) |
| 108 | if w := reviewGet(h, "GET", "/tasks/tk_preview/preview", cookie); w.Code != 200 { |
| 109 | t.Fatalf("baseline %d", w.Code) |
| 110 | } |
| 111 | exec := func(q string, args ...any) { |
| 112 | t.Helper() |
| 113 | if _, e := r.s.db.Writer().Exec(q, args...); e != nil { |
| 114 | t.Fatal(e) |
| 115 | } |
| 116 | } |
| 117 | switch kind { |
| 118 | case "epoch": |
| 119 | exec("UPDATE members SET session_epoch=?", r.clock.Now().Add(time.Second).Unix()) |
| 120 | case "revoked": |
| 121 | exec("UPDATE person_devices SET revoked_at=?", r.clock.Now()) |
| 122 | case "device-expired": |
| 123 | exec("UPDATE person_devices SET token_expires_at=?", r.clock.Now()) |
| 124 | case "native-session": |
| 125 | r.s.personNativeSession = func(*gorm.DB, string) (sessions.Session, error) { return sessions.Session{}, sql.ErrNoRows } |
| 126 | case "member": |
| 127 | exec("UPDATE members SET active=0") |
| 128 | case "member-removed": |
| 129 | exec("DELETE FROM members") |
| 130 | case "redeploy-url": |
| 131 | exec("UPDATE chat_steps SET preview=json_set(preview,'$.url','https://eq-other.example.test/') WHERE id='preview_step'") |
| 132 | case "redeploy-digest": |
| 133 | exec("UPDATE chat_steps SET preview=json_set(preview,'$.digest',?) WHERE id='preview_step'", strings.Repeat("b", 64)) |
| 134 | case "unsafe": |
| 135 | exec("UPDATE chat_steps SET preview=json_set(preview,'$.unsafe',json('true')) WHERE id='preview_step'") |
| 136 | case "final": |
| 137 | exec("UPDATE chat_tasks SET stage='done'") |
| 138 | case "candidate": |
| 139 | exec("UPDATE chat_steps SET candidate_sha=? WHERE id='eng_preview'", strings.Repeat("2", 40)) |
| 140 | case "new-preview-step": |
| 141 | exec("INSERT INTO chat_steps(id,task_id,idx,specialist,state,attempt,candidate_sha,revision) VALUES('preview_step2','tk_preview',2,'preview','running',1,?,1)", passCandidate) |
| 142 | case "task-deleted": |
| 143 | exec("DELETE FROM chat_tasks WHERE id='tk_preview'") |
| 144 | } |
| 145 | w := reviewGet(h, "GET", "/tasks/tk_preview/preview", cookie) |
| 146 | t.Logf("%s -> %d", kind, w.Code) |
| 147 | if w.Code < 400 || strings.Contains(w.Body.String(), "<iframe") { |
| 148 | t.Errorf("%s: wrapper still served: %d", kind, w.Code) |
| 149 | } |
| 150 | }) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | func TestReviewSecretsNeverAtRest(t *testing.T) { |
| 155 | r := newPreviewPassRig(t) |
| 156 | h := previewPassRouter(t, r) |
| 157 | pass, cookie := reviewFlow(t, r, h) |
| 158 | _ = reviewGet(h, "GET", "/tasks/tk_preview/preview", cookie) |
| 159 | _ = reviewGet(h, "GET", "/tasks/tk_other/preview", cookie) |
| 160 | // replay and wrong binding, to exercise refusal audits |
| 161 | w := httptest.NewRecorder() |
| 162 | h.ServeHTTP(w, passExchangeRequest(pass.Pass, "tk_preview", passCandidate)) |
| 163 | db := r.s.db.Reader() |
| 164 | rows, e := db.Query("SELECT name FROM sqlite_master WHERE type='table'") |
| 165 | if e != nil { |
| 166 | t.Fatal(e) |
| 167 | } |
| 168 | var tables []string |
| 169 | for rows.Next() { |
| 170 | var n string |
| 171 | _ = rows.Scan(&n) |
| 172 | tables = append(tables, n) |
| 173 | } |
| 174 | rows.Close() |
| 175 | needles := []string{pass.Pass, cookie.Value} |
| 176 | for _, n := range []string{pass.Pass, cookie.Value} { |
| 177 | needles = append(needles, hex.EncodeToString([]byte(n))) |
| 178 | } |
| 179 | for _, table := range tables { |
| 180 | cols, e := db.Query("SELECT name FROM pragma_table_info('" + table + "')") |
| 181 | if e != nil { |
| 182 | continue |
| 183 | } |
| 184 | var names []string |
| 185 | for cols.Next() { |
| 186 | var n string |
| 187 | _ = cols.Scan(&n) |
| 188 | names = append(names, n) |
| 189 | } |
| 190 | cols.Close() |
| 191 | for _, col := range names { |
| 192 | for i, needle := range needles { |
| 193 | var count int |
| 194 | q := fmt.Sprintf(`SELECT count(*) FROM "%s" WHERE instr(CAST("%s" AS text), ?) > 0 OR instr(lower(hex("%s")), ?) > 0`, table, col, col) |
| 195 | if e := db.QueryRow(q, needle, needle).Scan(&count); e != nil { |
| 196 | continue |
| 197 | } |
| 198 | if count > 0 { |
| 199 | t.Errorf("secret %d at rest in %s.%s", i, table, col) |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | t.Logf("scanned %d tables", len(tables)) |
| 205 | } |
| 206 | |
| 207 | func TestReviewExchangeHeaders(t *testing.T) { |
| 208 | r := newPreviewPassRig(t) |
| 209 | h := previewPassRouter(t, r) |
| 210 | for _, c := range []struct { |
| 211 | name string |
| 212 | set func(*http.Request) |
| 213 | ok bool |
| 214 | }{ |
| 215 | {"no-evidence", func(q *http.Request) { q.Header.Del("Origin") }, false}, |
| 216 | {"origin-null", func(q *http.Request) { q.Header.Set("Origin", "null") }, false}, |
| 217 | {"same-site", func(q *http.Request) { q.Header.Set("Sec-Fetch-Site", "same-site") }, false}, |
| 218 | {"same-site-no-origin", func(q *http.Request) { q.Header.Del("Origin"); q.Header.Set("Sec-Fetch-Site", "same-site") }, false}, |
| 219 | {"cross-site-good-origin", func(q *http.Request) { q.Header.Set("Sec-Fetch-Site", "cross-site") }, false}, |
| 220 | {"none-no-origin", func(q *http.Request) { q.Header.Del("Origin"); q.Header.Set("Sec-Fetch-Site", "none") }, true}, |
| 221 | {"none-evil-origin", func(q *http.Request) { |
| 222 | q.Header.Set("Origin", "https://evil.example") |
| 223 | q.Header.Set("Sec-Fetch-Site", "none") |
| 224 | }, false}, |
| 225 | {"two-origins", func(q *http.Request) { q.Header.Add("Origin", "https://evil.example") }, false}, |
| 226 | {"origin-case", func(q *http.Request) { q.Header.Set("Origin", "https://EQUIPO.example") }, false}, |
| 227 | {"origin-port", func(q *http.Request) { q.Header.Set("Origin", "https://equipo.example:443") }, false}, |
| 228 | {"cookie-session-junk", func(q *http.Request) { q.Header.Set("Cookie", "x=y") }, true}, |
| 229 | {"charset", func(q *http.Request) { |
| 230 | q.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") |
| 231 | }, true}, |
| 232 | {"multipart", func(q *http.Request) { q.Header.Set("Content-Type", "multipart/form-data; boundary=x") }, false}, |
| 233 | } { |
| 234 | p := r.mint(t) |
| 235 | r.clock.Advance(7 * time.Second) // stay inside the 10/min mint limit |
| 236 | q := passExchangeRequest(p.Pass, "tk_preview", passCandidate) |
| 237 | c.set(q) |
| 238 | w := httptest.NewRecorder() |
| 239 | h.ServeHTTP(w, q) |
| 240 | t.Logf("%-24s -> %d cookie=%v", c.name, w.Code, w.Header().Get("Set-Cookie") != "") |
| 241 | if (w.Code == 303) != c.ok { |
| 242 | t.Errorf("%s: got %d", c.name, w.Code) |
| 243 | } |
| 244 | if w.Code != 303 && w.Header().Get("Set-Cookie") != "" { |
| 245 | t.Errorf("%s: cookie on refusal", c.name) |
| 246 | } |
| 247 | if strings.Contains(w.Body.String(), p.Pass) || strings.Contains(w.Header().Get("Location"), p.Pass) { |
| 248 | t.Errorf("%s: pass reflected", c.name) |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | func TestReviewNewGrantReplacesOldAndMintNeedsDeviceBearer(t *testing.T) { |
| 254 | r := newPreviewPassRig(t) |
| 255 | h := previewPassRouter(t, r) |
| 256 | _, first := reviewFlow(t, r, h) |
| 257 | _, second := reviewFlow(t, r, h) |
| 258 | if w := reviewGet(h, "GET", "/tasks/tk_preview/preview", first); w.Code == 200 { |
| 259 | t.Errorf("old grant still live after a new presentation") |
| 260 | } |
| 261 | if w := reviewGet(h, "GET", "/tasks/tk_preview/preview", second); w.Code != 200 { |
| 262 | t.Errorf("new grant refused %d", w.Code) |
| 263 | } |
| 264 | // both cookies at once: restricted lane, refused |
| 265 | req := httptest.NewRequest("GET", "https://equipo.example/tasks/tk_preview/preview", nil) |
| 266 | req.Header.Set("Cookie", second.Name+"="+first.Value+"; "+second.Name+"="+second.Value) |
| 267 | w := httptest.NewRecorder() |
| 268 | h.ServeHTTP(w, req) |
| 269 | t.Logf("tossed duplicate cookie -> %d", w.Code) |
| 270 | if w.Code != 404 { |
| 271 | t.Fatal("duplicate capabilities accepted", w.Code) |
| 272 | } |
| 273 | // the preview cookie cannot mint |
| 274 | req = httptest.NewRequest("POST", "https://equipo.example/api/v1/tasks/tk_preview/preview-pass", strings.NewReader(`{"candidate_sha":"`+passCandidate+`"}`)) |
| 275 | req.Header.Set("Content-Type", "application/json") |
| 276 | req.Header.Set("Origin", "https://equipo.example") |
| 277 | req.AddCookie(second) |
| 278 | w = httptest.NewRecorder() |
| 279 | h.ServeHTTP(w, req) |
| 280 | if w.Code == 201 { |
| 281 | t.Errorf("cookie minted a pass") |
| 282 | } |
| 283 | // bearer + cookie together |
| 284 | req = httptest.NewRequest("POST", "https://equipo.example/api/v1/tasks/tk_preview/preview-pass", strings.NewReader(`{"candidate_sha":"`+passCandidate+`"}`)) |
| 285 | req.Header.Set("Content-Type", "application/json") |
| 286 | req.Header.Set("Authorization", "Bearer "+r.credential.Token) |
| 287 | req.AddCookie(second) |
| 288 | w = httptest.NewRecorder() |
| 289 | h.ServeHTTP(w, req) |
| 290 | t.Logf("bearer+cookie mint -> %d", w.Code) |
| 291 | if w.Code == 201 { |
| 292 | t.Errorf("bearer with cookie minted a pass") |
| 293 | } |
| 294 | // the grant secret is not a pass, and the pass is not a grant |
| 295 | p := r.mint(t) |
| 296 | if w := reviewGet(h, "GET", "/tasks/tk_preview/preview", &http.Cookie{Name: second.Name, Value: p.Pass}); w.Code == 200 { |
| 297 | t.Errorf("pass accepted as grant cookie") |
| 298 | } |
| 299 | w = httptest.NewRecorder() |
| 300 | h.ServeHTTP(w, passExchangeRequest(second.Value, "tk_preview", passCandidate)) |
| 301 | if w.Code == 303 { |
| 302 | t.Errorf("grant secret accepted as pass") |
| 303 | } |
| 304 | } |
| 305 | |