| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "net/url" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/go-chi/chi/v5" |
| 15 | ) |
| 16 | |
| 17 | func previewPassRouter(t *testing.T, r *previewPassRig) http.Handler { |
| 18 | t.Helper() |
| 19 | env := agentEnv(t) |
| 20 | cfg, e := LoadConfig(func(k string) string { return env[k] }) |
| 21 | if e != nil { |
| 22 | t.Fatal(e) |
| 23 | } |
| 24 | cfg.Origin = r.s.personOrigin |
| 25 | // Keep the fixture's verified native session while using the actual app router. |
| 26 | session := r.s.personNativeSession |
| 27 | h, e := RouterWithStore(r.s.db, cfg, agentMail{}, nil, r.s) |
| 28 | if e != nil { |
| 29 | t.Fatal(e) |
| 30 | } |
| 31 | r.s.personNativeSession = session |
| 32 | t.Cleanup(func() { CloseLive(h) }) |
| 33 | return h |
| 34 | } |
| 35 | func passExchangeRequest(token, task, candidate string) *http.Request { |
| 36 | form := url.Values{"pass": {token}, "task": {task}, "candidate": {candidate}} |
| 37 | r := httptest.NewRequest("POST", "https://equipo.example/native/preview/exchange", strings.NewReader(form.Encode())) |
| 38 | r.Header.Set("Origin", "https://equipo.example") |
| 39 | r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 40 | return r |
| 41 | } |
| 42 | func TestPreviewPassHTTPFlowAndIsolation(t *testing.T) { |
| 43 | r := newPreviewPassRig(t) |
| 44 | h := previewPassRouter(t, r) |
| 45 | minted := agentRequest(h, "POST", "/api/v1/tasks/tk_preview/preview-pass", `{"candidate_sha":"`+passCandidate+`"}`, r.credential.Token) |
| 46 | if minted.Code != 201 { |
| 47 | t.Fatalf("mint: %d %s", minted.Code, minted.Body) |
| 48 | } |
| 49 | var pass previewPass |
| 50 | if e := json.Unmarshal(minted.Body.Bytes(), &pass); e != nil { |
| 51 | t.Fatal(e) |
| 52 | } |
| 53 | w := httptest.NewRecorder() |
| 54 | h.ServeHTTP(w, passExchangeRequest(pass.Pass, "tk_preview", passCandidate)) |
| 55 | if w.Code != 303 || w.Header().Get("Location") != "/tasks/tk_preview/preview" { |
| 56 | t.Fatalf("exchange: %d %v %s", w.Code, w.Header(), w.Body) |
| 57 | } |
| 58 | cookies := w.Result().Cookies() |
| 59 | if len(cookies) != 1 { |
| 60 | t.Fatal("cookies", cookies) |
| 61 | } |
| 62 | cookie := cookies[0] |
| 63 | if cookie.Name != "__Host-equipo-preview-tk_preview" || cookie.Domain != "" || cookie.Path != "/" || !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode || cookie.MaxAge != 900 { |
| 64 | t.Fatalf("cookie attributes: %+v", cookie) |
| 65 | } |
| 66 | for _, route := range []struct { |
| 67 | method, path string |
| 68 | allowed bool |
| 69 | }{{"GET", "/tasks/tk_preview/preview", true}, {"POST", "/tasks/tk_preview/preview", false}, {"GET", "/tasks/tk_other/preview", false}, {"GET", "/tasks/tk_preview", false}, {"GET", "/api/v1/tasks/tk_preview", false}, {"GET", "/api/v1/events", false}, {"GET", "/api/v1/attachments/nope", false}} { |
| 70 | req := httptest.NewRequest(route.method, "https://equipo.example"+route.path, nil) |
| 71 | req.AddCookie(cookie) |
| 72 | req.Header.Set("Origin", "https://equipo.example") |
| 73 | answer := httptest.NewRecorder() |
| 74 | h.ServeHTTP(answer, req) |
| 75 | if route.allowed { |
| 76 | if answer.Code != 200 || !strings.Contains(answer.Header().Get("Content-Security-Policy"), "frame-src https://eq-preview.example.test;") || !strings.Contains(answer.Body.String(), `sandbox="allow-scripts allow-same-origin"`) { |
| 77 | t.Fatalf("wrapper %d %s", answer.Code, answer.Body) |
| 78 | } |
| 79 | } else if answer.Code >= 200 && answer.Code < 300 { |
| 80 | t.Fatalf("grant escaped scope: %s %s", route.method, route.path) |
| 81 | } |
| 82 | } |
| 83 | for _, input := range []struct{ token, task, candidate string }{{pass.Pass, "tk_preview", passCandidate}, {strings.Repeat("a", 43), "tk_preview", passCandidate}, {pass.Pass, "tk_other", passCandidate}} { |
| 84 | w = httptest.NewRecorder() |
| 85 | h.ServeHTTP(w, passExchangeRequest(input.token, input.task, input.candidate)) |
| 86 | if w.Code != 404 || strings.Contains(w.Body.String(), pass.Pass) { |
| 87 | t.Fatalf("observable refusal: %d %s", w.Code, w.Body) |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | func TestPreviewCookiePresenceNeverFallsThrough(t *testing.T) { |
| 92 | r := newPreviewPassRig(t) |
| 93 | // Even an otherwise valid browser session must not rescue a refused grant. |
| 94 | normal := 0 |
| 95 | app := &application{store: r.s, origin: r.s.personOrigin} |
| 96 | secret := strings.Repeat("A", 43) |
| 97 | for _, raw := range []string{"__Host-equipo-preview-tk_preview=" + secret, "__Host-equipo-preview-tk_preview=" + secret + "; __Host-equipo-preview-tk_preview=" + secret} { |
| 98 | route := chi.NewRouter() |
| 99 | route.Get("/tasks/{id}/preview", app.previewGrantOrBrowser(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { normal++; w.WriteHeader(200) })).ServeHTTP) |
| 100 | req := httptest.NewRequest("GET", "https://equipo.example/tasks/tk_preview/preview", nil) |
| 101 | req.Header.Set("Cookie", raw+"; normal-session=valid") |
| 102 | w := httptest.NewRecorder() |
| 103 | route.ServeHTTP(w, req) |
| 104 | if w.Code != 404 { |
| 105 | t.Fatalf("invalid cookie %q: %d", raw, w.Code) |
| 106 | } |
| 107 | } |
| 108 | if normal != 0 { |
| 109 | t.Fatal("fell through to normal sign-in", normal) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | func TestPreviewExchangeRejectsConflictingContext(t *testing.T) { |
| 114 | r := newPreviewPassRig(t) |
| 115 | h := previewPassRouter(t, r) |
| 116 | p := r.mint(t) |
| 117 | changes := []struct { |
| 118 | name string |
| 119 | change func(*http.Request) |
| 120 | }{ |
| 121 | {"query", func(q *http.Request) { q.URL.RawQuery = "redirect=https://evil.example" }}, |
| 122 | {"origin", func(q *http.Request) { q.Header.Set("Origin", "https://evil.example") }}, |
| 123 | {"referer", func(q *http.Request) { q.Header.Set("Referer", "https://evil.example/") }}, |
| 124 | {"fetch-site", func(q *http.Request) { q.Header.Set("Sec-Fetch-Site", "cross-site") }}, |
| 125 | {"bearer", func(q *http.Request) { q.Header.Set("Authorization", "Bearer "+r.credential.Token) }}, |
| 126 | {"type", func(q *http.Request) { q.Header.Set("Content-Type", "text/plain") }}, |
| 127 | {"get", func(q *http.Request) { q.Method = "GET" }}, |
| 128 | {"extra", func(q *http.Request) { |
| 129 | q.Body = io.NopCloser(strings.NewReader("pass=" + p.Pass + "&task=tk_preview&candidate=" + passCandidate + "&redirect=x")) |
| 130 | }}, |
| 131 | {"duplicate", func(q *http.Request) { |
| 132 | q.Body = io.NopCloser(strings.NewReader("pass=" + p.Pass + "&pass=" + p.Pass + "&task=tk_preview&candidate=" + passCandidate)) |
| 133 | }}, |
| 134 | {"bound", func(q *http.Request) { |
| 135 | q.Body = io.NopCloser(strings.NewReader("pass=" + p.Pass + "&task=tk_preview&candidate=" + passCandidate + strings.Repeat("&", 4096))) |
| 136 | }}, |
| 137 | } |
| 138 | for _, tt := range changes { |
| 139 | t.Run(tt.name, func(t *testing.T) { |
| 140 | request := passExchangeRequest(p.Pass, "tk_preview", passCandidate) |
| 141 | tt.change(request) |
| 142 | response := httptest.NewRecorder() |
| 143 | h.ServeHTTP(response, request) |
| 144 | if response.Code < 400 || response.Header().Get("Set-Cookie") != "" || response.Header().Get("Location") != "" { |
| 145 | t.Fatalf("accepted conflicting context: %d %v", response.Code, response.Header()) |
| 146 | } |
| 147 | }) |
| 148 | } |
| 149 | response := httptest.NewRecorder() |
| 150 | h.ServeHTTP(response, passExchangeRequest(p.Pass, "tk_preview", passCandidate)) |
| 151 | if response.Code != 303 { |
| 152 | t.Fatalf("refused requests consumed pass: %d %s", response.Code, response.Body) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | func TestPreviewExpiredCookieAndUnsafePOSTNeverFallThrough(t *testing.T) { |
| 157 | r := newPreviewPassRig(t) |
| 158 | pass := r.mint(t) |
| 159 | grant, err := r.s.exchangePreviewPass(r.ctx, pass.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| 160 | if err != nil { |
| 161 | t.Fatal(err) |
| 162 | } |
| 163 | app := &application{store: r.s, origin: r.s.personOrigin} |
| 164 | calls := 0 |
| 165 | handler := app.previewGrantOrBrowser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(200) })) |
| 166 | for _, method := range []string{"POST", "GET"} { |
| 167 | if method == "GET" { |
| 168 | r.clock.Advance(15 * time.Minute) |
| 169 | } |
| 170 | req := httptest.NewRequest(method, "https://equipo.example/tasks/tk_preview/preview", nil) |
| 171 | ctx := chi.NewRouteContext() |
| 172 | ctx.URLParams.Add("id", "tk_preview") |
| 173 | req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, ctx)) |
| 174 | req.Header.Set("Cookie", previewCookie+"tk_preview="+grant.Secret+"; normal-session=valid-browser-session") |
| 175 | out := httptest.NewRecorder() |
| 176 | handler.ServeHTTP(out, req) |
| 177 | if out.Code < 400 || calls != 0 { |
| 178 | t.Fatalf("%s grant fell through: code=%d calls=%d", method, out.Code, calls) |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |