oficina / agent-access Public
Answer the consent form with a hand-off page, not a 303
Pressing Allow access (or Cancel) left the person on the consent page when the client redirected on after its callback, as Equipo does to Base. Browsers hold every hop of a form navigation's redirect chain to the consent page's form-action, which can name only the client's redirect origin, so the hop to Base was refused (Chromium always; WebKit whenever the chain stays same-site, as *.oficina.works does). Every answer to the consent form that goes to the client (approve, deny, and refusals after the ticket is trusted) is now a 200 page with a meta refresh and one fallback link to the same URL. A refresh is a fresh navigation that form-action does not govern, so the CSP stays as strict as before. The page sends no-store and no-referrer because the URL carries the code, uses no inline script or style, and escapes the URL in both attributes. The link text is a placeholder, "Continue", in handoffText for copy review. Authorize-time (GET) refusals and the sign-in and /connections redirects are not form answers and still redirect. A chromedp test now drives the three-origin chain and failed before this change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+310
−62
connection/consent_browser_test.go+91 −9connection/server_test.go+12 −1grant/consent_test.go+114 −22grant/redirect_test.go+24 −8grant/server.go+66 −18grant/server_test.go+3 −4
diff --git a/connection/consent_browser_test.go b/connection/consent_browser_test.go| index c37a5a7..015e485 100644 |
| --- a/connection/consent_browser_test.go |
| +++ b/connection/consent_browser_test.go |
| @@ -86,6 +86,11 @@ type consentRig struct { |
| asks []url.Values |
| origins []string |
| calls []clientCall |
| + |
| + // finalOrigin, when set, is where the client's callback redirects on to, |
| + // the way Equipo hands a person on to Base after connecting. |
| + finalOrigin string |
| + finals []url.Values |
| } |
| type clientCall struct { |
| @@ -106,6 +111,19 @@ func publicOrigin(name string, server *httptest.Server) string { |
| } |
| func newConsentRig(t *testing.T) *consentRig { |
| + t.Helper() |
| + return newConsentRigAt(t, "client.example.test", "") |
| +} |
| + |
| +// newOnwardRig models Equipo, whose callback redirects on to Base. Both share a |
| +// site with connect, as *.oficina.works do in production; that matters, because |
| +// WebKit stops holding a form's redirects to form-action once they cross sites. |
| +func newOnwardRig(t *testing.T) *consentRig { |
| + t.Helper() |
| + return newConsentRigAt(t, "equipo.oficina.test", "base.oficina.test") |
| +} |
| + |
| +func newConsentRigAt(t *testing.T, clientHost, finalHost string) *consentRig { |
| t.Helper() |
| rig := &consentRig{t: t} |
| key, err := family.Generate() |
| @@ -121,10 +139,31 @@ func newConsentRig(t *testing.T) *consentRig { |
| rig.mu.Lock() |
| rig.calls = append(rig.calls, clientCall{r.URL.Query(), r.Header.Get("Referer")}) |
| rig.mu.Unlock() |
| + if rig.finalOrigin != "" { |
| + http.Redirect(w, r, rig.finalOrigin+"/done?from=client", http.StatusSeeOther) |
| + return |
| + } |
| w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| _, _ = io.WriteString(w, "client callback") |
| })) |
| - rig.clientOrigin = publicOrigin("client.example.test", fakeClient) |
| + rig.clientOrigin = publicOrigin(clientHost, fakeClient) |
| + |
| + if finalHost != "" { |
| + final := quietTLS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/done" { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + rig.mu.Lock() |
| + rig.finals = append(rig.finals, r.URL.Query()) |
| + rig.mu.Unlock() |
| + w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| + _, _ = io.WriteString(w, "final page") |
| + })) |
| + rig.finalOrigin = publicOrigin(finalHost, final) |
| + final.StartTLS() |
| + t.Cleanup(final.Close) |
| + } |
| fakeClient.StartTLS() |
| t.Cleanup(fakeClient.Close) |
| @@ -308,6 +347,17 @@ func (b *consentBrowser) click(selector string) { |
| // landOnClient waits for the browser to arrive at the client's redirect URI. |
| func (b *consentBrowser) landOnClient() clientCall { |
| + b.t.Helper() |
| + b.landOn(b.rig.clientOrigin+"/callback", "client callback") |
| + calls := b.rig.clientCalls() |
| + if len(calls) != 1 { |
| + b.t.Fatalf("client saw %d callbacks, want 1", len(calls)) |
| + } |
| + return calls[0] |
| +} |
| + |
| +// landOn waits for the browser to show a page at prefix that contains text. |
| +func (b *consentBrowser) landOn(prefix, text string) { |
| b.t.Helper() |
| deadline := time.Now().Add(browserTimeout) |
| for time.Now().Before(deadline) { |
| @@ -315,17 +365,27 @@ func (b *consentBrowser) landOnClient() clientCall { |
| ctx, cancel := context.WithTimeout(b.ctx, 3*time.Second) |
| err := chromedp.Run(ctx, chromedp.Location(&location), chromedp.Evaluate(`document.body ? document.body.innerText : ""`, &body)) |
| cancel() |
| - if err == nil && strings.HasPrefix(location, b.rig.clientOrigin+"/callback") && strings.Contains(body, "client callback") { |
| - calls := b.rig.clientCalls() |
| - if len(calls) != 1 { |
| - b.t.Fatalf("client saw %d callbacks, want 1", len(calls)) |
| - } |
| - return calls[0] |
| + if err == nil && strings.HasPrefix(location, prefix) && strings.Contains(body, text) { |
| + return |
| } |
| time.Sleep(50 * time.Millisecond) |
| } |
| - b.t.Fatalf("browser never reached the client's redirect\n%s", b.state()) |
| - return clientCall{} |
| + b.t.Fatalf("browser never reached %s\n%s", prefix, b.state()) |
| +} |
| + |
| +// landOnFinal waits for the browser to follow the client on to the third |
| +// origin, and returns what the client was sent before it redirected. |
| +func (b *consentBrowser) landOnFinal() clientCall { |
| + b.t.Helper() |
| + b.landOn(b.rig.finalOrigin+"/done", "final page") |
| + b.rig.mu.Lock() |
| + finals := len(b.rig.finals) |
| + b.rig.mu.Unlock() |
| + calls := b.rig.clientCalls() |
| + if len(calls) != 1 || finals != 1 { |
| + b.t.Fatalf("client saw %d callbacks and the final page %d visits, want 1 each", len(calls), finals) |
| + } |
| + return calls[0] |
| } |
| func wantCode(t *testing.T, rig *consentRig, call clientCall) { |
| @@ -362,6 +422,28 @@ func TestBrowserAllowLandsOnClientWithCode(t *testing.T) { |
| } |
| } |
| +// A client that redirects on after its callback, as Equipo does to Base, sends |
| +// the browser to a third origin the consent page's form-action cannot name. |
| +// Browsers check form-action along a form's whole redirect chain, so connect |
| +// answers the form with a page that moves the browser on, not a redirect. |
| +func TestBrowserAllowFollowsAClientThatRedirectsOn(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, button string |
| + want func(*testing.T, *consentRig, clientCall) |
| + }{ |
| + {"allow", consentButton, wantCode}, |
| + {"cancel", cancelButton, func(t *testing.T, rig *consentRig, call clientCall) { wantRefused(t, rig, call, "access_denied") }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + rig := newOnwardRig(t) |
| + b := rig.browser(t) |
| + b.openConsent(firstPartyID) |
| + b.click(tc.button) |
| + tc.want(t, rig, b.landOnFinal()) |
| + }) |
| + } |
| +} |
| + |
| func TestBrowserCancelLandsOnClientWithRefusal(t *testing.T) { |
| rig := newConsentRig(t) |
| b := rig.browser(t) |
diff --git a/connection/server_test.go b/connection/server_test.go| index 108cdfc..a523ae1 100644 |
| --- a/connection/server_test.go |
| +++ b/connection/server_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "context" |
| "encoding/base64" |
| "encoding/json" |
| + "html" |
| "io" |
| "log/slog" |
| "net/http" |
| @@ -192,7 +193,17 @@ func TestHomeBrowserConsentToHTTPMCPAndLogout(t *testing.T) { |
| if err != nil { |
| return err |
| } |
| - callback := redirect(resp) |
| + // The consent form is answered with a page that moves the browser on. |
| + handoff, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode != 200 || resp.Header.Get("Referrer-Policy") != "no-referrer" { |
| + t.Fatal("consent answer", resp.StatusCode, string(handoff)) |
| + } |
| + refresh := regexp.MustCompile(`<meta http-equiv="refresh" content="0;url=([^"]+)">`).FindSubmatch(handoff) |
| + if len(refresh) != 2 { |
| + t.Fatal("no hand-off to the client", string(handoff)) |
| + } |
| + callback := html.UnescapeString(string(refresh[1])) |
| resp = get(callback) |
| resp.Body.Close() |
| if resp.StatusCode != 200 { |
diff --git a/grant/consent_test.go b/grant/consent_test.go| index 4550d56..f039e10 100644 |
| --- a/grant/consent_test.go |
| +++ b/grant/consent_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "database/sql" |
| "encoding/json" |
| + "html" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| @@ -154,17 +155,113 @@ func wantPlainRefusal(t *testing.T, resp *http.Response, body string, status int |
| } |
| } |
| -func wantClientRefusal(t *testing.T, resp *http.Response, redirect string) { |
| +var ( |
| + handoffRefresh = regexp.MustCompile(`<meta http-equiv="refresh" content="0;url=([^"]*)">`) |
| + handoffLink = regexp.MustCompile(`<a href="([^"]*)">([^<]*)</a>`) |
| + htmlEntity = regexp.MustCompile(`&(amp|#[0-9]+);`) |
| +) |
| + |
| +// wantHandoff checks that an answer to the consent form is a page that sends |
| +// the browser on, not a redirect. Browsers hold a form's whole redirect chain to |
| +// form-action, so a client that redirects again would strand the person on the |
| +// consent page. It returns where the page sends the browser. |
| +func wantHandoff(t *testing.T, resp *http.Response, body string) *url.URL { |
| t.Helper() |
| - if resp.StatusCode != 303 { |
| - t.Fatalf("status %d, want a redirect to the client", resp.StatusCode) |
| + if resp.StatusCode != 200 || resp.Header.Get("Location") != "" { |
| + t.Fatalf("status %d location %q, want a 200 hand-off page", resp.StatusCode, resp.Header.Get("Location")) |
| + } |
| + if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/html") { |
| + t.Fatalf("content type %q", resp.Header.Get("Content-Type")) |
| + } |
| + // The page's URL carries the code: it is neither stored nor sent onward. |
| + if got := resp.Header.Get("Cache-Control"); got != "no-store" { |
| + t.Fatalf("Cache-Control %q", got) |
| + } |
| + if got := resp.Header.Get("Referrer-Policy"); got != "no-referrer" { |
| + t.Fatalf("Referrer-Policy %q", got) |
| + } |
| + if got := resp.Header.Get("Content-Security-Policy"); got != pageCSP { |
| + t.Fatalf("hand-off CSP %q, want %q", got, pageCSP) |
| + } |
| + for _, inline := range []string{"<script", "<style", " style=", "javascript:"} { |
| + if strings.Contains(body, inline) { |
| + t.Fatalf("hand-off page has %q: %s", inline, body) |
| + } |
| } |
| - loc, err := url.Parse(resp.Header.Get("Location")) |
| - if err != nil || loc.Scheme+"://"+loc.Host+loc.Path != redirect { |
| - t.Fatalf("redirected to %q, want %s", resp.Header.Get("Location"), redirect) |
| + refresh := handoffRefresh.FindAllStringSubmatch(body, -1) |
| + links := handoffLink.FindAllStringSubmatch(body, -1) |
| + if len(refresh) != 1 || len(links) != 1 { |
| + t.Fatalf("want one refresh and one link: %s", body) |
| + } |
| + if links[0][2] != handoffText { |
| + t.Fatalf("link text %q, want %q", links[0][2], handoffText) |
| + } |
| + for _, raw := range []string{refresh[0][1], links[0][1]} { |
| + if strings.Contains(htmlEntity.ReplaceAllString(raw, ""), "&") { |
| + t.Fatalf("unescaped & in %q", raw) |
| + } |
| + } |
| + target := html.UnescapeString(refresh[0][1]) |
| + if href := html.UnescapeString(links[0][1]); href != target { |
| + t.Fatalf("link %q and refresh %q differ", href, target) |
| + } |
| + dest, err := url.Parse(target) |
| + if err != nil || !dest.IsAbs() { |
| + t.Fatalf("hand-off to %q", target) |
| + } |
| + return dest |
| +} |
| + |
| +func wantClientRefusal(t *testing.T, resp *http.Response, body, redirect string) { |
| + t.Helper() |
| + loc := wantHandoff(t, resp, body) |
| + if loc.Scheme+"://"+loc.Host+loc.Path != redirect { |
| + t.Fatalf("sent to %q, want %s", loc, redirect) |
| } |
| if q := loc.Query(); q.Get("error") != "access_denied" || q.Get("state") != testState || q.Get("code") != "" || q.Get("iss") == "" { |
| - t.Fatalf("redirect query %v", q) |
| + t.Fatalf("refusal query %v", q) |
| + } |
| +} |
| + |
| +// wantClientCode checks an approval hands the browser to the client with a code. |
| +func wantClientCode(t *testing.T, resp *http.Response, body, redirect string) { |
| + t.Helper() |
| + loc := wantHandoff(t, resp, body) |
| + if loc.Scheme+"://"+loc.Host+loc.Path != redirect { |
| + t.Fatalf("sent to %q, want %s", loc, redirect) |
| + } |
| + if q := loc.Query(); q.Get("code") == "" || q.Get("error") != "" || q.Get("state") != testState || q.Get("iss") == "" { |
| + t.Fatalf("approval query %v", q) |
| + } |
| +} |
| + |
| +func TestConsentAnswersHandTheBrowserOnRatherThanRedirect(t *testing.T) { |
| + for _, tc := range []struct{ client, redirect string }{{"other", otherRedirect}, {"base", baseRedirect}, {"oficina-cli", cliRedirect}} { |
| + for _, decision := range []string{"approve", "deny"} { |
| + t.Run(tc.client+"/"+decision, func(t *testing.T) { |
| + _, ts := consentServer(t, consentClients, true) |
| + ticket, cookies := consentPage(t, ts, tc.client, tc.redirect, "fresh") |
| + resp, body := answer{ticket: ticket, decision: decision, session: "fresh", origins: []string{ts.URL}, cookies: cookies}.post(t, ts) |
| + if decision == "deny" { |
| + wantClientRefusal(t, resp, body, tc.redirect) |
| + return |
| + } |
| + wantClientCode(t, resp, body, tc.redirect) |
| + // The query joins state, iss and code with &, escaped in both places. |
| + dest := wantHandoff(t, resp, body).String() |
| + escaped := strings.ReplaceAll(dest, "&", "&") |
| + if !strings.Contains(body, `content="0;url=`+escaped+`"`) || !strings.Contains(body, `href="`+escaped+`"`) { |
| + t.Fatalf("%s not escaped as %s: %s", dest, escaped, body) |
| + } |
| + }) |
| + } |
| + } |
| + // The consent page itself keeps its policy: the form posts only to connect |
| + // and this request's client. |
| + _, ts := consentServer(t, consentClients, true) |
| + resp, _ := fetchAs(t, ts, consentURL(ts.URL, "other", otherRedirect), "fresh") |
| + if got := resp.Header.Get("Content-Security-Policy"); got != strings.Replace(pageCSP, "form-action 'self'", "form-action 'self' https://other.example", 1) { |
| + t.Fatalf("consent CSP %q", got) |
| } |
| } |
| @@ -185,10 +282,8 @@ func TestApproveRefusesAnyOtherOrigin(t *testing.T) { |
| }) |
| } |
| // None of those spent the ticket: the real origin still connects. |
| - resp, _ := answer{ticket: ticket, decision: "approve", session: "fresh", origins: []string{ts.URL}, cookies: cookies}.post(t, ts) |
| - if resp.StatusCode != 303 || !strings.Contains(resp.Header.Get("Location"), "code=") { |
| - t.Fatalf("same-origin approval: %d %q", resp.StatusCode, resp.Header.Get("Location")) |
| - } |
| + resp, body := answer{ticket: ticket, decision: "approve", session: "fresh", origins: []string{ts.URL}, cookies: cookies}.post(t, ts) |
| + wantClientCode(t, resp, body, otherRedirect) |
| } |
| func directive(csp, name string) string { |
| @@ -271,8 +366,8 @@ func TestTrustedTicketRefusalsGoBackToTheClient(t *testing.T) { |
| ticket, cookies := consentPage(t, ts, "other", otherRedirect, "fresh") |
| a := answer{ticket: ticket, decision: decision, session: "fresh", origins: []string{ts.URL}, cookies: cookies} |
| change(&a, s) |
| - resp, _ := a.post(t, ts) |
| - wantClientRefusal(t, resp, otherRedirect) |
| + resp, body := a.post(t, ts) |
| + wantClientRefusal(t, resp, body, otherRedirect) |
| }) |
| } |
| } |
| @@ -333,9 +428,8 @@ func TestSpentTicketGetsAPlainRefusalNotASecondAnswer(t *testing.T) { |
| _, ts := consentServer(t, consentClients, true) |
| ticket, cookies := consentPage(t, ts, "other", otherRedirect, "fresh") |
| a := answer{ticket: ticket, decision: "approve", session: "fresh", origins: []string{ts.URL}, cookies: cookies} |
| - if resp, _ := a.post(t, ts); resp.StatusCode != 303 { |
| - t.Fatalf("first answer %d", resp.StatusCode) |
| - } |
| + first, firstBody := a.post(t, ts) |
| + wantClientCode(t, first, firstBody, otherRedirect) |
| resp, body := a.post(t, ts) |
| wantPlainRefusal(t, resp, body, 400) |
| } |
| @@ -343,10 +437,8 @@ func TestSpentTicketGetsAPlainRefusalNotASecondAnswer(t *testing.T) { |
| func TestFirstPartyClientReusesAnExistingSession(t *testing.T) { |
| _, ts := consentServer(t, consentClients, true) |
| ticket, cookies := consentPage(t, ts, "base", baseRedirect, "older") |
| - resp, _ := answer{ticket: ticket, decision: "approve", session: "older", origins: []string{ts.URL}, cookies: cookies}.post(t, ts) |
| - if resp.StatusCode != 303 || !strings.HasPrefix(resp.Header.Get("Location"), baseRedirect+"?") || !strings.Contains(resp.Header.Get("Location"), "code=") { |
| - t.Fatalf("first-party approval %d %q", resp.StatusCode, resp.Header.Get("Location")) |
| - } |
| + resp, body := answer{ticket: ticket, decision: "approve", session: "older", origins: []string{ts.URL}, cookies: cookies}.post(t, ts) |
| + wantClientCode(t, resp, body, baseRedirect) |
| } |
| func TestFirstPartyClientStillNeedsASessionAndConsent(t *testing.T) { |
| @@ -360,8 +452,8 @@ func TestFirstPartyClientStillNeedsASessionAndConsent(t *testing.T) { |
| t.Fatalf("first-party client skipped consent: %d %q", resp.StatusCode, resp.Header.Get("Location")) |
| } |
| ticket, cookies := consentPage(t, ts, "base", baseRedirect, "older") |
| - refused, _ := answer{ticket: ticket, decision: "approve", session: "stranger", origins: []string{ts.URL}, cookies: cookies}.post(t, ts) |
| - wantClientRefusal(t, refused, baseRedirect) |
| + refused, refusedBody := answer{ticket: ticket, decision: "approve", session: "stranger", origins: []string{ts.URL}, cookies: cookies}.post(t, ts) |
| + wantClientRefusal(t, refused, refusedBody, baseRedirect) |
| } |
| func TestOtherClientsAreForcedToSignInFresh(t *testing.T) { |
diff --git a/grant/redirect_test.go b/grant/redirect_test.go| index 10f634a..e8e1753 100644 |
| --- a/grant/redirect_test.go |
| +++ b/grant/redirect_test.go |
| @@ -51,6 +51,21 @@ func wantErrorRedirect(t *testing.T, resp *http.Response, code string) { |
| } |
| } |
| +// wantErrorHandoff is wantErrorRedirect for an answer to the consent form, |
| +// which hands the browser on with a page instead of a redirect. |
| +func wantErrorHandoff(t *testing.T, code string) func(*http.Response, string) { |
| + return func(resp *http.Response, body string) { |
| + t.Helper() |
| + loc := wantHandoff(t, resp, body) |
| + if loc.Host != "127.0.0.1:4567" || loc.Path != "/callback" { |
| + t.Fatalf("sent to %q", loc) |
| + } |
| + if q := loc.Query(); q.Get("error") != code || q.Get("state") != testState || q.Get("code") != "" { |
| + t.Fatalf("hand-off query %v", q) |
| + } |
| + } |
| +} |
| + |
| func TestNoTeamRedirectsToClientWithAccessDenied(t *testing.T) { |
| _, ts, admitted := setup(t) |
| *admitted = false |
| @@ -124,7 +139,7 @@ func TestApproveRefusalRedirectsWithStateButReplayDoesNot(t *testing.T) { |
| if len(m) != 2 { |
| t.Fatal("no ticket") |
| } |
| - post := func(team string) *http.Response { |
| + post := func(team string) (*http.Response, string) { |
| form := url.Values{"ticket": {m[1]}, "decision": {"approve"}} |
| if team != "" { |
| form.Set("team", team) |
| @@ -142,15 +157,16 @@ func TestApproveRefusalRedirectsWithStateButReplayDoesNot(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - resp.Body.Close() |
| - return resp |
| + defer resp.Body.Close() |
| + body, _ := io.ReadAll(resp.Body) |
| + return resp, string(body) |
| } |
| - wantErrorRedirect(t, post("not-my-team"), "access_denied") |
| - wantErrorRedirect(t, post(""), "access_denied") |
| - if resp := post("acme"); resp.StatusCode != 303 || !strings.Contains(resp.Header.Get("Location"), "code=") { |
| - t.Fatalf("approve %d", resp.StatusCode) |
| + wantErrorHandoff(t, "access_denied")(post("not-my-team")) |
| + wantErrorHandoff(t, "access_denied")(post("")) |
| + if resp, body := post("acme"); wantHandoff(t, resp, body).Query().Get("code") == "" { |
| + t.Fatalf("approve sent no code: %s", body) |
| } |
| - if resp := post("acme"); resp.StatusCode != 400 || resp.Header.Get("Location") != "" { |
| + if resp, _ := post("acme"); resp.StatusCode != 400 || resp.Header.Get("Location") != "" { |
| t.Fatalf("replay %d %q", resp.StatusCode, resp.Header.Get("Location")) |
| } |
| } |
diff --git a/grant/server.go b/grant/server.go| index d1c7e88..0f178d8 100644 |
| --- a/grant/server.go |
| +++ b/grant/server.go |
| @@ -268,9 +268,10 @@ func single(values url.Values) bool { |
| // pageCSP lets the grant pages load their own stylesheet and nothing else. |
| const pageCSP = "default-src 'none'; style-src 'self'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'" |
| -// consentCSP is pageCSP for one consent page. Answering the form redirects to |
| -// the client, and browsers hold that redirect to form-action as well, so the |
| -// policy also names the origin of this request's validated redirect, and no other. |
| +// consentCSP is pageCSP for one consent page. It also names the origin of this |
| +// request's validated redirect, and no other. The form's answer is a hand-off |
| +// page rather than a redirect (see handOff), so this is not what lets the |
| +// browser reach the client. |
| func consentCSP(redirect string) string { |
| u, err := url.Parse(redirect) |
| if err != nil { |
| @@ -279,13 +280,12 @@ func consentCSP(redirect string) string { |
| return strings.Replace(pageCSP, "form-action 'self'", "form-action 'self' "+u.Scheme+"://"+u.Host, 1) |
| } |
| -// refuse sends a trusted client back to its registered redirect with an OAuth |
| -// error. Callers must have validated the client and redirect already. |
| -func (s *Server) refuse(w http.ResponseWriter, r *http.Request, redirect, state, code string) { |
| +// refusalURL is a trusted client's registered redirect carrying an OAuth error. |
| +// Callers must have validated the client and redirect already. |
| +func (s *Server) refusalURL(redirect, state, code string) (string, bool) { |
| dest, err := url.Parse(redirect) |
| if err != nil { |
| - refusalPage(w, 400) |
| - return |
| + return "", false |
| } |
| q := dest.Query() |
| q.Set("error", code) |
| @@ -294,7 +294,29 @@ func (s *Server) refuse(w http.ResponseWriter, r *http.Request, redirect, state, |
| } |
| q.Set("iss", s.cfg.Origin) |
| dest.RawQuery = q.Encode() |
| - http.Redirect(w, r, dest.String(), 303) |
| + return dest.String(), true |
| +} |
| + |
| +// refuse redirects a trusted client's authorize request back to it with an |
| +// OAuth error. Answers to the consent form use refuseForm instead. |
| +func (s *Server) refuse(w http.ResponseWriter, r *http.Request, redirect, state, code string) { |
| + dest, ok := s.refusalURL(redirect, state, code) |
| + if !ok { |
| + refusalPage(w, 400) |
| + return |
| + } |
| + http.Redirect(w, r, dest, 303) |
| +} |
| + |
| +// refuseForm is refuse for an answer to the consent form: it hands the browser |
| +// back to the client with a page instead of a redirect. |
| +func (s *Server) refuseForm(w http.ResponseWriter, redirect, state, code string) { |
| + dest, ok := s.refusalURL(redirect, state, code) |
| + if !ok { |
| + refusalPage(w, 400) |
| + return |
| + } |
| + handOff(w, dest) |
| } |
| func (s *Server) authorize(w http.ResponseWriter, r *http.Request) { |
| if len(r.URL.RawQuery) > 8192 { |
| @@ -420,6 +442,32 @@ func refusalPage(w http.ResponseWriter, status int) { |
| _ = refusal.Execute(w, nil) |
| } |
| +// handoffText is the hand-off page's one visible link, for a browser that does |
| +// not follow the refresh. It is a placeholder awaiting copy review. |
| +const handoffText = "Continue" |
| + |
| +// handoffPage moves the browser on with a meta refresh. html/template escapes |
| +// the URL in both attributes; a refresh URL that does not start with a quote |
| +// runs to the end of the attribute, so its & and ; need no further care. |
| +var handoffPage = template.Must(template.New("handoff").Parse(pageHead + `<meta http-equiv="refresh" content="0;url={{.URL}}"><title>Connect to Oficina</title>` + doorOpen + `<p><a href="{{.URL}}">{{.Text}}</a></p>` + doorClose)) |
| + |
| +// handOff answers the consent form by sending the browser to dest, a trusted |
| +// client's redirect, with a page rather than a 303. Browsers check form-action |
| +// along a form's whole redirect chain, and a client may redirect on to origins |
| +// connect cannot name (Equipo hands a person on to Base), so a 303 would leave |
| +// the person on the consent page. A meta refresh is a fresh navigation that |
| +// form-action does not govern, and the policy stays as strict as before. |
| +func handOff(w http.ResponseWriter, dest string) { |
| + w.Header().Set("Content-Security-Policy", pageCSP) |
| + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| + // dest carries the authorization code: keep it out of caches and out of |
| + // the Referer the client and anything after it would receive. |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| + w.WriteHeader(200) |
| + _ = handoffPage.Execute(w, map[string]string{"URL": dest, "Text": handoffText}) |
| +} |
| + |
| func (s *Server) approve(w http.ResponseWriter, r *http.Request) { |
| if len(r.Header.Values("Origin")) != 1 || r.Header.Get("Origin") != s.cfg.Origin { |
| refusalPage(w, 403) |
| @@ -444,17 +492,17 @@ func (s *Server) approve(w http.ResponseWriter, r *http.Request) { |
| // still registered, so from here a refusal goes back to that client. |
| cookies := r.CookiesNamed("__Host-oficina-consent") |
| if t.Expires <= s.cfg.Store.Now().Unix() || len(cookies) != 1 || subtle.ConstantTimeCompare([]byte(cookies[0].Value), []byte(t.Nonce)) != 1 || s.subjectFor(client, r) != t.Subject { |
| - s.refuse(w, r, t.Redirect, t.State, "access_denied") |
| + s.refuseForm(w, t.Redirect, t.State, "access_denied") |
| return |
| } |
| decision := r.PostForm.Get("decision") |
| if decision != "approve" && decision != "deny" { |
| - s.refuse(w, r, t.Redirect, t.State, "invalid_request") |
| + s.refuseForm(w, t.Redirect, t.State, "invalid_request") |
| return |
| } |
| teams, err := s.cfg.Teams(r.Context(), t.Subject) |
| if err != nil { |
| - s.refuse(w, r, t.Redirect, t.State, "temporarily_unavailable") |
| + s.refuseForm(w, t.Redirect, t.State, "temporarily_unavailable") |
| return |
| } |
| allowed := map[string]bool{} |
| @@ -465,18 +513,18 @@ func (s *Server) approve(w http.ResponseWriter, r *http.Request) { |
| seen := map[string]bool{} |
| for _, team := range selected { |
| if !allowed[team] || seen[team] { |
| - s.refuse(w, r, t.Redirect, t.State, "access_denied") |
| + s.refuseForm(w, t.Redirect, t.State, "access_denied") |
| return |
| } |
| seen[team] = true |
| } |
| if decision == "approve" && len(selected) == 0 { |
| - s.refuse(w, r, t.Redirect, t.State, "access_denied") |
| + s.refuseForm(w, t.Redirect, t.State, "access_denied") |
| return |
| } |
| result, err := s.cfg.Store.DB.ExecContext(r.Context(), `DELETE FROM agent_pending WHERE hash=? AND expires>?`, hash(t.Nonce), s.cfg.Store.Now().Unix()) |
| if err != nil { |
| - s.refuse(w, r, t.Redirect, t.State, "temporarily_unavailable") |
| + s.refuseForm(w, t.Redirect, t.State, "temporarily_unavailable") |
| return |
| } |
| n, _ := result.RowsAffected() |
| @@ -487,7 +535,7 @@ func (s *Server) approve(w http.ResponseWriter, r *http.Request) { |
| } |
| http.SetCookie(w, &http.Cookie{Name: "__Host-oficina-consent", Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1}) |
| if decision == "deny" { |
| - s.refuse(w, r, t.Redirect, t.State, "access_denied") |
| + s.refuseForm(w, t.Redirect, t.State, "access_denied") |
| return |
| } |
| { |
| @@ -497,12 +545,12 @@ func (s *Server) approve(w http.ResponseWriter, r *http.Request) { |
| q.Set("iss", s.cfg.Origin) |
| code, err := s.cfg.Store.CreateCode(r.Context(), Grant{Subject: t.Subject, ClientID: t.Client, Teams: selected, Scopes: t.Scopes}, Code{t.Redirect, t.Challenge, t.Resource}) |
| if err != nil { |
| - s.refuse(w, r, t.Redirect, t.State, "temporarily_unavailable") |
| + s.refuseForm(w, t.Redirect, t.State, "temporarily_unavailable") |
| return |
| } |
| q.Set("code", code) |
| dest.RawQuery = q.Encode() |
| - http.Redirect(w, r, dest.String(), 303) |
| + handOff(w, dest.String()) |
| } |
| } |
| func form(w http.ResponseWriter, r *http.Request) bool { |
diff --git a/grant/server_test.go b/grant/server_test.go| index 34c33af..96cb0b6 100644 |
| --- a/grant/server_test.go |
| +++ b/grant/server_test.go |
| @@ -96,10 +96,9 @@ func TestBrowserLoginRefreshReplayAndRevocation(t *testing.T) { |
| if err != nil { |
| return err |
| } |
| + handoff, _ := io.ReadAll(result.Body) |
| result.Body.Close() |
| - if result.StatusCode != 303 { |
| - t.Fatalf("approve %d", result.StatusCode) |
| - } |
| + dest := wantHandoff(t, result, string(handoff)) |
| // The same form cannot create a second grant. |
| replay := post.Clone(context.Background()) |
| replay.Body = io.NopCloser(strings.NewReader(form.Encode())) |
| @@ -111,7 +110,7 @@ func TestBrowserLoginRefreshReplayAndRevocation(t *testing.T) { |
| if replayed.StatusCode != 400 { |
| t.Fatalf("consent replay %d", replayed.StatusCode) |
| } |
| - callback, err := http.Get(result.Header.Get("Location")) |
| + callback, err := http.Get(dest.String()) |
| if err != nil { |
| return err |
| } |