oficina / agent-access Public
Let a person finish consent in a real browser
Allow access always ended on a raw {"error":"access_denied"} page. Each
cause below was reproduced in Chromium before it was fixed.
- Referrer-Policy: no-referrer made the consent form post Origin: null,
which approve refuses. Grant pages now send same-origin; the strict
Origin check is unchanged.
- form-action 'self' blocked the redirect back to the client. The consent
page now also names the origin of that request's validated redirect.
Registered redirect hosts can no longer hold wildcards or separators.
- Once a ticket is authentic and names a registered client, refusals such
as an expired cookie or stale sign-in go back to the client. Requests
that cannot be traced to a client get a plain page, never raw JSON.
Clients marked first_party in config now reuse the person's existing
Oficina ID session. A missing field stays strict, every other client keeps
the five-minute fresh sign-in, and consent is still asked of everyone.
The browser tests need Chromium: set RASTRILLO_CHROME, or
RASTRILLO_BROWSER_OPTIONAL to skip them deliberately.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+1,087
−19
cmd/oficina-connect/main_test.go+12 −0connection/consent_browser_test.go+488 −0connection/server.go+19 −4go.mod+6 −0go.sum+16 −0grant/consent_test.go+436 −0grant/server.go+110 −15
CI passed — run details
CI log
=== ci === go vet ./... go: downloading github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 go: downloading github.com/chromedp/chromedp v0.14.2 go: downloading github.com/gobwas/ws v1.4.0 go: downloading github.com/chromedp/sysutil v1.1.0 go: downloading github.com/gobwas/httphead v0.1.0 go: downloading github.com/gobwas/pool v0.2.1 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.670s ok amadan.net/oficina/agent-access.git/connection 8.094s ok amadan.net/oficina/agent-access.git/grant 3.018s
diff --git a/cmd/oficina-connect/main_test.go b/cmd/oficina-connect/main_test.go| index de6aced..339193c 100644 |
| --- a/cmd/oficina-connect/main_test.go |
| +++ b/cmd/oficina-connect/main_test.go |
| @@ -28,6 +28,18 @@ func syntheticConfig(t *testing.T) []byte { |
| return raw |
| } |
| +func TestConfigMarksOnlyNamedClientsFirstParty(t *testing.T) { |
| + t.Setenv("OFICINA_CONNECT_DEK", base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{5}, 32))) |
| + raw := append([]byte(`{"clients":[{"id":"base","name":"Base","redirects":["https://base.example.test/callback"],"first_party":true},{"id":"host","name":"Host","redirects":["https://host.example.test/callback"]}],`), syntheticConfig(t)[1:]...) |
| + cfg, err := loadConfig(raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(cfg.Clients) != 2 || !cfg.Clients[0].FirstParty || cfg.Clients[1].FirstParty { |
| + t.Fatalf("clients %+v", cfg.Clients) |
| + } |
| +} |
| + |
| func TestApplicationHeaderBudget(t *testing.T) { |
| for _, kind := range []string{"target", "host", "repeated"} { |
| t.Run(kind, func(t *testing.T) { |
diff --git a/connection/consent_browser_test.go b/connection/consent_browser_test.go| new file mode 100644 |
| index 0000000..c37a5a7 |
| --- /dev/null |
| +++ b/connection/consent_browser_test.go |
| @@ -0,0 +1,488 @@ |
| +package connection |
| + |
| +import ( |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "fmt" |
| + "html" |
| + "io" |
| + "log" |
| + "log/slog" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/agent-access.git/client" |
| + "amadan.net/oficina/agent-access.git/grant" |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| + family "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + cdplog "github.com/chromedp/cdproto/log" |
| + "github.com/chromedp/cdproto/network" |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +// These tests drive a real Chromium because the bugs they guard live in the |
| +// browser: what Origin it sends and what its CSP lets a form redirect to. A Go |
| +// client that sets Origin by hand passes whether or not a person can connect. |
| + |
| +const ( |
| + browserSubject = "pr_bbbbbbbbbbbbbbbbbbbbbbbbbb" |
| + browserState = "browser-state-0123456789" |
| + firstPartyID = "db533929-5300-4363-a0f7-586e8f0a349f" |
| + thirdPartyID = "third-party-host" |
| + consentButton = `button[value="approve"]` |
| + cancelButton = `button[value="deny"]` |
| + consentCookie = "__Host-oficina-consent" |
| + browserTimeout = 20 * time.Second |
| +) |
| + |
| +// chromePath follows rastrillo's harness: a missing browser fails the run |
| +// unless RASTRILLO_BROWSER_OPTIONAL makes skipping a deliberate choice. |
| +func chromePath(t *testing.T) string { |
| + t.Helper() |
| + if path := os.Getenv("RASTRILLO_CHROME"); path != "" { |
| + return path |
| + } |
| + for _, name := range []string{"chromium", "chromium-browser", "google-chrome", "google-chrome-stable"} { |
| + if path, err := exec.LookPath(name); err == nil { |
| + return path |
| + } |
| + } |
| + if home, err := os.UserHomeDir(); err == nil { |
| + hits, _ := filepath.Glob(filepath.Join(home, ".cache", "ms-playwright", "chromium-*", "chrome-linux64", "chrome")) |
| + if len(hits) > 0 { |
| + return hits[len(hits)-1] |
| + } |
| + } |
| + if os.Getenv("RASTRILLO_BROWSER_OPTIONAL") != "" { |
| + t.Skip("no chromium found, RASTRILLO_BROWSER_OPTIONAL set: SKIPPED, not passed") |
| + } |
| + t.Fatal("no chromium found: set RASTRILLO_CHROME, or RASTRILLO_BROWSER_OPTIONAL to skip deliberately") |
| + return "" |
| +} |
| + |
| +// consentRig runs connect, a fake Home, a fake directory and a fake client on |
| +// separate 127.0.0.1 ports. The browser reaches them through .test names mapped |
| +// to 127.0.0.1, because Home's assertions refuse IP-address origins; that also |
| +// makes connect and the client cross-site, as they are in production. |
| +type consentRig struct { |
| + t *testing.T |
| + origin string |
| + clientOrigin string |
| + store *db.DB |
| + handler http.Handler |
| + mu sync.Mutex |
| + asks []url.Values |
| + origins []string |
| + calls []clientCall |
| +} |
| + |
| +type clientCall struct { |
| + query url.Values |
| + referer string |
| +} |
| + |
| +func quietTLS(handler http.Handler) *httptest.Server { |
| + server := httptest.NewUnstartedServer(handler) |
| + server.Config.ErrorLog = log.New(io.Discard, "", 0) |
| + return server |
| +} |
| + |
| +// publicOrigin names a listener the way the browser will reach it. |
| +func publicOrigin(name string, server *httptest.Server) string { |
| + _, port, _ := net.SplitHostPort(server.Listener.Addr().String()) |
| + return "https://" + name + ":" + port |
| +} |
| + |
| +func newConsentRig(t *testing.T) *consentRig { |
| + t.Helper() |
| + rig := &consentRig{t: t} |
| + key, err := family.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + fakeClient := quietTLS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/callback" { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + rig.mu.Lock() |
| + rig.calls = append(rig.calls, clientCall{r.URL.Query(), r.Header.Get("Referer")}) |
| + rig.mu.Unlock() |
| + w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| + _, _ = io.WriteString(w, "client callback") |
| + })) |
| + rig.clientOrigin = publicOrigin("client.example.test", fakeClient) |
| + fakeClient.StartTLS() |
| + t.Cleanup(fakeClient.Close) |
| + |
| + var connect http.Handler |
| + service := quietTLS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method == http.MethodPost && r.URL.Path == "/oauth/authorize" { |
| + rig.mu.Lock() |
| + rig.origins = append(rig.origins, r.Header.Get("Origin")) |
| + rig.mu.Unlock() |
| + } |
| + connect.ServeHTTP(w, r) |
| + })) |
| + rig.origin = publicOrigin("connect.oficina.test", service) |
| + |
| + // The fake Home models the one rule that matters here: max_age=300 makes the |
| + // person authenticate now, and without it their old Home session is reused. |
| + var homeOrigin string |
| + home := quietTLS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/authorize" { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + q := r.URL.Query() |
| + rig.mu.Lock() |
| + rig.asks = append(rig.asks, q) |
| + rig.mu.Unlock() |
| + now := time.Now().Unix() |
| + authTime := now - int64((2*time.Hour)/time.Second) |
| + if q.Get("max_age") == "300" { |
| + authTime = now |
| + } |
| + id, err := assertion.RandomID() |
| + if err != nil { |
| + http.Error(w, "assertion id", 500) |
| + return |
| + } |
| + 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}) |
| + if err != nil { |
| + http.Error(w, "assertion", 500) |
| + return |
| + } |
| + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| + 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)) |
| + })) |
| + homeOrigin = publicOrigin("id.oficina.test", home) |
| + home.StartTLS() |
| + t.Cleanup(home.Close) |
| + |
| + const appOrigin = "https://notes.example.test" |
| + directory := quietTLS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/json") |
| + _ = json.NewEncoder(w).Encode(map[string]any{"teams": []DirectoryTeam{{ID: "acme", Name: "Acme", Apps: []DirectoryApp{{App: "memoria", Origin: appOrigin}}}}}) |
| + })) |
| + directory.StartTLS() |
| + t.Cleanup(directory.Close) |
| + |
| + // Clients arrive as JSON, the way the deployed configuration supplies them. |
| + redirect := rig.clientOrigin + "/callback" |
| + raw := fmt.Sprintf(`[{"id":%q,"name":"Base","redirects":[%q],"first_party":true},{"id":%q,"name":"Third Party Host","redirects":[%q]}]`, firstPartyID, redirect, thirdPartyID, redirect) |
| + var clients []grant.Client |
| + if err := json.Unmarshal([]byte(raw), &clients); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + registry, err := access.NewRegistry(access.Operation{Name: "notes_create", Description: "Create a note", Scope: "notes:write", Idempotent: true, |
| + Input: json.RawMessage(`{"type":"object","required":["team"],"properties":{"team":{"type":"string"}},"additionalProperties":false}`), |
| + Output: json.RawMessage(`{"type":"object"}`), |
| + Invoke: func(context.Context, access.Principal, json.RawMessage) (any, error) { return map[string]any{}, nil }}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + contracts := registry.List(access.Principal{Subject: browserSubject, Teams: []string{"acme"}, Scopes: []string{"notes:write"}}) |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + rig.store, err = db.Open(filepath.Join(t.TempDir(), "connect.db"), logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { rig.store.Close() }) |
| + 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) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + connect = server.Handler |
| + rig.handler = server.Handler |
| + service.StartTLS() |
| + t.Cleanup(service.Close) |
| + return rig |
| +} |
| + |
| +func (r *consentRig) authorizeURL(clientID string) string { |
| + 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}} |
| + return r.origin + "/oauth/authorize?" + q.Encode() |
| +} |
| + |
| +// ageSignIn makes the connect session's Home authentication look old. |
| +func (r *consentRig) ageSignIn(age time.Duration) { |
| + r.t.Helper() |
| + if _, err := r.store.Writer().Exec("UPDATE sessions SET auth_time=?", time.Now().Add(-age).UTC().Format(time.RFC3339)); err != nil { |
| + r.t.Fatal(err) |
| + } |
| +} |
| + |
| +func (r *consentRig) homeAsks() []url.Values { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + return append([]url.Values{}, r.asks...) |
| +} |
| + |
| +func (r *consentRig) clientCalls() []clientCall { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + return append([]clientCall{}, r.calls...) |
| +} |
| + |
| +func (r *consentRig) postedOrigins() []string { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + return append([]string{}, r.origins...) |
| +} |
| + |
| +// consentBrowser is one Chromium with its own empty profile. |
| +type consentBrowser struct { |
| + t *testing.T |
| + rig *consentRig |
| + ctx context.Context |
| + mu sync.Mutex |
| + logs []string |
| +} |
| + |
| +func (r *consentRig) browser(t *testing.T) *consentBrowser { |
| + t.Helper() |
| + 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)) |
| + allocator, stopAllocator := chromedp.NewExecAllocator(context.Background(), options...) |
| + t.Cleanup(stopAllocator) |
| + ctx, stop := chromedp.NewContext(allocator) |
| + t.Cleanup(stop) |
| + b := &consentBrowser{t: t, rig: r, ctx: ctx} |
| + chromedp.ListenTarget(ctx, func(event any) { |
| + if entry, ok := event.(*cdplog.EventEntryAdded); ok { |
| + b.mu.Lock() |
| + b.logs = append(b.logs, entry.Entry.Text) |
| + b.mu.Unlock() |
| + } |
| + }) |
| + if err := chromedp.Run(ctx, cdplog.Enable(), network.Enable()); err != nil { |
| + t.Fatalf("start browser: %v", err) |
| + } |
| + return b |
| +} |
| + |
| +// state describes where the browser is, for failure messages. |
| +func (b *consentBrowser) state() string { |
| + ctx, cancel := context.WithTimeout(b.ctx, 3*time.Second) |
| + defer cancel() |
| + var location, body string |
| + _ = chromedp.Run(ctx, chromedp.Location(&location), chromedp.Evaluate(`document.body ? document.body.innerText : ""`, &body)) |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return fmt.Sprintf("at %s\npage: %s\nconsole: %s\nposted Origin: %q", location, body, strings.Join(b.logs, " | "), b.rig.postedOrigins()) |
| +} |
| + |
| +func (b *consentBrowser) run(what string, actions ...chromedp.Action) { |
| + b.t.Helper() |
| + ctx, cancel := context.WithTimeout(b.ctx, browserTimeout) |
| + defer cancel() |
| + if err := chromedp.Run(ctx, actions...); err != nil { |
| + b.t.Fatalf("%s: %v\n%s", what, err, b.state()) |
| + } |
| +} |
| + |
| +// openConsent walks through sign-in and stops on the consent page. |
| +func (b *consentBrowser) openConsent(clientID string) { |
| + b.t.Helper() |
| + b.run("open consent page", chromedp.Navigate(b.rig.authorizeURL(clientID)), chromedp.WaitVisible(consentButton, chromedp.ByQuery)) |
| +} |
| + |
| +func (b *consentBrowser) click(selector string) { |
| + b.t.Helper() |
| + b.run("press "+selector, chromedp.Click(selector, chromedp.ByQuery)) |
| +} |
| + |
| +// landOnClient waits for the browser to arrive at the client's redirect URI. |
| +func (b *consentBrowser) landOnClient() clientCall { |
| + b.t.Helper() |
| + deadline := time.Now().Add(browserTimeout) |
| + for time.Now().Before(deadline) { |
| + var location, body string |
| + 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] |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + b.t.Fatalf("browser never reached the client's redirect\n%s", b.state()) |
| + return clientCall{} |
| +} |
| + |
| +func wantCode(t *testing.T, rig *consentRig, call clientCall) { |
| + t.Helper() |
| + if call.query.Get("code") == "" || call.query.Get("error") != "" || call.query.Get("state") != browserState || call.query.Get("iss") != rig.origin { |
| + t.Fatalf("callback query %v", call.query) |
| + } |
| + if call.referer != "" { |
| + t.Fatalf("consent page leaked a referrer to the client: %q", call.referer) |
| + } |
| +} |
| + |
| +func wantRefused(t *testing.T, rig *consentRig, call clientCall, code string) { |
| + t.Helper() |
| + if call.query.Get("error") != code || call.query.Get("code") != "" || call.query.Get("state") != browserState || call.query.Get("iss") != rig.origin { |
| + t.Fatalf("callback query %v, want error %s", call.query, code) |
| + } |
| + if call.referer != "" { |
| + t.Fatalf("consent page leaked a referrer to the client: %q", call.referer) |
| + } |
| +} |
| + |
| +func TestBrowserAllowLandsOnClientWithCode(t *testing.T) { |
| + rig := newConsentRig(t) |
| + b := rig.browser(t) |
| + b.openConsent(thirdPartyID) |
| + if calls := rig.clientCalls(); len(calls) != 0 { |
| + t.Fatalf("client called before consent: %v", calls) |
| + } |
| + b.click(consentButton) |
| + wantCode(t, rig, b.landOnClient()) |
| + if origins := rig.postedOrigins(); len(origins) != 1 || origins[0] != rig.origin { |
| + t.Fatalf("form posted Origin %q, want %q", origins, rig.origin) |
| + } |
| +} |
| + |
| +func TestBrowserCancelLandsOnClientWithRefusal(t *testing.T) { |
| + rig := newConsentRig(t) |
| + b := rig.browser(t) |
| + b.openConsent(thirdPartyID) |
| + b.click(cancelButton) |
| + wantRefused(t, rig, b.landOnClient(), "access_denied") |
| +} |
| + |
| +func TestBrowserExpiredConsentCookieGoesBackToClient(t *testing.T) { |
| + rig := newConsentRig(t) |
| + b := rig.browser(t) |
| + b.openConsent(thirdPartyID) |
| + b.run("expire consent cookie", network.DeleteCookies(consentCookie).WithURL(rig.origin+"/")) |
| + b.click(consentButton) |
| + wantRefused(t, rig, b.landOnClient(), "access_denied") |
| +} |
| + |
| +func TestBrowserStaleSignInGoesBackToClient(t *testing.T) { |
| + rig := newConsentRig(t) |
| + b := rig.browser(t) |
| + b.openConsent(thirdPartyID) |
| + rig.ageSignIn(6 * time.Minute) |
| + b.click(consentButton) |
| + wantRefused(t, rig, b.landOnClient(), "access_denied") |
| +} |
| + |
| +func TestBrowserFirstPartyReusesHomeSessionButStillAsksConsent(t *testing.T) { |
| + rig := newConsentRig(t) |
| + b := rig.browser(t) |
| + b.openConsent(firstPartyID) |
| + asks := rig.homeAsks() |
| + if len(asks) != 1 || asks[0].Has("max_age") { |
| + t.Fatalf("first-party sign-in forced fresh: %v", asks) |
| + } |
| + if calls := rig.clientCalls(); len(calls) != 0 { |
| + t.Fatalf("first-party client skipped the consent page: %v", calls) |
| + } |
| + b.click(consentButton) |
| + wantCode(t, rig, b.landOnClient()) |
| +} |
| + |
| +func TestBrowserFirstPartyKeepsAnOlderConnectSession(t *testing.T) { |
| + rig := newConsentRig(t) |
| + b := rig.browser(t) |
| + b.openConsent(firstPartyID) |
| + rig.ageSignIn(30 * time.Minute) |
| + b.openConsent(firstPartyID) |
| + if asks := rig.homeAsks(); len(asks) != 1 { |
| + t.Fatalf("first-party client went back to Home: %v", asks) |
| + } |
| + b.click(consentButton) |
| + wantCode(t, rig, b.landOnClient()) |
| +} |
| + |
| +func TestBrowserOtherClientsStillSignInFresh(t *testing.T) { |
| + rig := newConsentRig(t) |
| + b := rig.browser(t) |
| + b.openConsent(thirdPartyID) |
| + asks := rig.homeAsks() |
| + if len(asks) != 1 || asks[0].Get("max_age") != "300" { |
| + t.Fatalf("third-party sign-in was not forced fresh: %v", asks) |
| + } |
| + rig.ageSignIn(6 * time.Minute) |
| + b.openConsent(thirdPartyID) |
| + asks = rig.homeAsks() |
| + if len(asks) != 2 || asks[1].Get("max_age") != "300" { |
| + t.Fatalf("aged session reused for a third-party client: %v", asks) |
| + } |
| +} |
| + |
| +// A session earned through the first-party door must not open another client's. |
| +func TestBrowserFirstPartySessionDoesNotCarryOverToOtherClients(t *testing.T) { |
| + rig := newConsentRig(t) |
| + b := rig.browser(t) |
| + b.openConsent(firstPartyID) |
| + b.openConsent(thirdPartyID) |
| + asks := rig.homeAsks() |
| + if len(asks) != 2 || asks[0].Has("max_age") || asks[1].Get("max_age") != "300" { |
| + t.Fatalf("first-party session satisfied a third-party client: %v", asks) |
| + } |
| +} |
| + |
| +// Which door a sign-in takes is decided from the request it will return to. |
| +func TestSignInForcesFreshExceptForAFirstPartyClient(t *testing.T) { |
| + rig := newConsentRig(t) |
| + local := func(raw string) string { return strings.TrimPrefix(raw, rig.origin) } |
| + first := local(rig.authorizeURL(firstPartyID)) |
| + for _, tc := range []struct { |
| + name, returnTo string |
| + fresh bool |
| + }{ |
| + {"first-party client", first, false}, |
| + {"client with no first_party field", local(rig.authorizeURL(thirdPartyID)), true}, |
| + {"Oficina CLI", local(rig.authorizeURL(client.ClientID)), true}, |
| + {"unknown client", local(rig.authorizeURL("nobody")), true}, |
| + {"first-party client with another redirect", strings.ReplaceAll(first, "client.example.test", "evil.example.test"), true}, |
| + {"first-party client named twice", first + "&client_id=" + thirdPartyID, true}, |
| + {"connections page", "/connections", true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + r := httptest.NewRequest("GET", rig.origin+"/auth/start?"+url.Values{"return_to": {tc.returnTo}}.Encode(), nil) |
| + w := httptest.NewRecorder() |
| + rig.handler.ServeHTTP(w, r) |
| + if w.Code != 303 { |
| + t.Fatalf("status %d: %s", w.Code, w.Body) |
| + } |
| + target, err := url.Parse(w.Header().Get("Location")) |
| + if err != nil || target.Path != "/authorize" { |
| + t.Fatalf("redirected to %q", w.Header().Get("Location")) |
| + } |
| + if got := target.Query().Get("max_age"); tc.fresh && got != "300" || !tc.fresh && target.Query().Has("max_age") { |
| + t.Fatalf("max_age %q, want fresh=%v", got, tc.fresh) |
| + } |
| + }) |
| + } |
| + t.Run("no return path", func(t *testing.T) { |
| + w := httptest.NewRecorder() |
| + rig.handler.ServeHTTP(w, httptest.NewRequest("GET", rig.origin+"/auth/start", nil)) |
| + target, err := url.Parse(w.Header().Get("Location")) |
| + if err != nil || target.Query().Get("max_age") != "300" { |
| + t.Fatalf("%d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + }) |
| +} |
diff --git a/connection/server.go b/connection/server.go| index d893dfe..667d992 100644 |
| --- a/connection/server.go |
| +++ b/connection/server.go |
| @@ -98,9 +98,17 @@ func New(ctx context.Context, cfg Config, d *db.DB, logger *slog.Logger) (*Serve |
| } |
| return s.Subject |
| } |
| - consumer, err := handoff.NewConsumer(handoff.ConsumerConfig{Store: identity, ConsumerID: cfg.ConsumerID, RequireFreshAuth: true, CurrentSubject: current, Complete: func(w http.ResponseWriter, r *http.Request, c assertion.Claims) error { |
| + signIn := handoff.ConsumerConfig{Store: identity, ConsumerID: cfg.ConsumerID, RequireFreshAuth: true, CurrentSubject: current, Complete: func(w http.ResponseWriter, r *http.Request, c assertion.Claims) error { |
| return sess.SignIn(w, r, sessions.Session{Subject: c.Subject, Method: "home-assertion", AuthTime: time.Unix(c.AuthTime, 0)}) |
| - }}) |
| + }} |
| + consumer, err := handoff.NewConsumer(signIn) |
| + if err != nil { |
| + return nil, err |
| + } |
| + // Connecting a first-party client reuses the person's Home session. The |
| + // session still records the real AuthTime, so it never passes as fresh. |
| + signIn.RequireFreshAuth = false |
| + reuse, err := handoff.NewConsumer(signIn) |
| if err != nil { |
| return nil, err |
| } |
| @@ -131,12 +139,19 @@ func New(ctx context.Context, cfg Config, d *db.DB, logger *slog.Logger) (*Serve |
| if err != nil { |
| return nil, err |
| } |
| - grants, err := grant.NewServer(grant.Config{IdentityIssuer: cfg.HomeIssuer, Origin: cfg.Origin, Resource: cfg.Origin + "/mcp", Store: store, ConsentKey: consentKey, Clients: clients, Scopes: scopes, Subject: fresh, Teams: provider.teams, ResourceTeams: provider.resourceTeams, SignInPath: handoff.StartPath}) |
| + grants, err := grant.NewServer(grant.Config{IdentityIssuer: cfg.HomeIssuer, Origin: cfg.Origin, Resource: cfg.Origin + "/mcp", Store: store, ConsentKey: consentKey, Clients: clients, Scopes: scopes, Subject: fresh, SessionSubject: current, Teams: provider.teams, ResourceTeams: provider.resourceTeams, SignInPath: handoff.StartPath}) |
| if err != nil { |
| return nil, err |
| } |
| mux := http.NewServeMux() |
| - mux.HandleFunc(handoff.StartPath, consumer.Start) |
| + mux.HandleFunc(handoff.StartPath, func(w http.ResponseWriter, r *http.Request) { |
| + q, err := url.ParseQuery(r.URL.RawQuery) |
| + if err == nil && len(q) == 1 && len(q["return_to"]) == 1 && grants.ReusesSession(q["return_to"][0]) { |
| + reuse.Start(w, r) |
| + return |
| + } |
| + consumer.Start(w, r) |
| + }) |
| mux.HandleFunc(handoff.CallbackPath, consumer.Callback) |
| mux.HandleFunc(handoff.FinishPath, consumer.Finish) |
| mcpHandler, err := registry.MCPAtOrigin(grants, cfg.Origin) |
diff --git a/go.mod b/go.mod| index 42d979f..5cd003f 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -5,6 +5,8 @@ go 1.25.0 |
| require ( |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 |
| + github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 |
| + github.com/chromedp/chromedp v0.14.2 |
| github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 |
| github.com/gofrs/flock v0.12.1 |
| github.com/google/uuid v1.6.0 |
| @@ -16,8 +18,12 @@ require ( |
| ) |
| require ( |
| + github.com/chromedp/sysutil v1.1.0 // indirect |
| github.com/danieljoos/wincred v1.2.3 // indirect |
| github.com/dustin/go-humanize v1.0.1 // indirect |
| + github.com/gobwas/httphead v0.1.0 // indirect |
| + github.com/gobwas/pool v0.2.1 // indirect |
| + github.com/gobwas/ws v1.4.0 // indirect |
| github.com/godbus/dbus/v5 v5.2.2 // indirect |
| github.com/google/jsonschema-go v0.4.3 // indirect |
| github.com/jinzhu/inflection v1.0.0 // indirect |
diff --git a/go.sum b/go.sum| index ee7d97e..14c7eb0 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -4,6 +4,12 @@ amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 h1:K2PXcCKf |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060/go.mod h1:WmC8TAIfqjAkSwmD+FCTqr7VuqAO5FaX03HlV49K608= |
| amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM= |
| amadan.net/rastrillo/rastrillo/money v0.1.0/go.mod h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U= |
| +github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 h1:UQ4AU+BGti3Sy/aLU8KVseYKNALcX9UXY6DfpwQ6J8E= |
| +github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k= |
| +github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM= |
| +github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo= |
| +github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM= |
| +github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8= |
| github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= |
| github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= |
| github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= |
| @@ -16,6 +22,12 @@ github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9 |
| github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M= |
| github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc= |
| github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= |
| +github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= |
| +github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= |
| +github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= |
| +github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= |
| +github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs= |
| +github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc= |
| github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= |
| github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= |
| github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E= |
| @@ -38,6 +50,8 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= |
| github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= |
| github.com/keymaildev/signin v0.1.1 h1:gO+1IAM99sqUkBtCezkgGxab+/DOrqwDxd5H32N1s9Q= |
| github.com/keymaildev/signin v0.1.1/go.mod h1:Eb/sCmEel1jlcdkgPOrNeMn5jvxzoFvJrdjDUxOBHls= |
| +github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo= |
| +github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs= |
| github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= |
| github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= |
| github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= |
| @@ -46,6 +60,8 @@ github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6 |
| github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts= |
| github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= |
| github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= |
| +github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw= |
| +github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= |
| github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= |
| github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= |
diff --git a/grant/consent_test.go b/grant/consent_test.go| new file mode 100644 |
| index 0000000..4550d56 |
| --- /dev/null |
| +++ b/grant/consent_test.go |
| @@ -0,0 +1,436 @@ |
| +package grant |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +const ( |
| + baseRedirect = "https://base.example/callback" |
| + otherRedirect = "https://other.example/oauth/done" |
| + cliRedirect = "http://127.0.0.1:4567/callback" |
| +) |
| + |
| +var consentClients = []Client{ |
| + {ID: "oficina-cli", Name: "Oficina CLI", Loopback: true}, |
| + {ID: "base", Name: "Base", Redirects: []string{baseRedirect}, FirstParty: true}, |
| + {ID: "other", Name: "Other Host", Redirects: []string{otherRedirect}}, |
| +} |
| + |
| +// consentServer's sessions are named by the Test-Session header: "fresh" has |
| +// just signed in, "older" signed in a while ago, and "stranger" is someone else. |
| +func consentServer(t *testing.T, clients []Client, reuse bool) (*Server, *httptest.Server) { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", t.TempDir()+"/grants.sqlite") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + db.SetMaxOpenConns(1) |
| + t.Cleanup(func() { db.Close() }) |
| + store, err := NewStore(context.Background(), db) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var handler http.Handler |
| + ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler.ServeHTTP(w, r) })) |
| + t.Cleanup(ts.Close) |
| + cfg := consentConfig(ts.URL, store, clients) |
| + if reuse { |
| + cfg.SessionSubject = func(r *http.Request) string { |
| + switch r.Header.Get("Test-Session") { |
| + case "fresh", "older": |
| + return "opaque-person" |
| + case "stranger": |
| + return "someone-else" |
| + } |
| + return "" |
| + } |
| + } |
| + s, err := NewServer(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + handler = s.Handler() |
| + return s, ts |
| +} |
| + |
| +func consentConfig(origin string, store *Store, clients []Client) Config { |
| + 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 { |
| + switch r.Header.Get("Test-Session") { |
| + case "fresh": |
| + return "opaque-person" |
| + case "stranger": |
| + return "someone-else" |
| + } |
| + return "" |
| + }, Teams: func(context.Context, string) ([]Team, error) { |
| + return []Team{{ID: "acme", Name: "Acme"}}, nil |
| + }, SignInPath: "/signin"} |
| +} |
| + |
| +func consentURL(base, client, redirect string) string { |
| + return authorizeURL(base, url.Values{"client_id": {client}, "redirect_uri": {redirect}}) |
| +} |
| + |
| +func noRedirects(ts *httptest.Server) *http.Client { |
| + c := *ts.Client() |
| + c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| + return &c |
| +} |
| + |
| +// consentPage loads the consent page and returns its ticket and cookies. |
| +func consentPage(t *testing.T, ts *httptest.Server, client, redirect, session string) (string, []*http.Cookie) { |
| + t.Helper() |
| + resp, body := fetchAs(t, ts, consentURL(ts.URL, client, redirect), session) |
| + if resp.StatusCode != 200 { |
| + t.Fatalf("consent page %d: %s", resp.StatusCode, body) |
| + } |
| + m := regexp.MustCompile(`name="ticket" value="([^"]+)"`).FindStringSubmatch(body) |
| + if len(m) != 2 { |
| + t.Fatal("no ticket on the consent page") |
| + } |
| + return m[1], resp.Cookies() |
| +} |
| + |
| +func fetchAs(t *testing.T, ts *httptest.Server, raw, session string) (*http.Response, string) { |
| + t.Helper() |
| + req, _ := http.NewRequest("GET", raw, nil) |
| + req.Header.Set("Test-Session", session) |
| + resp, err := noRedirects(ts).Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + body, _ := io.ReadAll(resp.Body) |
| + return resp, string(body) |
| +} |
| + |
| +type answer struct { |
| + ticket, decision, session string |
| + origins []string |
| + cookies []*http.Cookie |
| +} |
| + |
| +func (a answer) post(t *testing.T, ts *httptest.Server) (*http.Response, string) { |
| + t.Helper() |
| + form := url.Values{"ticket": {a.ticket}, "decision": {a.decision}, "team": {"acme"}} |
| + if a.decision == "" { |
| + form.Del("decision") |
| + } |
| + req, _ := http.NewRequest("POST", ts.URL+"/oauth/authorize", strings.NewReader(form.Encode())) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Test-Session", a.session) |
| + for _, origin := range a.origins { |
| + req.Header.Add("Origin", origin) |
| + } |
| + for _, cookie := range a.cookies { |
| + req.AddCookie(cookie) |
| + } |
| + resp, err := noRedirects(ts).Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + body, _ := io.ReadAll(resp.Body) |
| + return resp, string(body) |
| +} |
| + |
| +func wantPlainRefusal(t *testing.T, resp *http.Response, body string, status int) { |
| + t.Helper() |
| + if resp.StatusCode != status || resp.Header.Get("Location") != "" { |
| + t.Fatalf("status %d location %q, want %d and no redirect", resp.StatusCode, resp.Header.Get("Location"), status) |
| + } |
| + if !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/html") || strings.Contains(body, `{"error"`) { |
| + t.Fatalf("a person was shown %q: %s", resp.Header.Get("Content-Type"), body) |
| + } |
| +} |
| + |
| +func wantClientRefusal(t *testing.T, resp *http.Response, redirect string) { |
| + t.Helper() |
| + if resp.StatusCode != 303 { |
| + t.Fatalf("status %d, want a redirect to the client", resp.StatusCode) |
| + } |
| + 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 q := loc.Query(); q.Get("error") != "access_denied" || q.Get("state") != testState || q.Get("code") != "" || q.Get("iss") == "" { |
| + t.Fatalf("redirect query %v", q) |
| + } |
| +} |
| + |
| +func TestApproveRefusesAnyOtherOrigin(t *testing.T) { |
| + _, ts := consentServer(t, consentClients, true) |
| + ticket, cookies := consentPage(t, ts, "other", otherRedirect, "fresh") |
| + for name, origins := range map[string][]string{ |
| + "cross-site": {"https://evil.example"}, |
| + "null": {"null"}, |
| + "missing": nil, |
| + "trailing": {ts.URL + "/"}, |
| + "other scheme": {strings.Replace(ts.URL, "https://", "http://", 1)}, |
| + "repeated": {ts.URL, ts.URL}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + resp, body := answer{ticket: ticket, decision: "approve", session: "fresh", origins: origins, cookies: cookies}.post(t, ts) |
| + wantPlainRefusal(t, resp, body, 403) |
| + }) |
| + } |
| + // 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")) |
| + } |
| +} |
| + |
| +func directive(csp, name string) string { |
| + for _, part := range strings.Split(csp, ";") { |
| + if part = strings.TrimSpace(part); strings.HasPrefix(part, name+" ") { |
| + return part |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +func TestConsentFormActionNamesOnlyThisClient(t *testing.T) { |
| + _, ts := consentServer(t, consentClients, true) |
| + for _, tc := range []struct{ client, redirect, want string }{ |
| + {"base", baseRedirect, "form-action 'self' https://base.example"}, |
| + {"other", otherRedirect, "form-action 'self' https://other.example"}, |
| + {"oficina-cli", cliRedirect, "form-action 'self' http://127.0.0.1:4567"}, |
| + } { |
| + resp, _ := fetchAs(t, ts, consentURL(ts.URL, tc.client, tc.redirect), "fresh") |
| + csp := resp.Header.Get("Content-Security-Policy") |
| + if got := directive(csp, "form-action"); got != tc.want { |
| + t.Fatalf("%s: form-action %q, want %q", tc.client, got, tc.want) |
| + } |
| + if strings.Contains(csp, "*") { |
| + t.Fatalf("%s: wildcard in %q", tc.client, csp) |
| + } |
| + } |
| + // Pages that never redirect off-site keep the strict policy. |
| + resp, _ := fetchAs(t, ts, ts.URL+"/connections", "fresh") |
| + if got := directive(resp.Header.Get("Content-Security-Policy"), "form-action"); got != "form-action 'self'" { |
| + t.Fatalf("connections form-action %q", got) |
| + } |
| +} |
| + |
| +func TestRedirectThatCouldWidenThePolicyIsNotRegistered(t *testing.T) { |
| + db, err := sql.Open("sqlite", t.TempDir()+"/grants.sqlite") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + db.SetMaxOpenConns(1) |
| + t.Cleanup(func() { db.Close() }) |
| + store, err := NewStore(context.Background(), db) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, redirect := range []string{"https://*.example/callback", "https://a.example,b.example/callback", "https://a.example;script-src/callback"} { |
| + if _, err := NewServer(consentConfig("https://connect.example", store, []Client{{ID: "wide", Name: "Wide", Redirects: []string{redirect}}})); err == nil { |
| + t.Fatalf("registered %s", redirect) |
| + } |
| + } |
| +} |
| + |
| +func TestConsentPageSendsItsOriginButNoReferrerElsewhere(t *testing.T) { |
| + _, ts := consentServer(t, consentClients, true) |
| + resp, _ := fetchAs(t, ts, consentURL(ts.URL, "other", otherRedirect), "fresh") |
| + if got := resp.Header.Get("Referrer-Policy"); got != "same-origin" { |
| + t.Fatalf("Referrer-Policy %q", got) |
| + } |
| +} |
| + |
| +func TestTrustedTicketRefusalsGoBackToTheClient(t *testing.T) { |
| + for name, change := range map[string]func(*answer, *Server){ |
| + "expired consent cookie": func(a *answer, _ *Server) { a.cookies = nil }, |
| + "wrong consent cookie": func(a *answer, _ *Server) { |
| + a.cookies = []*http.Cookie{{Name: "__Host-oficina-consent", Value: "not-this-ticket"}} |
| + }, |
| + "stale sign-in": func(a *answer, _ *Server) { a.session = "older" }, |
| + "signed out": func(a *answer, _ *Server) { a.session = "" }, |
| + "another person": func(a *answer, _ *Server) { |
| + a.session = "stranger" |
| + }, |
| + "expired ticket": func(_ *answer, s *Server) { |
| + later := time.Now().Add(6 * time.Minute) |
| + s.cfg.Store.Now = func() time.Time { return later } |
| + }, |
| + } { |
| + for _, decision := range []string{"approve", "deny"} { |
| + t.Run(name+"/"+decision, func(t *testing.T) { |
| + s, ts := consentServer(t, consentClients, true) |
| + 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) |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestUntrustedTicketsGetAPlainRefusal(t *testing.T) { |
| + s, ts := consentServer(t, consentClients, true) |
| + _, cookies := consentPage(t, ts, "other", otherRedirect, "fresh") |
| + sealed := func(tk ticket) string { |
| + t.Helper() |
| + tk.Expires = time.Now().Add(time.Minute).Unix() |
| + raw, err := s.seal(tk) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return raw |
| + } |
| + for name, ticket := range map[string]string{ |
| + "unreadable": "not-a-ticket", |
| + "another purpose": sealed(ticket{Purpose: "revoke", Client: "other", Redirect: otherRedirect, State: testState, Subject: "opaque-person", Nonce: "n"}), |
| + "unregistered client": sealed(ticket{Purpose: "authorize", Client: "gone", Redirect: otherRedirect, State: testState, Subject: "opaque-person", Nonce: "n"}), |
| + "foreign redirect": sealed(ticket{Purpose: "authorize", Client: "other", Redirect: "https://evil.example/callback", State: testState, Subject: "opaque-person", Nonce: "n"}), |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + resp, body := answer{ticket: ticket, decision: "approve", session: "fresh", origins: []string{ts.URL}, cookies: cookies}.post(t, ts) |
| + wantPlainRefusal(t, resp, body, 403) |
| + }) |
| + } |
| + t.Run("incomplete form", func(t *testing.T) { |
| + resp, body := answer{ticket: "x", session: "fresh", origins: []string{ts.URL}, cookies: cookies}.post(t, ts) |
| + wantPlainRefusal(t, resp, body, 400) |
| + }) |
| + t.Run("unknown client on the way in", func(t *testing.T) { |
| + resp, body := fetchAs(t, ts, consentURL(ts.URL, "nobody", otherRedirect), "fresh") |
| + wantPlainRefusal(t, resp, body, 400) |
| + }) |
| +} |
| + |
| +func TestStorageFailureOnTheConsentPathIsNotRawJSON(t *testing.T) { |
| + s, ts := consentServer(t, consentClients, true) |
| + if err := s.cfg.Store.DB.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + resp, body := fetchAs(t, ts, consentURL(ts.URL, "other", otherRedirect), "fresh") |
| + wantPlainRefusal(t, resp, body, 503) |
| + // Machine clients keep their JSON error. |
| + token, err := noRedirects(ts).Post(ts.URL+"/oauth/token", "application/x-www-form-urlencoded", strings.NewReader("grant_type=refresh_token")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer token.Body.Close() |
| + if token.StatusCode != 503 || !strings.HasPrefix(token.Header.Get("Content-Type"), "application/json") { |
| + t.Fatalf("token endpoint %d %q", token.StatusCode, token.Header.Get("Content-Type")) |
| + } |
| +} |
| + |
| +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) |
| + } |
| + resp, body := a.post(t, ts) |
| + wantPlainRefusal(t, resp, body, 400) |
| +} |
| + |
| +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")) |
| + } |
| +} |
| + |
| +func TestFirstPartyClientStillNeedsASessionAndConsent(t *testing.T) { |
| + _, ts := consentServer(t, consentClients, true) |
| + resp, _ := fetchAs(t, ts, consentURL(ts.URL, "base", baseRedirect), "") |
| + if resp.StatusCode != 303 || !strings.HasPrefix(resp.Header.Get("Location"), "/signin?") { |
| + t.Fatalf("no session: %d %q", resp.StatusCode, resp.Header.Get("Location")) |
| + } |
| + resp, body := fetchAs(t, ts, consentURL(ts.URL, "base", baseRedirect), "older") |
| + if resp.StatusCode != 200 || !strings.Contains(body, "Allow access") || strings.Contains(resp.Header.Get("Location"), "code=") { |
| + 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) |
| +} |
| + |
| +func TestOtherClientsAreForcedToSignInFresh(t *testing.T) { |
| + _, ts := consentServer(t, consentClients, true) |
| + for _, tc := range []struct{ client, redirect string }{{"other", otherRedirect}, {"oficina-cli", cliRedirect}} { |
| + resp, _ := fetchAs(t, ts, consentURL(ts.URL, tc.client, tc.redirect), "older") |
| + if resp.StatusCode != 303 || !strings.HasPrefix(resp.Header.Get("Location"), "/signin?") { |
| + t.Fatalf("%s reused an older session: %d %q", tc.client, resp.StatusCode, resp.Header.Get("Location")) |
| + } |
| + } |
| +} |
| + |
| +func TestMissingFirstPartyFieldStaysStrict(t *testing.T) { |
| + var clients []Client |
| + raw := `[{"id":"unmarked","name":"Unmarked","redirects":["` + otherRedirect + `"]},{"id":"declined","name":"Declined","redirects":["` + baseRedirect + `"],"first_party":false}]` |
| + if err := json.Unmarshal([]byte(raw), &clients); err != nil { |
| + t.Fatal(err) |
| + } |
| + s, ts := consentServer(t, clients, true) |
| + for _, c := range clients { |
| + if c.FirstParty { |
| + t.Fatalf("%s defaulted to first-party", c.ID) |
| + } |
| + target := consentURL(ts.URL, c.ID, c.Redirects[0]) |
| + resp, _ := fetchAs(t, ts, target, "older") |
| + if resp.StatusCode != 303 || !strings.HasPrefix(resp.Header.Get("Location"), "/signin?") { |
| + t.Fatalf("%s reused an older session: %d", c.ID, resp.StatusCode) |
| + } |
| + if s.ReusesSession(strings.TrimPrefix(target, ts.URL)) { |
| + t.Fatalf("%s sign-in would not be forced fresh", c.ID) |
| + } |
| + } |
| +} |
| + |
| +func TestFirstPartyWithoutASessionReaderStaysStrict(t *testing.T) { |
| + s, ts := consentServer(t, consentClients, false) |
| + target := consentURL(ts.URL, "base", baseRedirect) |
| + resp, _ := fetchAs(t, ts, target, "older") |
| + if resp.StatusCode != 303 || !strings.HasPrefix(resp.Header.Get("Location"), "/signin?") { |
| + t.Fatalf("reused an older session: %d", resp.StatusCode) |
| + } |
| + if s.ReusesSession(strings.TrimPrefix(target, ts.URL)) { |
| + t.Fatal("sign-in would not be forced fresh") |
| + } |
| +} |
| + |
| +func TestReusesSessionReadsOnlyAnExactFirstPartyRequest(t *testing.T) { |
| + s, ts := consentServer(t, consentClients, true) |
| + exact := strings.TrimPrefix(consentURL(ts.URL, "base", baseRedirect), ts.URL) |
| + if !s.ReusesSession(exact) { |
| + t.Fatal("first-party authorize request not recognised") |
| + } |
| + query := strings.TrimPrefix(exact, "/oauth/authorize") |
| + for name, returnTo := range map[string]string{ |
| + "empty": "", |
| + "other client": strings.TrimPrefix(consentURL(ts.URL, "other", otherRedirect), ts.URL), |
| + "cli": strings.TrimPrefix(consentURL(ts.URL, "oficina-cli", cliRedirect), ts.URL), |
| + "unknown client": strings.TrimPrefix(consentURL(ts.URL, "nobody", baseRedirect), ts.URL), |
| + "foreign redirect": strings.TrimPrefix(consentURL(ts.URL, "base", "https://evil.example/callback"), ts.URL), |
| + "repeated client": exact + "&client_id=other", |
| + "another page": "/connections" + query, |
| + "encoded path": "/oauth%2Fauthorize" + query, |
| + "absolute": "https://evil.example/oauth/authorize" + query, |
| + "scheme-relative": "//evil.example/oauth/authorize" + query, |
| + "unreadable query": exact + "&bad=%zz", |
| + "semicolon in form": exact + ";client_id=other", |
| + } { |
| + if s.ReusesSession(returnTo) { |
| + t.Fatalf("%s: %q treated as first-party", name, returnTo) |
| + } |
| + } |
| +} |
diff --git a/grant/server.go b/grant/server.go| index b80f86a..d1c7e88 100644 |
| --- a/grant/server.go |
| +++ b/grant/server.go |
| @@ -26,6 +26,10 @@ type Client struct { |
| Name string `json:"name"` |
| Redirects []string `json:"redirects"` |
| Loopback bool `json:"loopback"` |
| + // FirstParty lets this client reuse the person's existing Oficina ID session |
| + // when connecting. Left out, the client keeps the five-minute fresh sign-in. |
| + // Every client, first-party included, still needs the consent page and click. |
| + FirstParty bool `json:"first_party"` |
| } |
| type Team struct { |
| ID string `json:"id"` |
| @@ -42,6 +46,9 @@ type Config struct { |
| Scopes map[string]string |
| // Subject reads a verified browser session. Empty means sign-in is needed. |
| Subject func(*http.Request) string |
| + // SessionSubject reads a verified browser session of any age, for first-party |
| + // clients only. Left nil, first-party clients need a fresh sign-in as well. |
| + SessionSubject func(*http.Request) string |
| // Teams reads CURRENT memberships, including on token verification. |
| Teams func(context.Context, string) ([]Team, error) |
| // ResourceTeams rechecks the current app destination for downstream tokens. |
| @@ -112,7 +119,18 @@ func NewServer(cfg Config) (*Server, error) { |
| } |
| func validRedirect(raw string) bool { |
| u, e := url.Parse(raw) |
| - return e == nil && u.Scheme == "https" && u.Host != "" && u.User == nil && u.Fragment == "" |
| + return e == nil && u.Scheme == "https" && u.Host != "" && u.User == nil && u.Fragment == "" && policySafeHost(u.Host) |
| +} |
| + |
| +// policySafeHost keeps a registered redirect's host fit to name in a |
| +// Content-Security-Policy: a wildcard or separator could widen the policy. |
| +func policySafeHost(host string) bool { |
| + for _, c := range []byte(host) { |
| + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '-' || c == ':') { |
| + return false |
| + } |
| + } |
| + return true |
| } |
| func (c Client) validRedirect(raw string) bool { |
| for _, allowed := range c.Redirects { |
| @@ -134,7 +152,18 @@ func (s *Server) seal(t ticket) (string, error) { |
| } |
| return base64.RawURLEncoding.EncodeToString(s.aead.Seal(nonce, nonce, raw, []byte(s.cfg.Origin))), nil |
| } |
| + |
| +// open reads a sealed ticket that is authentic and still in date. |
| func (s *Server) open(raw string) (ticket, error) { |
| + t, err := s.unseal(raw) |
| + if err != nil || t.Expires <= s.cfg.Store.Now().Unix() { |
| + return t, ErrCredential |
| + } |
| + return t, nil |
| +} |
| + |
| +// unseal proves a ticket is this server's own, whatever its age. |
| +func (s *Server) unseal(raw string) (ticket, error) { |
| var t ticket |
| b, err := base64.RawURLEncoding.DecodeString(raw) |
| n := s.aead.NonceSize() |
| @@ -142,11 +171,36 @@ func (s *Server) open(raw string) (ticket, error) { |
| return t, ErrCredential |
| } |
| b, err = s.aead.Open(nil, b[:n], b[n:], []byte(s.cfg.Origin)) |
| - if err != nil || json.Unmarshal(b, &t) != nil || t.Expires <= s.cfg.Store.Now().Unix() { |
| + if err != nil || json.Unmarshal(b, &t) != nil { |
| return t, ErrCredential |
| } |
| return t, nil |
| } |
| + |
| +// subjectFor reads the person behind a consent request. Only a client marked |
| +// first-party may rely on an existing session; the rest need a fresh sign-in. |
| +func (s *Server) subjectFor(client Client, r *http.Request) string { |
| + if client.FirstParty && s.cfg.SessionSubject != nil { |
| + return s.cfg.SessionSubject(r) |
| + } |
| + return s.cfg.Subject(r) |
| +} |
| + |
| +// ReusesSession reports whether a local return path is the authorize request of |
| +// a first-party client, so that signing in for it need not be forced fresh. |
| +// Anything it cannot read exactly keeps the strict sign-in. |
| +func (s *Server) ReusesSession(returnTo string) bool { |
| + u, err := url.ParseRequestURI(returnTo) |
| + if err != nil || u.IsAbs() || u.Host != "" || u.EscapedPath() != "/oauth/authorize" { |
| + return false |
| + } |
| + q, err := url.ParseQuery(u.RawQuery) |
| + if err != nil || !single(q) { |
| + return false |
| + } |
| + client, ok := s.clients[q.Get("client_id")] |
| + return ok && client.FirstParty && s.cfg.SessionSubject != nil && client.validRedirect(q.Get("redirect_uri")) |
| +} |
| func (s *Server) Handler() http.Handler { |
| mux := http.NewServeMux() |
| mux.HandleFunc("GET /.well-known/oauth-authorization-server", s.metadata) |
| @@ -162,7 +216,10 @@ func (s *Server) Handler() http.Handler { |
| mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/connections", 303) }) |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| - w.Header().Set("Referrer-Policy", "no-referrer") |
| + // same-origin, not no-referrer: under no-referrer a browser posts the |
| + // consent form with Origin: null, which approve must refuse. Other sites |
| + // still receive no referrer. |
| + w.Header().Set("Referrer-Policy", "same-origin") |
| w.Header().Set("X-Content-Type-Options", "nosniff") |
| expected, _ := url.Parse(s.cfg.Origin) |
| if r.Host != expected.Host { |
| @@ -170,6 +227,10 @@ func (s *Server) Handler() http.Handler { |
| return |
| } |
| if err := s.cfg.Store.Maintain(r.Context()); err != nil { |
| + if r.URL.Path == "/oauth/authorize" { |
| + refusalPage(w, 503) |
| + return |
| + } |
| fail(w, 503, "temporarily_unavailable") |
| return |
| } |
| @@ -207,12 +268,23 @@ 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. |
| +func consentCSP(redirect string) string { |
| + u, err := url.Parse(redirect) |
| + if err != nil { |
| + return pageCSP |
| + } |
| + 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) { |
| dest, err := url.Parse(redirect) |
| if err != nil { |
| - fail(w, 400, "invalid_request") |
| + refusalPage(w, 400) |
| return |
| } |
| q := dest.Query() |
| @@ -226,17 +298,17 @@ func (s *Server) refuse(w http.ResponseWriter, r *http.Request, redirect, state, |
| } |
| func (s *Server) authorize(w http.ResponseWriter, r *http.Request) { |
| if len(r.URL.RawQuery) > 8192 { |
| - fail(w, 400, "invalid_request") |
| + refusalPage(w, 400) |
| return |
| } |
| q, err := url.ParseQuery(r.URL.RawQuery) |
| if err != nil || !single(q) { |
| - fail(w, 400, "invalid_request") |
| + refusalPage(w, 400) |
| return |
| } |
| client, ok := s.clients[q.Get("client_id")] |
| if !ok || !client.validRedirect(q.Get("redirect_uri")) { |
| - fail(w, 400, "invalid_request") |
| + refusalPage(w, 400) |
| return |
| } |
| @@ -261,7 +333,7 @@ func (s *Server) authorize(w http.ResponseWriter, r *http.Request) { |
| } |
| seen[scope] = true |
| } |
| - subject := s.cfg.Subject(r) |
| + subject := s.subjectFor(client, r) |
| if subject == "" { |
| dest, _ := url.Parse(s.cfg.SignInPath) |
| v := dest.Query() |
| @@ -294,7 +366,7 @@ func (s *Server) authorize(w http.ResponseWriter, r *http.Request) { |
| for _, scope := range scopes { |
| labels = append(labels, s.cfg.Scopes[scope]) |
| } |
| - w.Header().Set("Content-Security-Policy", pageCSP) |
| + w.Header().Set("Content-Security-Policy", consentCSP(redirect)) |
| w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| _ = consent.Execute(w, map[string]any{"Client": client.Name, "Ticket": encoded, "Teams": teams, "Only": len(teams) == 1, "Scopes": labels}) |
| } |
| @@ -337,20 +409,42 @@ const doorClose = `</section></div></main></html>` |
| var consent = template.Must(template.New("consent").Parse(pageHead + `<title>Connect to Oficina</title>` + doorOpen + `<h1>Connect {{.Client}} to Oficina</h1><p>This client will receive the content it reads and can act within the permissions you approve.</p><ul>{{range .Scopes}}<li>{{.}}</li>{{end}}</ul><form method="post" action="/oauth/authorize"><input type="hidden" name="ticket" value="{{.Ticket}}"><fieldset><legend>Choose teams</legend>{{range .Teams}}<label><input type="checkbox" name="team" value="{{.ID}}"{{if $.Only}} checked{{end}}>{{.Name}}</label>{{end}}</fieldset><div class="actions"><button name="decision" value="approve">Allow access</button><button name="decision" value="deny">Cancel</button></div></form>` + doorClose)) |
| +// refusal uses the sign-in door's existing wording for a request that cannot be |
| +// traced to a client it would be safe to send the person back to. |
| +var refusal = template.Must(template.New("refusal").Parse(pageHead + `<title>Connect to Oficina</title>` + doorOpen + `<h1>Unable to sign in. Start again.</h1>` + doorClose)) |
| + |
| +func refusalPage(w http.ResponseWriter, status int) { |
| + w.Header().Set("Content-Security-Policy", pageCSP) |
| + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| + w.WriteHeader(status) |
| + _ = refusal.Execute(w, nil) |
| +} |
| + |
| func (s *Server) approve(w http.ResponseWriter, r *http.Request) { |
| if len(r.Header.Values("Origin")) != 1 || r.Header.Get("Origin") != s.cfg.Origin { |
| - fail(w, 403, "access_denied") |
| + refusalPage(w, 403) |
| return |
| } |
| r.Body = http.MaxBytesReader(w, r.Body, 16384) |
| if r.ParseForm() != nil || len(r.PostForm["ticket"]) != 1 || len(r.PostForm["decision"]) != 1 { |
| - fail(w, 400, "invalid_request") |
| + refusalPage(w, 400) |
| return |
| } |
| - t, err := s.open(r.PostForm.Get("ticket")) |
| + t, err := s.unseal(r.PostForm.Get("ticket")) |
| + if err != nil || t.Purpose != "authorize" { |
| + refusalPage(w, 403) |
| + return |
| + } |
| + client, ok := s.clients[t.Client] |
| + if !ok || !client.validRedirect(t.Redirect) { |
| + refusalPage(w, 403) |
| + return |
| + } |
| + // The ticket is this server's own and names a client and redirect that are |
| + // still registered, so from here a refusal goes back to that client. |
| cookies := r.CookiesNamed("__Host-oficina-consent") |
| - if err != nil || t.Purpose != "authorize" || len(cookies) != 1 || subtle.ConstantTimeCompare([]byte(cookies[0].Value), []byte(t.Nonce)) != 1 || s.cfg.Subject(r) != t.Subject { |
| - fail(w, 403, "access_denied") |
| + 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") |
| return |
| } |
| decision := r.PostForm.Get("decision") |
| @@ -387,7 +481,8 @@ func (s *Server) approve(w http.ResponseWriter, r *http.Request) { |
| } |
| n, _ := result.RowsAffected() |
| if n != 1 { |
| - fail(w, 400, "invalid_request") |
| + // A spent ticket has already answered the client once; it gets no second answer. |
| + refusalPage(w, 400) |
| return |
| } |
| http.SetCookie(w, &http.Cookie{Name: "__Host-oficina-consent", Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1}) |