| 1 | package connection |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/base64" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "html" |
| 9 | "io" |
| 10 | "log" |
| 11 | "log/slog" |
| 12 | "net" |
| 13 | "net/http" |
| 14 | "net/http/httptest" |
| 15 | "net/url" |
| 16 | "os" |
| 17 | "os/exec" |
| 18 | "path/filepath" |
| 19 | "strings" |
| 20 | "sync" |
| 21 | "testing" |
| 22 | "time" |
| 23 | |
| 24 | access "amadan.net/oficina/agent-access.git" |
| 25 | "amadan.net/oficina/agent-access.git/client" |
| 26 | "amadan.net/oficina/agent-access.git/grant" |
| 27 | "amadan.net/rastrillo/rastrillo/assertion" |
| 28 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 29 | "amadan.net/rastrillo/rastrillo/db" |
| 30 | cdplog "github.com/chromedp/cdproto/log" |
| 31 | "github.com/chromedp/cdproto/network" |
| 32 | "github.com/chromedp/chromedp" |
| 33 | ) |
| 34 | |
| 35 | // These tests drive a real Chromium because the bugs they guard live in the |
| 36 | // browser: what Origin it sends and what its CSP lets a form redirect to. A Go |
| 37 | // client that sets Origin by hand passes whether or not a person can connect. |
| 38 | |
| 39 | const ( |
| 40 | browserSubject = "pr_bbbbbbbbbbbbbbbbbbbbbbbbbb" |
| 41 | browserState = "browser-state-0123456789" |
| 42 | firstPartyID = "db533929-5300-4363-a0f7-586e8f0a349f" |
| 43 | thirdPartyID = "third-party-host" |
| 44 | consentButton = `button[value="approve"]` |
| 45 | cancelButton = `button[value="deny"]` |
| 46 | consentCookie = "__Host-oficina-consent" |
| 47 | browserTimeout = 20 * time.Second |
| 48 | ) |
| 49 | |
| 50 | // chromePath follows rastrillo's harness: a missing browser fails the run |
| 51 | // unless RASTRILLO_BROWSER_OPTIONAL makes skipping a deliberate choice. |
| 52 | func chromePath(t *testing.T) string { |
| 53 | t.Helper() |
| 54 | if path := os.Getenv("RASTRILLO_CHROME"); path != "" { |
| 55 | return path |
| 56 | } |
| 57 | for _, name := range []string{"chromium", "chromium-browser", "google-chrome", "google-chrome-stable"} { |
| 58 | if path, err := exec.LookPath(name); err == nil { |
| 59 | return path |
| 60 | } |
| 61 | } |
| 62 | if home, err := os.UserHomeDir(); err == nil { |
| 63 | hits, _ := filepath.Glob(filepath.Join(home, ".cache", "ms-playwright", "chromium-*", "chrome-linux64", "chrome")) |
| 64 | if len(hits) > 0 { |
| 65 | return hits[len(hits)-1] |
| 66 | } |
| 67 | } |
| 68 | if os.Getenv("RASTRILLO_BROWSER_OPTIONAL") != "" { |
| 69 | t.Skip("no chromium found, RASTRILLO_BROWSER_OPTIONAL set: SKIPPED, not passed") |
| 70 | } |
| 71 | t.Fatal("no chromium found: set RASTRILLO_CHROME, or RASTRILLO_BROWSER_OPTIONAL to skip deliberately") |
| 72 | return "" |
| 73 | } |
| 74 | |
| 75 | // consentRig runs connect, a fake Home, a fake directory and a fake client on |
| 76 | // separate 127.0.0.1 ports. The browser reaches them through .test names mapped |
| 77 | // to 127.0.0.1, because Home's assertions refuse IP-address origins; that also |
| 78 | // makes connect and the client cross-site, as they are in production. |
| 79 | type consentRig struct { |
| 80 | t *testing.T |
| 81 | origin string |
| 82 | clientOrigin string |
| 83 | store *db.DB |
| 84 | handler http.Handler |
| 85 | mu sync.Mutex |
| 86 | asks []url.Values |
| 87 | origins []string |
| 88 | calls []clientCall |
| 89 | |
| 90 | // finalOrigin, when set, is where the client's callback redirects on to, |
| 91 | // the way Equipo hands a person on to Base after connecting. |
| 92 | finalOrigin string |
| 93 | finals []clientCall |
| 94 | } |
| 95 | |
| 96 | type clientCall struct { |
| 97 | query url.Values |
| 98 | referer string |
| 99 | } |
| 100 | |
| 101 | func quietTLS(handler http.Handler) *httptest.Server { |
| 102 | server := httptest.NewUnstartedServer(handler) |
| 103 | server.Config.ErrorLog = log.New(io.Discard, "", 0) |
| 104 | return server |
| 105 | } |
| 106 | |
| 107 | // publicOrigin names a listener the way the browser will reach it. |
| 108 | func publicOrigin(name string, server *httptest.Server) string { |
| 109 | _, port, _ := net.SplitHostPort(server.Listener.Addr().String()) |
| 110 | return "https://" + name + ":" + port |
| 111 | } |
| 112 | |
| 113 | func newConsentRig(t *testing.T) *consentRig { |
| 114 | t.Helper() |
| 115 | return newConsentRigAt(t, "client.example.test", "") |
| 116 | } |
| 117 | |
| 118 | // newOnwardRig models Equipo, whose callback redirects on to Base. Both share a |
| 119 | // site with connect, as *.oficina.works do in production; that matters, because |
| 120 | // WebKit stops holding a form's redirects to form-action once they cross sites. |
| 121 | func newOnwardRig(t *testing.T) *consentRig { |
| 122 | t.Helper() |
| 123 | return newConsentRigAt(t, "equipo.oficina.test", "base.oficina.test") |
| 124 | } |
| 125 | |
| 126 | func newConsentRigAt(t *testing.T, clientHost, finalHost string) *consentRig { |
| 127 | t.Helper() |
| 128 | rig := &consentRig{t: t} |
| 129 | key, err := family.Generate() |
| 130 | if err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | |
| 134 | fakeClient := quietTLS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 135 | if r.URL.Path != "/callback" { |
| 136 | http.NotFound(w, r) |
| 137 | return |
| 138 | } |
| 139 | rig.mu.Lock() |
| 140 | rig.calls = append(rig.calls, clientCall{r.URL.Query(), r.Header.Get("Referer")}) |
| 141 | rig.mu.Unlock() |
| 142 | if rig.finalOrigin != "" { |
| 143 | http.Redirect(w, r, rig.finalOrigin+"/done?from=client", http.StatusSeeOther) |
| 144 | return |
| 145 | } |
| 146 | w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| 147 | _, _ = io.WriteString(w, "client callback") |
| 148 | })) |
| 149 | rig.clientOrigin = publicOrigin(clientHost, fakeClient) |
| 150 | |
| 151 | if finalHost != "" { |
| 152 | final := quietTLS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 153 | if r.URL.Path != "/done" { |
| 154 | http.NotFound(w, r) |
| 155 | return |
| 156 | } |
| 157 | rig.mu.Lock() |
| 158 | rig.finals = append(rig.finals, clientCall{r.URL.Query(), r.Header.Get("Referer")}) |
| 159 | rig.mu.Unlock() |
| 160 | w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| 161 | _, _ = io.WriteString(w, "final page") |
| 162 | })) |
| 163 | rig.finalOrigin = publicOrigin(finalHost, final) |
| 164 | final.StartTLS() |
| 165 | t.Cleanup(final.Close) |
| 166 | } |
| 167 | fakeClient.StartTLS() |
| 168 | t.Cleanup(fakeClient.Close) |
| 169 | |
| 170 | var connect http.Handler |
| 171 | service := quietTLS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 172 | if r.Method == http.MethodPost && r.URL.Path == "/oauth/authorize" { |
| 173 | rig.mu.Lock() |
| 174 | rig.origins = append(rig.origins, r.Header.Get("Origin")) |
| 175 | rig.mu.Unlock() |
| 176 | } |
| 177 | connect.ServeHTTP(w, r) |
| 178 | })) |
| 179 | rig.origin = publicOrigin("connect.oficina.test", service) |
| 180 | |
| 181 | // The fake Home models the one rule that matters here: max_age=300 makes the |
| 182 | // person authenticate now, and without it their old Home session is reused. |
| 183 | var homeOrigin string |
| 184 | home := quietTLS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 185 | if r.URL.Path != "/authorize" { |
| 186 | http.NotFound(w, r) |
| 187 | return |
| 188 | } |
| 189 | q := r.URL.Query() |
| 190 | rig.mu.Lock() |
| 191 | rig.asks = append(rig.asks, q) |
| 192 | rig.mu.Unlock() |
| 193 | now := time.Now().Unix() |
| 194 | authTime := now - int64((2*time.Hour)/time.Second) |
| 195 | if q.Get("max_age") == "300" { |
| 196 | authTime = now |
| 197 | } |
| 198 | id, err := assertion.RandomID() |
| 199 | if err != nil { |
| 200 | http.Error(w, "assertion id", 500) |
| 201 | return |
| 202 | } |
| 203 | proof, err := assertion.Sign(key, assertion.Claims{Version: 1, Issuer: homeOrigin, Audience: rig.origin, Subject: browserSubject, KeyID: "key", ID: id, Nonce: q.Get("nonce"), IssuedAt: now, ExpiresAt: now + 120, AuthTime: authTime}) |
| 204 | if err != nil { |
| 205 | http.Error(w, "assertion", 500) |
| 206 | return |
| 207 | } |
| 208 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 209 | fmt.Fprintf(w, `<!doctype html><form method="post" action="%s/auth/assertion"><input type="hidden" name="assertion" value="%s"></form><script>document.forms[0].submit()</script>`, html.EscapeString(rig.origin), html.EscapeString(proof)) |
| 210 | })) |
| 211 | homeOrigin = publicOrigin("id.oficina.test", home) |
| 212 | home.StartTLS() |
| 213 | t.Cleanup(home.Close) |
| 214 | |
| 215 | const appOrigin = "https://notes.example.test" |
| 216 | directory := quietTLS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 217 | w.Header().Set("Content-Type", "application/json") |
| 218 | _ = json.NewEncoder(w).Encode(map[string]any{"teams": []DirectoryTeam{{ID: "acme", Name: "Acme", Apps: []DirectoryApp{{App: "memoria", Origin: appOrigin}}}}}) |
| 219 | })) |
| 220 | directory.StartTLS() |
| 221 | t.Cleanup(directory.Close) |
| 222 | |
| 223 | // Clients arrive as JSON, the way the deployed configuration supplies them. |
| 224 | redirect := rig.clientOrigin + "/callback" |
| 225 | raw := fmt.Sprintf(`[{"id":%q,"name":"Base","redirects":[%q],"first_party":true},{"id":%q,"name":"Third Party Host","redirects":[%q]}]`, firstPartyID, redirect, thirdPartyID, redirect) |
| 226 | var clients []grant.Client |
| 227 | if err := json.Unmarshal([]byte(raw), &clients); err != nil { |
| 228 | t.Fatal(err) |
| 229 | } |
| 230 | |
| 231 | registry, err := access.NewRegistry(access.Operation{Name: "notes_create", Description: "Create a note", Scope: "notes:write", Idempotent: true, |
| 232 | Input: json.RawMessage(`{"type":"object","required":["team"],"properties":{"team":{"type":"string"}},"additionalProperties":false}`), |
| 233 | Output: json.RawMessage(`{"type":"object"}`), |
| 234 | Invoke: func(context.Context, access.Principal, json.RawMessage) (any, error) { return map[string]any{}, nil }}) |
| 235 | if err != nil { |
| 236 | t.Fatal(err) |
| 237 | } |
| 238 | contracts := registry.List(access.Principal{Subject: browserSubject, Teams: []string{"acme"}, Scopes: []string{"notes:write"}}) |
| 239 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 240 | rig.store, err = db.Open(filepath.Join(t.TempDir(), "connect.db"), logger) |
| 241 | if err != nil { |
| 242 | t.Fatal(err) |
| 243 | } |
| 244 | t.Cleanup(func() { rig.store.Close() }) |
| 245 | server, err := New(t.Context(), Config{Origin: rig.origin, HomeIssuer: homeOrigin, ConsumerID: "agent-access", HomeKeys: map[string]string{"key": base64.StdEncoding.EncodeToString(key.SignPub())}, Directory: directory.URL, DirectoryToken: strings.Repeat("t", 32), DEK: []byte(strings.Repeat("d", 32)), Transport: directory.Client().Transport, Clients: clients, Routes: []access.Route{{Team: "acme", Resource: appOrigin + "/api/v1", Operations: contracts}}}, rig.store, logger) |
| 246 | if err != nil { |
| 247 | t.Fatal(err) |
| 248 | } |
| 249 | connect = server.Handler |
| 250 | rig.handler = server.Handler |
| 251 | service.StartTLS() |
| 252 | t.Cleanup(service.Close) |
| 253 | return rig |
| 254 | } |
| 255 | |
| 256 | func (r *consentRig) authorizeURL(clientID string) string { |
| 257 | q := url.Values{"client_id": {clientID}, "redirect_uri": {r.clientOrigin + "/callback"}, "response_type": {"code"}, "code_challenge": {"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"}, "code_challenge_method": {"S256"}, "resource": {r.origin + "/mcp"}, "scope": {"notes:write"}, "state": {browserState}} |
| 258 | return r.origin + "/oauth/authorize?" + q.Encode() |
| 259 | } |
| 260 | |
| 261 | // ageSignIn makes the connect session's Home authentication look old. |
| 262 | func (r *consentRig) ageSignIn(age time.Duration) { |
| 263 | r.t.Helper() |
| 264 | if _, err := r.store.Writer().Exec("UPDATE sessions SET auth_time=?", time.Now().Add(-age).UTC().Format(time.RFC3339)); err != nil { |
| 265 | r.t.Fatal(err) |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | func (r *consentRig) homeAsks() []url.Values { |
| 270 | r.mu.Lock() |
| 271 | defer r.mu.Unlock() |
| 272 | return append([]url.Values{}, r.asks...) |
| 273 | } |
| 274 | |
| 275 | func (r *consentRig) clientCalls() []clientCall { |
| 276 | r.mu.Lock() |
| 277 | defer r.mu.Unlock() |
| 278 | return append([]clientCall{}, r.calls...) |
| 279 | } |
| 280 | |
| 281 | func (r *consentRig) postedOrigins() []string { |
| 282 | r.mu.Lock() |
| 283 | defer r.mu.Unlock() |
| 284 | return append([]string{}, r.origins...) |
| 285 | } |
| 286 | |
| 287 | // consentBrowser is one Chromium with its own empty profile. |
| 288 | type consentBrowser struct { |
| 289 | t *testing.T |
| 290 | rig *consentRig |
| 291 | ctx context.Context |
| 292 | mu sync.Mutex |
| 293 | logs []string |
| 294 | } |
| 295 | |
| 296 | func (r *consentRig) browser(t *testing.T) *consentBrowser { |
| 297 | t.Helper() |
| 298 | options := append(append([]chromedp.ExecAllocatorOption{}, chromedp.DefaultExecAllocatorOptions[:]...), chromedp.ExecPath(chromePath(t)), chromedp.NoSandbox, chromedp.Flag("ignore-certificate-errors", true), chromedp.Flag("host-resolver-rules", "MAP *.test 127.0.0.1"), chromedp.Flag("disable-dev-shm-usage", true)) |
| 299 | allocator, stopAllocator := chromedp.NewExecAllocator(context.Background(), options...) |
| 300 | t.Cleanup(stopAllocator) |
| 301 | ctx, stop := chromedp.NewContext(allocator) |
| 302 | t.Cleanup(stop) |
| 303 | b := &consentBrowser{t: t, rig: r, ctx: ctx} |
| 304 | chromedp.ListenTarget(ctx, func(event any) { |
| 305 | if entry, ok := event.(*cdplog.EventEntryAdded); ok { |
| 306 | b.mu.Lock() |
| 307 | b.logs = append(b.logs, entry.Entry.Text) |
| 308 | b.mu.Unlock() |
| 309 | } |
| 310 | }) |
| 311 | if err := chromedp.Run(ctx, cdplog.Enable(), network.Enable()); err != nil { |
| 312 | t.Fatalf("start browser: %v", err) |
| 313 | } |
| 314 | return b |
| 315 | } |
| 316 | |
| 317 | // state describes where the browser is, for failure messages. |
| 318 | func (b *consentBrowser) state() string { |
| 319 | ctx, cancel := context.WithTimeout(b.ctx, 3*time.Second) |
| 320 | defer cancel() |
| 321 | var location, body string |
| 322 | _ = chromedp.Run(ctx, chromedp.Location(&location), chromedp.Evaluate(`document.body ? document.body.innerText : ""`, &body)) |
| 323 | b.mu.Lock() |
| 324 | defer b.mu.Unlock() |
| 325 | return fmt.Sprintf("at %s\npage: %s\nconsole: %s\nposted Origin: %q", location, body, strings.Join(b.logs, " | "), b.rig.postedOrigins()) |
| 326 | } |
| 327 | |
| 328 | func (b *consentBrowser) run(what string, actions ...chromedp.Action) { |
| 329 | b.t.Helper() |
| 330 | ctx, cancel := context.WithTimeout(b.ctx, browserTimeout) |
| 331 | defer cancel() |
| 332 | if err := chromedp.Run(ctx, actions...); err != nil { |
| 333 | b.t.Fatalf("%s: %v\n%s", what, err, b.state()) |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | // openConsent walks through sign-in and stops on the consent page. |
| 338 | func (b *consentBrowser) openConsent(clientID string) { |
| 339 | b.t.Helper() |
| 340 | b.run("open consent page", chromedp.Navigate(b.rig.authorizeURL(clientID)), chromedp.WaitVisible(consentButton, chromedp.ByQuery)) |
| 341 | } |
| 342 | |
| 343 | func (b *consentBrowser) click(selector string) { |
| 344 | b.t.Helper() |
| 345 | b.run("press "+selector, chromedp.Click(selector, chromedp.ByQuery)) |
| 346 | } |
| 347 | |
| 348 | // landOnClient waits for the browser to arrive at the client's redirect URI. |
| 349 | func (b *consentBrowser) landOnClient() clientCall { |
| 350 | b.t.Helper() |
| 351 | b.landOn(b.rig.clientOrigin+"/callback", "client callback") |
| 352 | calls := b.rig.clientCalls() |
| 353 | if len(calls) != 1 { |
| 354 | b.t.Fatalf("client saw %d callbacks, want 1", len(calls)) |
| 355 | } |
| 356 | return calls[0] |
| 357 | } |
| 358 | |
| 359 | // landOn waits for the browser to show a page at prefix that contains text. |
| 360 | func (b *consentBrowser) landOn(prefix, text string) { |
| 361 | b.t.Helper() |
| 362 | deadline := time.Now().Add(browserTimeout) |
| 363 | for time.Now().Before(deadline) { |
| 364 | var location, body string |
| 365 | ctx, cancel := context.WithTimeout(b.ctx, 3*time.Second) |
| 366 | err := chromedp.Run(ctx, chromedp.Location(&location), chromedp.Evaluate(`document.body ? document.body.innerText : ""`, &body)) |
| 367 | cancel() |
| 368 | if err == nil && strings.HasPrefix(location, prefix) && strings.Contains(body, text) { |
| 369 | return |
| 370 | } |
| 371 | time.Sleep(50 * time.Millisecond) |
| 372 | } |
| 373 | b.t.Fatalf("browser never reached %s\n%s", prefix, b.state()) |
| 374 | } |
| 375 | |
| 376 | // landOnFinal waits for the browser to follow the client on to the third |
| 377 | // origin, and returns what the client was sent before it redirected. |
| 378 | func (b *consentBrowser) landOnFinal() clientCall { |
| 379 | b.t.Helper() |
| 380 | b.landOn(b.rig.finalOrigin+"/done", "final page") |
| 381 | b.rig.mu.Lock() |
| 382 | finals := append([]clientCall{}, b.rig.finals...) |
| 383 | b.rig.mu.Unlock() |
| 384 | calls := b.rig.clientCalls() |
| 385 | if len(calls) != 1 || len(finals) != 1 { |
| 386 | b.t.Fatalf("client saw %d callbacks and the final page %d visits, want 1 each", len(calls), len(finals)) |
| 387 | } |
| 388 | // The code was in the client's URL; the page after it must not learn it. |
| 389 | if finals[0].referer != "" { |
| 390 | b.t.Fatalf("final page received a referrer: %q", finals[0].referer) |
| 391 | } |
| 392 | return calls[0] |
| 393 | } |
| 394 | |
| 395 | func wantCode(t *testing.T, rig *consentRig, call clientCall) { |
| 396 | t.Helper() |
| 397 | if call.query.Get("code") == "" || call.query.Get("error") != "" || call.query.Get("state") != browserState || call.query.Get("iss") != rig.origin { |
| 398 | t.Fatalf("callback query %v", call.query) |
| 399 | } |
| 400 | if call.referer != "" { |
| 401 | t.Fatalf("consent page leaked a referrer to the client: %q", call.referer) |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | func wantRefused(t *testing.T, rig *consentRig, call clientCall, code string) { |
| 406 | t.Helper() |
| 407 | if call.query.Get("error") != code || call.query.Get("code") != "" || call.query.Get("state") != browserState || call.query.Get("iss") != rig.origin { |
| 408 | t.Fatalf("callback query %v, want error %s", call.query, code) |
| 409 | } |
| 410 | if call.referer != "" { |
| 411 | t.Fatalf("consent page leaked a referrer to the client: %q", call.referer) |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | func TestBrowserAllowLandsOnClientWithCode(t *testing.T) { |
| 416 | rig := newConsentRig(t) |
| 417 | b := rig.browser(t) |
| 418 | b.openConsent(thirdPartyID) |
| 419 | if calls := rig.clientCalls(); len(calls) != 0 { |
| 420 | t.Fatalf("client called before consent: %v", calls) |
| 421 | } |
| 422 | b.click(consentButton) |
| 423 | wantCode(t, rig, b.landOnClient()) |
| 424 | if origins := rig.postedOrigins(); len(origins) != 1 || origins[0] != rig.origin { |
| 425 | t.Fatalf("form posted Origin %q, want %q", origins, rig.origin) |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | // A client that redirects on after its callback, as Equipo does to Base, sends |
| 430 | // the browser to a third origin the consent page's form-action cannot name. |
| 431 | // Browsers check form-action along a form's whole redirect chain, so connect |
| 432 | // answers the form with a page that moves the browser on, not a redirect. |
| 433 | func TestBrowserAllowFollowsAClientThatRedirectsOn(t *testing.T) { |
| 434 | for _, tc := range []struct { |
| 435 | name, button string |
| 436 | want func(*testing.T, *consentRig, clientCall) |
| 437 | }{ |
| 438 | {"allow", consentButton, wantCode}, |
| 439 | {"cancel", cancelButton, func(t *testing.T, rig *consentRig, call clientCall) { wantRefused(t, rig, call, "access_denied") }}, |
| 440 | } { |
| 441 | t.Run(tc.name, func(t *testing.T) { |
| 442 | rig := newOnwardRig(t) |
| 443 | b := rig.browser(t) |
| 444 | b.openConsent(firstPartyID) |
| 445 | b.click(tc.button) |
| 446 | tc.want(t, rig, b.landOnFinal()) |
| 447 | }) |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | func TestBrowserCancelLandsOnClientWithRefusal(t *testing.T) { |
| 452 | rig := newConsentRig(t) |
| 453 | b := rig.browser(t) |
| 454 | b.openConsent(thirdPartyID) |
| 455 | b.click(cancelButton) |
| 456 | wantRefused(t, rig, b.landOnClient(), "access_denied") |
| 457 | } |
| 458 | |
| 459 | func TestBrowserExpiredConsentCookieGoesBackToClient(t *testing.T) { |
| 460 | rig := newConsentRig(t) |
| 461 | b := rig.browser(t) |
| 462 | b.openConsent(thirdPartyID) |
| 463 | b.run("expire consent cookie", network.DeleteCookies(consentCookie).WithURL(rig.origin+"/")) |
| 464 | b.click(consentButton) |
| 465 | wantRefused(t, rig, b.landOnClient(), "access_denied") |
| 466 | } |
| 467 | |
| 468 | func TestBrowserStaleSignInGoesBackToClient(t *testing.T) { |
| 469 | rig := newConsentRig(t) |
| 470 | b := rig.browser(t) |
| 471 | b.openConsent(thirdPartyID) |
| 472 | rig.ageSignIn(6 * time.Minute) |
| 473 | b.click(consentButton) |
| 474 | wantRefused(t, rig, b.landOnClient(), "access_denied") |
| 475 | } |
| 476 | |
| 477 | func TestBrowserFirstPartyReusesHomeSessionButStillAsksConsent(t *testing.T) { |
| 478 | rig := newConsentRig(t) |
| 479 | b := rig.browser(t) |
| 480 | b.openConsent(firstPartyID) |
| 481 | asks := rig.homeAsks() |
| 482 | if len(asks) != 1 || asks[0].Has("max_age") { |
| 483 | t.Fatalf("first-party sign-in forced fresh: %v", asks) |
| 484 | } |
| 485 | if calls := rig.clientCalls(); len(calls) != 0 { |
| 486 | t.Fatalf("first-party client skipped the consent page: %v", calls) |
| 487 | } |
| 488 | b.click(consentButton) |
| 489 | wantCode(t, rig, b.landOnClient()) |
| 490 | } |
| 491 | |
| 492 | func TestBrowserFirstPartyKeepsAnOlderConnectSession(t *testing.T) { |
| 493 | rig := newConsentRig(t) |
| 494 | b := rig.browser(t) |
| 495 | b.openConsent(firstPartyID) |
| 496 | rig.ageSignIn(30 * time.Minute) |
| 497 | b.openConsent(firstPartyID) |
| 498 | if asks := rig.homeAsks(); len(asks) != 1 { |
| 499 | t.Fatalf("first-party client went back to Home: %v", asks) |
| 500 | } |
| 501 | b.click(consentButton) |
| 502 | wantCode(t, rig, b.landOnClient()) |
| 503 | } |
| 504 | |
| 505 | func TestBrowserOtherClientsStillSignInFresh(t *testing.T) { |
| 506 | rig := newConsentRig(t) |
| 507 | b := rig.browser(t) |
| 508 | b.openConsent(thirdPartyID) |
| 509 | asks := rig.homeAsks() |
| 510 | if len(asks) != 1 || asks[0].Get("max_age") != "300" { |
| 511 | t.Fatalf("third-party sign-in was not forced fresh: %v", asks) |
| 512 | } |
| 513 | rig.ageSignIn(6 * time.Minute) |
| 514 | b.openConsent(thirdPartyID) |
| 515 | asks = rig.homeAsks() |
| 516 | if len(asks) != 2 || asks[1].Get("max_age") != "300" { |
| 517 | t.Fatalf("aged session reused for a third-party client: %v", asks) |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | // A session earned through the first-party door must not open another client's. |
| 522 | func TestBrowserFirstPartySessionDoesNotCarryOverToOtherClients(t *testing.T) { |
| 523 | rig := newConsentRig(t) |
| 524 | b := rig.browser(t) |
| 525 | b.openConsent(firstPartyID) |
| 526 | b.openConsent(thirdPartyID) |
| 527 | asks := rig.homeAsks() |
| 528 | if len(asks) != 2 || asks[0].Has("max_age") || asks[1].Get("max_age") != "300" { |
| 529 | t.Fatalf("first-party session satisfied a third-party client: %v", asks) |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | // Which door a sign-in takes is decided from the request it will return to. |
| 534 | func TestSignInForcesFreshExceptForAFirstPartyClient(t *testing.T) { |
| 535 | rig := newConsentRig(t) |
| 536 | local := func(raw string) string { return strings.TrimPrefix(raw, rig.origin) } |
| 537 | first := local(rig.authorizeURL(firstPartyID)) |
| 538 | for _, tc := range []struct { |
| 539 | name, returnTo string |
| 540 | fresh bool |
| 541 | }{ |
| 542 | {"first-party client", first, false}, |
| 543 | {"client with no first_party field", local(rig.authorizeURL(thirdPartyID)), true}, |
| 544 | {"Oficina CLI", local(rig.authorizeURL(client.ClientID)), true}, |
| 545 | {"unknown client", local(rig.authorizeURL("nobody")), true}, |
| 546 | {"first-party client with another redirect", strings.ReplaceAll(first, "client.example.test", "evil.example.test"), true}, |
| 547 | {"first-party client named twice", first + "&client_id=" + thirdPartyID, true}, |
| 548 | {"connections page", "/connections", true}, |
| 549 | } { |
| 550 | t.Run(tc.name, func(t *testing.T) { |
| 551 | r := httptest.NewRequest("GET", rig.origin+"/auth/start?"+url.Values{"return_to": {tc.returnTo}}.Encode(), nil) |
| 552 | w := httptest.NewRecorder() |
| 553 | rig.handler.ServeHTTP(w, r) |
| 554 | if w.Code != 303 { |
| 555 | t.Fatalf("status %d: %s", w.Code, w.Body) |
| 556 | } |
| 557 | target, err := url.Parse(w.Header().Get("Location")) |
| 558 | if err != nil || target.Path != "/authorize" { |
| 559 | t.Fatalf("redirected to %q", w.Header().Get("Location")) |
| 560 | } |
| 561 | if got := target.Query().Get("max_age"); tc.fresh && got != "300" || !tc.fresh && target.Query().Has("max_age") { |
| 562 | t.Fatalf("max_age %q, want fresh=%v", got, tc.fresh) |
| 563 | } |
| 564 | }) |
| 565 | } |
| 566 | t.Run("no return path", func(t *testing.T) { |
| 567 | w := httptest.NewRecorder() |
| 568 | rig.handler.ServeHTTP(w, httptest.NewRequest("GET", rig.origin+"/auth/start", nil)) |
| 569 | target, err := url.Parse(w.Header().Get("Location")) |
| 570 | if err != nil || target.Query().Get("max_age") != "300" { |
| 571 | t.Fatalf("%d %q", w.Code, w.Header().Get("Location")) |
| 572 | } |
| 573 | }) |
| 574 | } |
| 575 | |