oficina / agent-access Public

Clone
git clone https://amadan.net/oficina/agent-access

Plain git — no account needed to clone.

Download this file

1package grant
2
3import (
4 "context"
5 "database/sql"
6 "encoding/json"
7 "html"
8 "io"
9 "net/http"
10 "net/http/httptest"
11 "net/url"
12 "regexp"
13 "strings"
14 "testing"
15 "time"
16)
17
18const (
19 baseRedirect = "https://base.example/callback"
20 otherRedirect = "https://other.example/oauth/done"
21 cliRedirect = "http://127.0.0.1:4567/callback"
22)
23
24var consentClients = []Client{
25 {ID: "oficina-cli", Name: "Oficina CLI", Loopback: true},
26 {ID: "base", Name: "Base", Redirects: []string{baseRedirect}, FirstParty: true},
27 {ID: "other", Name: "Other Host", Redirects: []string{otherRedirect}},
28}
29
30// consentServer's sessions are named by the Test-Session header: "fresh" has
31// just signed in, "older" signed in a while ago, and "stranger" is someone else.
32func consentServer(t *testing.T, clients []Client, reuse bool) (*Server, *httptest.Server) {
33 t.Helper()
34 db, err := sql.Open("sqlite", t.TempDir()+"/grants.sqlite")
35 if err != nil {
36 t.Fatal(err)
37 }
38 db.SetMaxOpenConns(1)
39 t.Cleanup(func() { db.Close() })
40 store, err := NewStore(context.Background(), db)
41 if err != nil {
42 t.Fatal(err)
43 }
44 var handler http.Handler
45 ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler.ServeHTTP(w, r) }))
46 t.Cleanup(ts.Close)
47 cfg := consentConfig(ts.URL, store, clients)
48 if reuse {
49 cfg.SessionSubject = func(r *http.Request) string {
50 switch r.Header.Get("Test-Session") {
51 case "fresh", "older":
52 return "opaque-person"
53 case "stranger":
54 return "someone-else"
55 }
56 return ""
57 }
58 }
59 s, err := NewServer(cfg)
60 if err != nil {
61 t.Fatal(err)
62 }
63 handler = s.Handler()
64 return s, ts
65}
66
67func consentConfig(origin string, store *Store, clients []Client) Config {
68 return Config{IdentityIssuer: "https://home.example", Origin: origin, Resource: origin + "/mcp", Store: store, ConsentKey: []byte(strings.Repeat("k", 32)), Clients: clients, Scopes: map[string]string{"notes:write": "Create and edit notes"}, Subject: func(r *http.Request) string {
69 switch r.Header.Get("Test-Session") {
70 case "fresh":
71 return "opaque-person"
72 case "stranger":
73 return "someone-else"
74 }
75 return ""
76 }, Teams: func(context.Context, string) ([]Team, error) {
77 return []Team{{ID: "acme", Name: "Acme"}}, nil
78 }, SignInPath: "/signin"}
79}
80
81func consentURL(base, client, redirect string) string {
82 return authorizeURL(base, url.Values{"client_id": {client}, "redirect_uri": {redirect}})
83}
84
85func noRedirects(ts *httptest.Server) *http.Client {
86 c := *ts.Client()
87 c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
88 return &c
89}
90
91// consentPage loads the consent page and returns its ticket and cookies.
92func consentPage(t *testing.T, ts *httptest.Server, client, redirect, session string) (string, []*http.Cookie) {
93 t.Helper()
94 resp, body := fetchAs(t, ts, consentURL(ts.URL, client, redirect), session)
95 if resp.StatusCode != 200 {
96 t.Fatalf("consent page %d: %s", resp.StatusCode, body)
97 }
98 m := regexp.MustCompile(`name="ticket" value="([^"]+)"`).FindStringSubmatch(body)
99 if len(m) != 2 {
100 t.Fatal("no ticket on the consent page")
101 }
102 return m[1], resp.Cookies()
103}
104
105func fetchAs(t *testing.T, ts *httptest.Server, raw, session string) (*http.Response, string) {
106 t.Helper()
107 req, _ := http.NewRequest("GET", raw, nil)
108 req.Header.Set("Test-Session", session)
109 resp, err := noRedirects(ts).Do(req)
110 if err != nil {
111 t.Fatal(err)
112 }
113 defer resp.Body.Close()
114 body, _ := io.ReadAll(resp.Body)
115 return resp, string(body)
116}
117
118type answer struct {
119 ticket, decision, session string
120 origins []string
121 cookies []*http.Cookie
122}
123
124func (a answer) post(t *testing.T, ts *httptest.Server) (*http.Response, string) {
125 t.Helper()
126 form := url.Values{"ticket": {a.ticket}, "decision": {a.decision}, "team": {"acme"}}
127 if a.decision == "" {
128 form.Del("decision")
129 }
130 req, _ := http.NewRequest("POST", ts.URL+"/oauth/authorize", strings.NewReader(form.Encode()))
131 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
132 req.Header.Set("Test-Session", a.session)
133 for _, origin := range a.origins {
134 req.Header.Add("Origin", origin)
135 }
136 for _, cookie := range a.cookies {
137 req.AddCookie(cookie)
138 }
139 resp, err := noRedirects(ts).Do(req)
140 if err != nil {
141 t.Fatal(err)
142 }
143 defer resp.Body.Close()
144 body, _ := io.ReadAll(resp.Body)
145 return resp, string(body)
146}
147
148func wantPlainRefusal(t *testing.T, resp *http.Response, body string, status int) {
149 t.Helper()
150 if resp.StatusCode != status || resp.Header.Get("Location") != "" {
151 t.Fatalf("status %d location %q, want %d and no redirect", resp.StatusCode, resp.Header.Get("Location"), status)
152 }
153 if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/html") || strings.Contains(body, `{"error"`) {
154 t.Fatalf("a person was shown %q: %s", resp.Header.Get("Content-Type"), body)
155 }
156}
157
158var (
159 handoffRefresh = regexp.MustCompile(`<meta http-equiv="refresh" content="0;url=([^"]*)">`)
160 handoffLink = regexp.MustCompile(`<a href="([^"]*)">([^<]*)</a>`)
161 htmlEntity = regexp.MustCompile(`&(amp|#[0-9]+);`)
162)
163
164// wantHandoff checks that an answer to the consent form is a page that sends
165// the browser on, not a redirect. Browsers hold a form's whole redirect chain to
166// form-action, so a client that redirects again would strand the person on the
167// consent page. It returns where the page sends the browser.
168func wantHandoff(t *testing.T, resp *http.Response, body string) *url.URL {
169 t.Helper()
170 if resp.StatusCode != 200 || resp.Header.Get("Location") != "" {
171 t.Fatalf("status %d location %q, want a 200 hand-off page", resp.StatusCode, resp.Header.Get("Location"))
172 }
173 if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/html") {
174 t.Fatalf("content type %q", resp.Header.Get("Content-Type"))
175 }
176 // The page's URL carries the code: it is neither stored nor sent onward.
177 if got := resp.Header.Get("Cache-Control"); got != "no-store" {
178 t.Fatalf("Cache-Control %q", got)
179 }
180 if got := resp.Header.Get("Referrer-Policy"); got != "no-referrer" {
181 t.Fatalf("Referrer-Policy %q", got)
182 }
183 if got := resp.Header.Get("Content-Security-Policy"); got != pageCSP {
184 t.Fatalf("hand-off CSP %q, want %q", got, pageCSP)
185 }
186 for _, inline := range []string{"<script", "<style", " style=", "javascript:"} {
187 if strings.Contains(body, inline) {
188 t.Fatalf("hand-off page has %q: %s", inline, body)
189 }
190 }
191 refresh := handoffRefresh.FindAllStringSubmatch(body, -1)
192 links := handoffLink.FindAllStringSubmatch(body, -1)
193 if len(refresh) != 1 || len(links) != 1 {
194 t.Fatalf("want one refresh and one link: %s", body)
195 }
196 if links[0][2] != handoffText {
197 t.Fatalf("link text %q, want %q", links[0][2], handoffText)
198 }
199 for _, raw := range []string{refresh[0][1], links[0][1]} {
200 if strings.Contains(htmlEntity.ReplaceAllString(raw, ""), "&") {
201 t.Fatalf("unescaped & in %q", raw)
202 }
203 }
204 target := html.UnescapeString(refresh[0][1])
205 if href := html.UnescapeString(links[0][1]); href != target {
206 t.Fatalf("link %q and refresh %q differ", href, target)
207 }
208 dest, err := url.Parse(target)
209 if err != nil || !dest.IsAbs() {
210 t.Fatalf("hand-off to %q", target)
211 }
212 return dest
213}
214
215func wantClientRefusal(t *testing.T, resp *http.Response, body, redirect string) {
216 t.Helper()
217 loc := wantHandoff(t, resp, body)
218 if loc.Scheme+"://"+loc.Host+loc.Path != redirect {
219 t.Fatalf("sent to %q, want %s", loc, redirect)
220 }
221 if q := loc.Query(); q.Get("error") != "access_denied" || q.Get("state") != testState || q.Get("code") != "" || q.Get("iss") == "" {
222 t.Fatalf("refusal query %v", q)
223 }
224}
225
226// wantClientCode checks an approval hands the browser to the client with a code.
227func wantClientCode(t *testing.T, resp *http.Response, body, redirect string) {
228 t.Helper()
229 loc := wantHandoff(t, resp, body)
230 if loc.Scheme+"://"+loc.Host+loc.Path != redirect {
231 t.Fatalf("sent to %q, want %s", loc, redirect)
232 }
233 if q := loc.Query(); q.Get("code") == "" || q.Get("error") != "" || q.Get("state") != testState || q.Get("iss") == "" {
234 t.Fatalf("approval query %v", q)
235 }
236}
237
238func TestConsentAnswersHandTheBrowserOnRatherThanRedirect(t *testing.T) {
239 for _, tc := range []struct{ client, redirect string }{{"other", otherRedirect}, {"base", baseRedirect}, {"oficina-cli", cliRedirect}} {
240 for _, decision := range []string{"approve", "deny"} {
241 t.Run(tc.client+"/"+decision, func(t *testing.T) {
242 _, ts := consentServer(t, consentClients, true)
243 ticket, cookies := consentPage(t, ts, tc.client, tc.redirect, "fresh")
244 resp, body := answer{ticket: ticket, decision: decision, session: "fresh", origins: []string{ts.URL}, cookies: cookies}.post(t, ts)
245 if decision == "deny" {
246 wantClientRefusal(t, resp, body, tc.redirect)
247 return
248 }
249 wantClientCode(t, resp, body, tc.redirect)
250 // The query joins state, iss and code with &, escaped in both places.
251 dest := wantHandoff(t, resp, body).String()
252 escaped := strings.ReplaceAll(dest, "&", "&amp;")
253 if !strings.Contains(body, `content="0;url=`+escaped+`"`) || !strings.Contains(body, `href="`+escaped+`"`) {
254 t.Fatalf("%s not escaped as %s: %s", dest, escaped, body)
255 }
256 })
257 }
258 }
259 // The consent page itself keeps its policy: the form posts only to connect
260 // and this request's client.
261 _, ts := consentServer(t, consentClients, true)
262 resp, _ := fetchAs(t, ts, consentURL(ts.URL, "other", otherRedirect), "fresh")
263 if got := resp.Header.Get("Content-Security-Policy"); got != strings.Replace(pageCSP, "form-action 'self'", "form-action 'self' https://other.example", 1) {
264 t.Fatalf("consent CSP %q", got)
265 }
266}
267
268// A state can hold anything the client likes, and a registered redirect can
269// carry its own query; neither may change where the hand-off page goes.
270func TestHandoffKeepsAHostileStateInsideTheURL(t *testing.T) {
271 const redirect = "https://other.example/oauth/done;v=1?tenant=a"
272 const state = `quote"'<b>&amp;%zz ünï;url=https://evil.example/ + 0;url=x`
273 clients := []Client{{ID: "other", Name: "Other Host", Redirects: []string{redirect}}}
274 for _, decision := range []string{"approve", "deny"} {
275 t.Run(decision, func(t *testing.T) {
276 _, ts := consentServer(t, clients, true)
277 resp, body := fetchAs(t, ts, authorizeURL(ts.URL, url.Values{"client_id": {"other"}, "redirect_uri": {redirect}, "state": {state}}), "fresh")
278 m := regexp.MustCompile(`name="ticket" value="([^"]+)"`).FindStringSubmatch(body)
279 if resp.StatusCode != 200 || len(m) != 2 {
280 t.Fatalf("consent page %d", resp.StatusCode)
281 }
282 resp, body = answer{ticket: m[1], decision: decision, session: "fresh", origins: []string{ts.URL}, cookies: resp.Cookies()}.post(t, ts)
283 dest := wantHandoff(t, resp, body)
284 q := dest.Query()
285 if dest.Scheme != "https" || dest.Host != "other.example" || dest.Path != "/oauth/done;v=1" || q.Get("state") != state || q.Get("tenant") != "a" {
286 t.Fatalf("sent to %q, query %v", dest, q)
287 }
288 if strings.Contains(body, "<b>") || strings.Contains(body, `quote"`) {
289 t.Fatalf("state reached the page unescaped: %s", body)
290 }
291 })
292 }
293}
294
295func TestApproveRefusesAnyOtherOrigin(t *testing.T) {
296 _, ts := consentServer(t, consentClients, true)
297 ticket, cookies := consentPage(t, ts, "other", otherRedirect, "fresh")
298 for name, origins := range map[string][]string{
299 "cross-site": {"https://evil.example"},
300 "null": {"null"},
301 "missing": nil,
302 "trailing": {ts.URL + "/"},
303 "other scheme": {strings.Replace(ts.URL, "https://", "http://", 1)},
304 "repeated": {ts.URL, ts.URL},
305 } {
306 t.Run(name, func(t *testing.T) {
307 resp, body := answer{ticket: ticket, decision: "approve", session: "fresh", origins: origins, cookies: cookies}.post(t, ts)
308 wantPlainRefusal(t, resp, body, 403)
309 })
310 }
311 // None of those spent the ticket: the real origin still connects.
312 resp, body := answer{ticket: ticket, decision: "approve", session: "fresh", origins: []string{ts.URL}, cookies: cookies}.post(t, ts)
313 wantClientCode(t, resp, body, otherRedirect)
314}
315
316func directive(csp, name string) string {
317 for _, part := range strings.Split(csp, ";") {
318 if part = strings.TrimSpace(part); strings.HasPrefix(part, name+" ") {
319 return part
320 }
321 }
322 return ""
323}
324
325func TestConsentFormActionNamesOnlyThisClient(t *testing.T) {
326 _, ts := consentServer(t, consentClients, true)
327 for _, tc := range []struct{ client, redirect, want string }{
328 {"base", baseRedirect, "form-action 'self' https://base.example"},
329 {"other", otherRedirect, "form-action 'self' https://other.example"},
330 {"oficina-cli", cliRedirect, "form-action 'self' http://127.0.0.1:4567"},
331 } {
332 resp, _ := fetchAs(t, ts, consentURL(ts.URL, tc.client, tc.redirect), "fresh")
333 csp := resp.Header.Get("Content-Security-Policy")
334 if got := directive(csp, "form-action"); got != tc.want {
335 t.Fatalf("%s: form-action %q, want %q", tc.client, got, tc.want)
336 }
337 if strings.Contains(csp, "*") {
338 t.Fatalf("%s: wildcard in %q", tc.client, csp)
339 }
340 }
341 // Pages that never redirect off-site keep the strict policy.
342 resp, _ := fetchAs(t, ts, ts.URL+"/connections", "fresh")
343 if got := directive(resp.Header.Get("Content-Security-Policy"), "form-action"); got != "form-action 'self'" {
344 t.Fatalf("connections form-action %q", got)
345 }
346}
347
348func TestRedirectThatCouldWidenThePolicyIsNotRegistered(t *testing.T) {
349 db, err := sql.Open("sqlite", t.TempDir()+"/grants.sqlite")
350 if err != nil {
351 t.Fatal(err)
352 }
353 db.SetMaxOpenConns(1)
354 t.Cleanup(func() { db.Close() })
355 store, err := NewStore(context.Background(), db)
356 if err != nil {
357 t.Fatal(err)
358 }
359 for _, redirect := range []string{"https://*.example/callback", "https://a.example,b.example/callback", "https://a.example;script-src/callback"} {
360 if _, err := NewServer(consentConfig("https://connect.example", store, []Client{{ID: "wide", Name: "Wide", Redirects: []string{redirect}}})); err == nil {
361 t.Fatalf("registered %s", redirect)
362 }
363 }
364}
365
366func TestConsentPageSendsItsOriginButNoReferrerElsewhere(t *testing.T) {
367 _, ts := consentServer(t, consentClients, true)
368 resp, _ := fetchAs(t, ts, consentURL(ts.URL, "other", otherRedirect), "fresh")
369 if got := resp.Header.Get("Referrer-Policy"); got != "same-origin" {
370 t.Fatalf("Referrer-Policy %q", got)
371 }
372}
373
374func TestTrustedTicketRefusalsGoBackToTheClient(t *testing.T) {
375 for name, change := range map[string]func(*answer, *Server){
376 "expired consent cookie": func(a *answer, _ *Server) { a.cookies = nil },
377 "wrong consent cookie": func(a *answer, _ *Server) {
378 a.cookies = []*http.Cookie{{Name: "__Host-oficina-consent", Value: "not-this-ticket"}}
379 },
380 "stale sign-in": func(a *answer, _ *Server) { a.session = "older" },
381 "signed out": func(a *answer, _ *Server) { a.session = "" },
382 "another person": func(a *answer, _ *Server) {
383 a.session = "stranger"
384 },
385 "expired ticket": func(_ *answer, s *Server) {
386 later := time.Now().Add(6 * time.Minute)
387 s.cfg.Store.Now = func() time.Time { return later }
388 },
389 } {
390 for _, decision := range []string{"approve", "deny"} {
391 t.Run(name+"/"+decision, func(t *testing.T) {
392 s, ts := consentServer(t, consentClients, true)
393 ticket, cookies := consentPage(t, ts, "other", otherRedirect, "fresh")
394 a := answer{ticket: ticket, decision: decision, session: "fresh", origins: []string{ts.URL}, cookies: cookies}
395 change(&a, s)
396 resp, body := a.post(t, ts)
397 wantClientRefusal(t, resp, body, otherRedirect)
398 })
399 }
400 }
401}
402
403func TestUntrustedTicketsGetAPlainRefusal(t *testing.T) {
404 s, ts := consentServer(t, consentClients, true)
405 _, cookies := consentPage(t, ts, "other", otherRedirect, "fresh")
406 sealed := func(tk ticket) string {
407 t.Helper()
408 tk.Expires = time.Now().Add(time.Minute).Unix()
409 raw, err := s.seal(tk)
410 if err != nil {
411 t.Fatal(err)
412 }
413 return raw
414 }
415 for name, ticket := range map[string]string{
416 "unreadable": "not-a-ticket",
417 "another purpose": sealed(ticket{Purpose: "revoke", Client: "other", Redirect: otherRedirect, State: testState, Subject: "opaque-person", Nonce: "n"}),
418 "unregistered client": sealed(ticket{Purpose: "authorize", Client: "gone", Redirect: otherRedirect, State: testState, Subject: "opaque-person", Nonce: "n"}),
419 "foreign redirect": sealed(ticket{Purpose: "authorize", Client: "other", Redirect: "https://evil.example/callback", State: testState, Subject: "opaque-person", Nonce: "n"}),
420 } {
421 t.Run(name, func(t *testing.T) {
422 resp, body := answer{ticket: ticket, decision: "approve", session: "fresh", origins: []string{ts.URL}, cookies: cookies}.post(t, ts)
423 wantPlainRefusal(t, resp, body, 403)
424 })
425 }
426 t.Run("incomplete form", func(t *testing.T) {
427 resp, body := answer{ticket: "x", session: "fresh", origins: []string{ts.URL}, cookies: cookies}.post(t, ts)
428 wantPlainRefusal(t, resp, body, 400)
429 })
430 t.Run("unknown client on the way in", func(t *testing.T) {
431 resp, body := fetchAs(t, ts, consentURL(ts.URL, "nobody", otherRedirect), "fresh")
432 wantPlainRefusal(t, resp, body, 400)
433 })
434}
435
436func TestStorageFailureOnTheConsentPathIsNotRawJSON(t *testing.T) {
437 s, ts := consentServer(t, consentClients, true)
438 if err := s.cfg.Store.DB.Close(); err != nil {
439 t.Fatal(err)
440 }
441 resp, body := fetchAs(t, ts, consentURL(ts.URL, "other", otherRedirect), "fresh")
442 wantPlainRefusal(t, resp, body, 503)
443 // Machine clients keep their JSON error.
444 token, err := noRedirects(ts).Post(ts.URL+"/oauth/token", "application/x-www-form-urlencoded", strings.NewReader("grant_type=refresh_token"))
445 if err != nil {
446 t.Fatal(err)
447 }
448 defer token.Body.Close()
449 if token.StatusCode != 503 || !strings.HasPrefix(token.Header.Get("Content-Type"), "application/json") {
450 t.Fatalf("token endpoint %d %q", token.StatusCode, token.Header.Get("Content-Type"))
451 }
452}
453
454func TestSpentTicketGetsAPlainRefusalNotASecondAnswer(t *testing.T) {
455 _, ts := consentServer(t, consentClients, true)
456 ticket, cookies := consentPage(t, ts, "other", otherRedirect, "fresh")
457 a := answer{ticket: ticket, decision: "approve", session: "fresh", origins: []string{ts.URL}, cookies: cookies}
458 first, firstBody := a.post(t, ts)
459 wantClientCode(t, first, firstBody, otherRedirect)
460 resp, body := a.post(t, ts)
461 wantPlainRefusal(t, resp, body, 400)
462}
463
464func TestFirstPartyClientReusesAnExistingSession(t *testing.T) {
465 _, ts := consentServer(t, consentClients, true)
466 ticket, cookies := consentPage(t, ts, "base", baseRedirect, "older")
467 resp, body := answer{ticket: ticket, decision: "approve", session: "older", origins: []string{ts.URL}, cookies: cookies}.post(t, ts)
468 wantClientCode(t, resp, body, baseRedirect)
469}
470
471func TestFirstPartyClientStillNeedsASessionAndConsent(t *testing.T) {
472 _, ts := consentServer(t, consentClients, true)
473 resp, _ := fetchAs(t, ts, consentURL(ts.URL, "base", baseRedirect), "")
474 if resp.StatusCode != 303 || !strings.HasPrefix(resp.Header.Get("Location"), "/signin?") {
475 t.Fatalf("no session: %d %q", resp.StatusCode, resp.Header.Get("Location"))
476 }
477 resp, body := fetchAs(t, ts, consentURL(ts.URL, "base", baseRedirect), "older")
478 if resp.StatusCode != 200 || !strings.Contains(body, "Allow access") || strings.Contains(resp.Header.Get("Location"), "code=") {
479 t.Fatalf("first-party client skipped consent: %d %q", resp.StatusCode, resp.Header.Get("Location"))
480 }
481 ticket, cookies := consentPage(t, ts, "base", baseRedirect, "older")
482 refused, refusedBody := answer{ticket: ticket, decision: "approve", session: "stranger", origins: []string{ts.URL}, cookies: cookies}.post(t, ts)
483 wantClientRefusal(t, refused, refusedBody, baseRedirect)
484}
485
486func TestOtherClientsAreForcedToSignInFresh(t *testing.T) {
487 _, ts := consentServer(t, consentClients, true)
488 for _, tc := range []struct{ client, redirect string }{{"other", otherRedirect}, {"oficina-cli", cliRedirect}} {
489 resp, _ := fetchAs(t, ts, consentURL(ts.URL, tc.client, tc.redirect), "older")
490 if resp.StatusCode != 303 || !strings.HasPrefix(resp.Header.Get("Location"), "/signin?") {
491 t.Fatalf("%s reused an older session: %d %q", tc.client, resp.StatusCode, resp.Header.Get("Location"))
492 }
493 }
494}
495
496func TestMissingFirstPartyFieldStaysStrict(t *testing.T) {
497 var clients []Client
498 raw := `[{"id":"unmarked","name":"Unmarked","redirects":["` + otherRedirect + `"]},{"id":"declined","name":"Declined","redirects":["` + baseRedirect + `"],"first_party":false}]`
499 if err := json.Unmarshal([]byte(raw), &clients); err != nil {
500 t.Fatal(err)
501 }
502 s, ts := consentServer(t, clients, true)
503 for _, c := range clients {
504 if c.FirstParty {
505 t.Fatalf("%s defaulted to first-party", c.ID)
506 }
507 target := consentURL(ts.URL, c.ID, c.Redirects[0])
508 resp, _ := fetchAs(t, ts, target, "older")
509 if resp.StatusCode != 303 || !strings.HasPrefix(resp.Header.Get("Location"), "/signin?") {
510 t.Fatalf("%s reused an older session: %d", c.ID, resp.StatusCode)
511 }
512 if s.ReusesSession(strings.TrimPrefix(target, ts.URL)) {
513 t.Fatalf("%s sign-in would not be forced fresh", c.ID)
514 }
515 }
516}
517
518func TestFirstPartyWithoutASessionReaderStaysStrict(t *testing.T) {
519 s, ts := consentServer(t, consentClients, false)
520 target := consentURL(ts.URL, "base", baseRedirect)
521 resp, _ := fetchAs(t, ts, target, "older")
522 if resp.StatusCode != 303 || !strings.HasPrefix(resp.Header.Get("Location"), "/signin?") {
523 t.Fatalf("reused an older session: %d", resp.StatusCode)
524 }
525 if s.ReusesSession(strings.TrimPrefix(target, ts.URL)) {
526 t.Fatal("sign-in would not be forced fresh")
527 }
528}
529
530func TestReusesSessionReadsOnlyAnExactFirstPartyRequest(t *testing.T) {
531 s, ts := consentServer(t, consentClients, true)
532 exact := strings.TrimPrefix(consentURL(ts.URL, "base", baseRedirect), ts.URL)
533 if !s.ReusesSession(exact) {
534 t.Fatal("first-party authorize request not recognised")
535 }
536 query := strings.TrimPrefix(exact, "/oauth/authorize")
537 for name, returnTo := range map[string]string{
538 "empty": "",
539 "other client": strings.TrimPrefix(consentURL(ts.URL, "other", otherRedirect), ts.URL),
540 "cli": strings.TrimPrefix(consentURL(ts.URL, "oficina-cli", cliRedirect), ts.URL),
541 "unknown client": strings.TrimPrefix(consentURL(ts.URL, "nobody", baseRedirect), ts.URL),
542 "foreign redirect": strings.TrimPrefix(consentURL(ts.URL, "base", "https://evil.example/callback"), ts.URL),
543 "repeated client": exact + "&client_id=other",
544 "another page": "/connections" + query,
545 "encoded path": "/oauth%2Fauthorize" + query,
546 "absolute": "https://evil.example/oauth/authorize" + query,
547 "scheme-relative": "//evil.example/oauth/authorize" + query,
548 "unreadable query": exact + "&bad=%zz",
549 "semicolon in form": exact + ";client_id=other",
550 } {
551 if s.ReusesSession(returnTo) {
552 t.Fatalf("%s: %q treated as first-party", name, returnTo)
553 }
554 }
555}
556