Merge branch 'consent-handoff' into feat/agent-access

Merge branch 'consent-handoff' into feat/agent-access

Answer consent decisions with a hand-off page, not a 303, so browsers
stop checking the client's onward redirect against the consent page's
form-action. Fixes Allow access sticking when Equipo returns to Base.
Astra clean; CI green.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 7afa24c1d8b0de5ff947cd1d357a412303f11440 parent b851aa2parent 62724a4
6 files changed, +341 −62
  • connection/consent_browser_test.go +95 −9
  • connection/server_test.go +12 −1
  • grant/consent_test.go +141 −22
  • grant/redirect_test.go +24 −8
  • grant/server.go +66 −18
  • grant/server_test.go +3 −4

CI passed — run details

CI log
=== ci ===
go vet ./...
go test -race ./...
ok  	amadan.net/oficina/agent-access.git	(cached)
ok  	amadan.net/oficina/agent-access.git/client	(cached)
?   	amadan.net/oficina/agent-access.git/cmd/oficina	[no test files]
ok  	amadan.net/oficina/agent-access.git/cmd/oficina-connect	5.619s
ok  	amadan.net/oficina/agent-access.git/connection	10.999s
ok  	amadan.net/oficina/agent-access.git/grant	3.588s
diff --git a/connection/consent_browser_test.go b/connection/consent_browser_test.go
index c37a5a7..938d321 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 []clientCall
}
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, clientCall{r.URL.Query(), r.Header.Get("Referer")})
+ 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,31 @@ 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 := append([]clientCall{}, b.rig.finals...)
+ b.rig.mu.Unlock()
+ calls := b.rig.clientCalls()
+ if len(calls) != 1 || len(finals) != 1 {
+ b.t.Fatalf("client saw %d callbacks and the final page %d visits, want 1 each", len(calls), len(finals))
+ }
+ // The code was in the client's URL; the page after it must not learn it.
+ if finals[0].referer != "" {
+ b.t.Fatalf("final page received a referrer: %q", finals[0].referer)
+ }
+ return calls[0]
}
func wantCode(t *testing.T, rig *consentRig, call clientCall) {
@@ -362,6 +426,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..56815b5 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,140 @@ 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)
}
- 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)
+ 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)
+ }
+ }
+ 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, "&", "&amp;")
+ 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)
+ }
+}
+
+// A state can hold anything the client likes, and a registered redirect can
+// carry its own query; neither may change where the hand-off page goes.
+func TestHandoffKeepsAHostileStateInsideTheURL(t *testing.T) {
+ const redirect = "https://other.example/oauth/done;v=1?tenant=a"
+ const state = `quote"'<b>&amp;%zz ünï;url=https://evil.example/ + 0;url=x`
+ clients := []Client{{ID: "other", Name: "Other Host", Redirects: []string{redirect}}}
+ for _, decision := range []string{"approve", "deny"} {
+ t.Run(decision, func(t *testing.T) {
+ _, ts := consentServer(t, clients, true)
+ resp, body := fetchAs(t, ts, authorizeURL(ts.URL, url.Values{"client_id": {"other"}, "redirect_uri": {redirect}, "state": {state}}), "fresh")
+ m := regexp.MustCompile(`name="ticket" value="([^"]+)"`).FindStringSubmatch(body)
+ if resp.StatusCode != 200 || len(m) != 2 {
+ t.Fatalf("consent page %d", resp.StatusCode)
+ }
+ resp, body = answer{ticket: m[1], decision: decision, session: "fresh", origins: []string{ts.URL}, cookies: resp.Cookies()}.post(t, ts)
+ dest := wantHandoff(t, resp, body)
+ q := dest.Query()
+ if dest.Scheme != "https" || dest.Host != "other.example" || dest.Path != "/oauth/done;v=1" || q.Get("state") != state || q.Get("tenant") != "a" {
+ t.Fatalf("sent to %q, query %v", dest, q)
+ }
+ if strings.Contains(body, "<b>") || strings.Contains(body, `quote"`) {
+ t.Fatalf("state reached the page unescaped: %s", body)
+ }
+ })
}
}
@@ -185,10 +309,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 +393,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 +455,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 +464,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 +479,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..1106c70 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. Its wording passed copy review on 2026-11-24.
+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
}