| 1 | package grant |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/aes" |
| 6 | "crypto/cipher" |
| 7 | "crypto/rand" |
| 8 | "crypto/subtle" |
| 9 | "embed" |
| 10 | "encoding/base64" |
| 11 | "encoding/json" |
| 12 | "errors" |
| 13 | "html/template" |
| 14 | "io" |
| 15 | "net/http" |
| 16 | "net/url" |
| 17 | "sort" |
| 18 | "strings" |
| 19 | "time" |
| 20 | |
| 21 | access "amadan.net/oficina/agent-access.git" |
| 22 | ) |
| 23 | |
| 24 | type Client struct { |
| 25 | ID string `json:"id"` |
| 26 | Name string `json:"name"` |
| 27 | Redirects []string `json:"redirects"` |
| 28 | Loopback bool `json:"loopback"` |
| 29 | // FirstParty lets this client reuse the person's existing Oficina ID session |
| 30 | // when connecting. Left out, the client keeps the five-minute fresh sign-in. |
| 31 | // Every client, first-party included, still needs the consent page and click. |
| 32 | FirstParty bool `json:"first_party"` |
| 33 | } |
| 34 | type Team struct { |
| 35 | ID string `json:"id"` |
| 36 | Name string `json:"name"` |
| 37 | } |
| 38 | type Config struct { |
| 39 | // IdentityIssuer is the fixed Home namespace; it is not the grant Origin. |
| 40 | IdentityIssuer string |
| 41 | Origin string |
| 42 | Resource string |
| 43 | Store *Store |
| 44 | ConsentKey []byte |
| 45 | Clients []Client |
| 46 | Scopes map[string]string |
| 47 | // Subject reads a verified browser session. Empty means sign-in is needed. |
| 48 | Subject func(*http.Request) string |
| 49 | // SessionSubject reads a verified browser session of any age, for first-party |
| 50 | // clients only. Left nil, first-party clients need a fresh sign-in as well. |
| 51 | SessionSubject func(*http.Request) string |
| 52 | // Teams reads CURRENT memberships, including on token verification. |
| 53 | Teams func(context.Context, string) ([]Team, error) |
| 54 | // ResourceTeams rechecks the current app destination for downstream tokens. |
| 55 | // A missing callback refuses downstream introspection. |
| 56 | ResourceTeams func(context.Context, string, string) ([]Team, error) |
| 57 | SignInPath string |
| 58 | } |
| 59 | type Server struct { |
| 60 | cfg Config |
| 61 | aead cipher.AEAD |
| 62 | clients map[string]Client |
| 63 | } |
| 64 | type ticket struct { |
| 65 | Purpose string |
| 66 | Client, Redirect, Resource, Challenge, State, Subject, Nonce string |
| 67 | Scopes []string |
| 68 | Expires int64 |
| 69 | } |
| 70 | |
| 71 | func NewServer(cfg Config) (*Server, error) { |
| 72 | u, err := url.Parse(cfg.Origin) |
| 73 | if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" || cfg.Origin != "https://"+u.Host { |
| 74 | return nil, errors.New("grant issuer must be an HTTPS origin") |
| 75 | } |
| 76 | identity, identityErr := url.Parse(cfg.IdentityIssuer) |
| 77 | if identityErr != nil || identity.Scheme != "https" || identity.Host == "" || identity.User != nil || identity.Path != "" || identity.RawQuery != "" || identity.Fragment != "" || cfg.IdentityIssuer != "https://"+identity.Host || cfg.IdentityIssuer == cfg.Origin { |
| 78 | return nil, errors.New("Home identity issuer must be an HTTPS origin") |
| 79 | } |
| 80 | if cfg.Resource != cfg.Origin+"/mcp" || cfg.Store == nil || cfg.Subject == nil || cfg.Teams == nil || len(cfg.Scopes) == 0 || !strings.HasPrefix(cfg.SignInPath, "/") || strings.HasPrefix(cfg.SignInPath, "//") { |
| 81 | return nil, errors.New("incomplete grant configuration") |
| 82 | } |
| 83 | if len(cfg.ConsentKey) != 32 { |
| 84 | return nil, errors.New("a 32-byte consent encryption key is required") |
| 85 | } |
| 86 | block, err := aes.NewCipher(cfg.ConsentKey) |
| 87 | if err != nil { |
| 88 | return nil, err |
| 89 | } |
| 90 | aead, err := cipher.NewGCM(block) |
| 91 | if err != nil { |
| 92 | return nil, err |
| 93 | } |
| 94 | s := &Server{cfg: cfg, aead: aead, clients: map[string]Client{}} |
| 95 | for _, client := range cfg.Clients { |
| 96 | if client.ID == "" || client.Name == "" { |
| 97 | return nil, errors.New("invalid OAuth client") |
| 98 | } |
| 99 | if _, ok := s.clients[client.ID]; ok { |
| 100 | return nil, errors.New("duplicate OAuth client") |
| 101 | } |
| 102 | for _, raw := range client.Redirects { |
| 103 | if !validRedirect(raw) { |
| 104 | return nil, errors.New("invalid client redirect") |
| 105 | } |
| 106 | } |
| 107 | if len(client.Redirects) == 0 && !client.Loopback { |
| 108 | return nil, errors.New("client needs a redirect") |
| 109 | } |
| 110 | s.clients[client.ID] = client |
| 111 | } |
| 112 | if _, err = cfg.Store.DB.Exec(`CREATE TABLE IF NOT EXISTS agent_pending(hash TEXT PRIMARY KEY, expires INTEGER NOT NULL)`); err != nil { |
| 113 | return nil, err |
| 114 | } |
| 115 | if err := cfg.Store.bindIdentityIssuer(context.Background(), cfg.IdentityIssuer); err != nil { |
| 116 | return nil, err |
| 117 | } |
| 118 | return s, nil |
| 119 | } |
| 120 | func validRedirect(raw string) bool { |
| 121 | u, e := url.Parse(raw) |
| 122 | return e == nil && u.Scheme == "https" && u.Host != "" && u.User == nil && u.Fragment == "" && policySafeHost(u.Host) |
| 123 | } |
| 124 | |
| 125 | // policySafeHost keeps a registered redirect's host fit to name in a |
| 126 | // Content-Security-Policy: a wildcard or separator could widen the policy. |
| 127 | func policySafeHost(host string) bool { |
| 128 | for _, c := range []byte(host) { |
| 129 | if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '-' || c == ':') { |
| 130 | return false |
| 131 | } |
| 132 | } |
| 133 | return true |
| 134 | } |
| 135 | func (c Client) validRedirect(raw string) bool { |
| 136 | for _, allowed := range c.Redirects { |
| 137 | if raw == allowed { |
| 138 | return true |
| 139 | } |
| 140 | } |
| 141 | u, e := url.Parse(raw) |
| 142 | return c.Loopback && e == nil && u.Scheme == "http" && u.Hostname() == "127.0.0.1" && u.Port() != "" && u.Path == "/callback" && u.User == nil && u.RawQuery == "" && u.Fragment == "" |
| 143 | } |
| 144 | func (s *Server) seal(t ticket) (string, error) { |
| 145 | raw, err := json.Marshal(t) |
| 146 | if err != nil { |
| 147 | return "", err |
| 148 | } |
| 149 | nonce := make([]byte, s.aead.NonceSize()) |
| 150 | if _, err = rand.Read(nonce); err != nil { |
| 151 | return "", err |
| 152 | } |
| 153 | return base64.RawURLEncoding.EncodeToString(s.aead.Seal(nonce, nonce, raw, []byte(s.cfg.Origin))), nil |
| 154 | } |
| 155 | |
| 156 | // open reads a sealed ticket that is authentic and still in date. |
| 157 | func (s *Server) open(raw string) (ticket, error) { |
| 158 | t, err := s.unseal(raw) |
| 159 | if err != nil || t.Expires <= s.cfg.Store.Now().Unix() { |
| 160 | return t, ErrCredential |
| 161 | } |
| 162 | return t, nil |
| 163 | } |
| 164 | |
| 165 | // unseal proves a ticket is this server's own, whatever its age. |
| 166 | func (s *Server) unseal(raw string) (ticket, error) { |
| 167 | var t ticket |
| 168 | b, err := base64.RawURLEncoding.DecodeString(raw) |
| 169 | n := s.aead.NonceSize() |
| 170 | if err != nil || len(b) < n || len(b) > 16384 { |
| 171 | return t, ErrCredential |
| 172 | } |
| 173 | b, err = s.aead.Open(nil, b[:n], b[n:], []byte(s.cfg.Origin)) |
| 174 | if err != nil || json.Unmarshal(b, &t) != nil { |
| 175 | return t, ErrCredential |
| 176 | } |
| 177 | return t, nil |
| 178 | } |
| 179 | |
| 180 | // subjectFor reads the person behind a consent request. Only a client marked |
| 181 | // first-party may rely on an existing session; the rest need a fresh sign-in. |
| 182 | func (s *Server) subjectFor(client Client, r *http.Request) string { |
| 183 | if client.FirstParty && s.cfg.SessionSubject != nil { |
| 184 | return s.cfg.SessionSubject(r) |
| 185 | } |
| 186 | return s.cfg.Subject(r) |
| 187 | } |
| 188 | |
| 189 | // ReusesSession reports whether a local return path is the authorize request of |
| 190 | // a first-party client, so that signing in for it need not be forced fresh. |
| 191 | // Anything it cannot read exactly keeps the strict sign-in. |
| 192 | func (s *Server) ReusesSession(returnTo string) bool { |
| 193 | u, err := url.ParseRequestURI(returnTo) |
| 194 | if err != nil || u.IsAbs() || u.Host != "" || u.EscapedPath() != "/oauth/authorize" { |
| 195 | return false |
| 196 | } |
| 197 | q, err := url.ParseQuery(u.RawQuery) |
| 198 | if err != nil || !single(q) { |
| 199 | return false |
| 200 | } |
| 201 | client, ok := s.clients[q.Get("client_id")] |
| 202 | return ok && client.FirstParty && s.cfg.SessionSubject != nil && client.validRedirect(q.Get("redirect_uri")) |
| 203 | } |
| 204 | func (s *Server) Handler() http.Handler { |
| 205 | mux := http.NewServeMux() |
| 206 | mux.HandleFunc("GET /.well-known/oauth-authorization-server", s.metadata) |
| 207 | mux.HandleFunc("GET /.well-known/oauth-protected-resource", s.resourceMetadata) |
| 208 | mux.HandleFunc("GET /oauth/authorize", s.authorize) |
| 209 | mux.HandleFunc("POST /oauth/authorize", s.approve) |
| 210 | mux.HandleFunc("GET /static/{name...}", serveStatic) |
| 211 | mux.HandleFunc("POST /oauth/token", s.token) |
| 212 | mux.HandleFunc("POST /oauth/revoke", s.revoke) |
| 213 | mux.HandleFunc("POST /api/v1/credential", s.credential) |
| 214 | mux.HandleFunc("GET /connections", s.manage) |
| 215 | mux.HandleFunc("POST /connections/revoke", s.disconnect) |
| 216 | mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/connections", 303) }) |
| 217 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 218 | w.Header().Set("Cache-Control", "no-store") |
| 219 | // same-origin, not no-referrer: under no-referrer a browser posts the |
| 220 | // consent form with Origin: null, which approve must refuse. Other sites |
| 221 | // still receive no referrer. |
| 222 | w.Header().Set("Referrer-Policy", "same-origin") |
| 223 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 224 | expected, _ := url.Parse(s.cfg.Origin) |
| 225 | if r.Host != expected.Host { |
| 226 | http.NotFound(w, r) |
| 227 | return |
| 228 | } |
| 229 | if err := s.cfg.Store.Maintain(r.Context()); err != nil { |
| 230 | if r.URL.Path == "/oauth/authorize" { |
| 231 | refusalPage(w, 503) |
| 232 | return |
| 233 | } |
| 234 | fail(w, 503, "temporarily_unavailable") |
| 235 | return |
| 236 | } |
| 237 | mux.ServeHTTP(w, r) |
| 238 | }) |
| 239 | } |
| 240 | func write(w http.ResponseWriter, status int, v any) { |
| 241 | w.Header().Set("Content-Type", "application/json") |
| 242 | w.WriteHeader(status) |
| 243 | _ = json.NewEncoder(w).Encode(v) |
| 244 | } |
| 245 | func fail(w http.ResponseWriter, status int, code string) { |
| 246 | write(w, status, map[string]string{"error": code}) |
| 247 | } |
| 248 | func (s *Server) metadata(w http.ResponseWriter, r *http.Request) { |
| 249 | scopes := []string{} |
| 250 | for scope := range s.cfg.Scopes { |
| 251 | scopes = append(scopes, scope) |
| 252 | } |
| 253 | sort.Strings(scopes) |
| 254 | write(w, 200, map[string]any{"issuer": s.cfg.Origin, "authorization_endpoint": s.cfg.Origin + "/oauth/authorize", "token_endpoint": s.cfg.Origin + "/oauth/token", "revocation_endpoint": s.cfg.Origin + "/oauth/revoke", "response_types_supported": []string{"code"}, "grant_types_supported": []string{"authorization_code", "refresh_token"}, "code_challenge_methods_supported": []string{"S256"}, "token_endpoint_auth_methods_supported": []string{"none"}, "scopes_supported": scopes, "authorization_response_iss_parameter_supported": true}) |
| 255 | } |
| 256 | func (s *Server) resourceMetadata(w http.ResponseWriter, r *http.Request) { |
| 257 | write(w, 200, map[string]any{"resource": s.cfg.Resource, "authorization_servers": []string{s.cfg.Origin}, "scopes_supported": sortedScopes(s.cfg.Scopes), "bearer_methods_supported": []string{"header"}}) |
| 258 | } |
| 259 | func single(values url.Values) bool { |
| 260 | for _, xs := range values { |
| 261 | if len(xs) != 1 { |
| 262 | return false |
| 263 | } |
| 264 | } |
| 265 | return true |
| 266 | } |
| 267 | |
| 268 | // pageCSP lets the grant pages load their own stylesheet and nothing else. |
| 269 | const pageCSP = "default-src 'none'; style-src 'self'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'" |
| 270 | |
| 271 | // consentCSP is pageCSP for one consent page. It also names the origin of this |
| 272 | // request's validated redirect, and no other. The form's answer is a hand-off |
| 273 | // page rather than a redirect (see handOff), so this is not what lets the |
| 274 | // browser reach the client. |
| 275 | func consentCSP(redirect string) string { |
| 276 | u, err := url.Parse(redirect) |
| 277 | if err != nil { |
| 278 | return pageCSP |
| 279 | } |
| 280 | return strings.Replace(pageCSP, "form-action 'self'", "form-action 'self' "+u.Scheme+"://"+u.Host, 1) |
| 281 | } |
| 282 | |
| 283 | // refusalURL is a trusted client's registered redirect carrying an OAuth error. |
| 284 | // Callers must have validated the client and redirect already. |
| 285 | func (s *Server) refusalURL(redirect, state, code string) (string, bool) { |
| 286 | dest, err := url.Parse(redirect) |
| 287 | if err != nil { |
| 288 | return "", false |
| 289 | } |
| 290 | q := dest.Query() |
| 291 | q.Set("error", code) |
| 292 | if state != "" { |
| 293 | q.Set("state", state) |
| 294 | } |
| 295 | q.Set("iss", s.cfg.Origin) |
| 296 | dest.RawQuery = q.Encode() |
| 297 | return dest.String(), true |
| 298 | } |
| 299 | |
| 300 | // refuse redirects a trusted client's authorize request back to it with an |
| 301 | // OAuth error. Answers to the consent form use refuseForm instead. |
| 302 | func (s *Server) refuse(w http.ResponseWriter, r *http.Request, redirect, state, code string) { |
| 303 | dest, ok := s.refusalURL(redirect, state, code) |
| 304 | if !ok { |
| 305 | refusalPage(w, 400) |
| 306 | return |
| 307 | } |
| 308 | http.Redirect(w, r, dest, 303) |
| 309 | } |
| 310 | |
| 311 | // refuseForm is refuse for an answer to the consent form: it hands the browser |
| 312 | // back to the client with a page instead of a redirect. |
| 313 | func (s *Server) refuseForm(w http.ResponseWriter, redirect, state, code string) { |
| 314 | dest, ok := s.refusalURL(redirect, state, code) |
| 315 | if !ok { |
| 316 | refusalPage(w, 400) |
| 317 | return |
| 318 | } |
| 319 | handOff(w, dest) |
| 320 | } |
| 321 | func (s *Server) authorize(w http.ResponseWriter, r *http.Request) { |
| 322 | if len(r.URL.RawQuery) > 8192 { |
| 323 | refusalPage(w, 400) |
| 324 | return |
| 325 | } |
| 326 | q, err := url.ParseQuery(r.URL.RawQuery) |
| 327 | if err != nil || !single(q) { |
| 328 | refusalPage(w, 400) |
| 329 | return |
| 330 | } |
| 331 | client, ok := s.clients[q.Get("client_id")] |
| 332 | if !ok || !client.validRedirect(q.Get("redirect_uri")) { |
| 333 | refusalPage(w, 400) |
| 334 | return |
| 335 | } |
| 336 | |
| 337 | // The client and redirect are now trusted: later refusals go back to the |
| 338 | // client (RFC 6749 section 4.1.2.1) instead of a bare JSON page. |
| 339 | redirect, state := q.Get("redirect_uri"), q.Get("state") |
| 340 | challenge, err := base64.RawURLEncoding.DecodeString(q.Get("code_challenge")) |
| 341 | if err != nil || len(challenge) != 32 || q.Get("code_challenge_method") != "S256" || q.Get("response_type") != "code" || q.Get("resource") != s.cfg.Resource || len(q.Get("state")) < 16 { |
| 342 | s.refuse(w, r, redirect, state, "invalid_request") |
| 343 | return |
| 344 | } |
| 345 | scopes := strings.Fields(q.Get("scope")) |
| 346 | if len(scopes) == 0 { |
| 347 | s.refuse(w, r, redirect, state, "invalid_scope") |
| 348 | return |
| 349 | } |
| 350 | seen := map[string]bool{} |
| 351 | for _, scope := range scopes { |
| 352 | if _, ok := s.cfg.Scopes[scope]; !ok || seen[scope] { |
| 353 | s.refuse(w, r, redirect, state, "invalid_scope") |
| 354 | return |
| 355 | } |
| 356 | seen[scope] = true |
| 357 | } |
| 358 | subject := s.subjectFor(client, r) |
| 359 | if subject == "" { |
| 360 | dest, _ := url.Parse(s.cfg.SignInPath) |
| 361 | v := dest.Query() |
| 362 | v.Set("return_to", r.URL.RequestURI()) |
| 363 | dest.RawQuery = v.Encode() |
| 364 | http.Redirect(w, r, dest.String(), 303) |
| 365 | return |
| 366 | } |
| 367 | teams, err := s.cfg.Teams(r.Context(), subject) |
| 368 | if err != nil { |
| 369 | s.refuse(w, r, redirect, state, "temporarily_unavailable") |
| 370 | return |
| 371 | } |
| 372 | if len(teams) == 0 { |
| 373 | s.refuse(w, r, redirect, state, "access_denied") |
| 374 | return |
| 375 | } |
| 376 | t := ticket{Purpose: "authorize", Client: client.ID, Redirect: q.Get("redirect_uri"), Resource: s.cfg.Resource, Challenge: q.Get("code_challenge"), State: q.Get("state"), Subject: subject, Nonce: random(), Scopes: scopes, Expires: s.cfg.Store.Now().Add(5 * time.Minute).Unix()} |
| 377 | encoded, err := s.seal(t) |
| 378 | if err != nil { |
| 379 | s.refuse(w, r, redirect, state, "server_error") |
| 380 | return |
| 381 | } |
| 382 | if _, err = s.cfg.Store.DB.ExecContext(r.Context(), `INSERT INTO agent_pending(hash,expires) VALUES(?,?)`, hash(t.Nonce), t.Expires); err != nil { |
| 383 | s.refuse(w, r, redirect, state, "temporarily_unavailable") |
| 384 | return |
| 385 | } |
| 386 | http.SetCookie(w, &http.Cookie{Name: "__Host-oficina-consent", Value: t.Nonce, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: 300}) |
| 387 | labels := []string{} |
| 388 | for _, scope := range scopes { |
| 389 | labels = append(labels, s.cfg.Scopes[scope]) |
| 390 | } |
| 391 | w.Header().Set("Content-Security-Policy", consentCSP(redirect)) |
| 392 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 393 | _ = consent.Execute(w, map[string]any{"Client": client.Name, "Ticket": encoded, "Teams": teams, "Only": len(teams) == 1, "Scopes": labels}) |
| 394 | } |
| 395 | |
| 396 | //go:embed static |
| 397 | var staticFS embed.FS |
| 398 | |
| 399 | // staticTypes is the closed list of files served under /static/. |
| 400 | var staticTypes = map[string]string{ |
| 401 | "grant.css": "text/css; charset=utf-8", |
| 402 | "brand/icon.svg": "image/svg+xml", |
| 403 | "sky/grain.svg": "image/svg+xml", |
| 404 | "sky/filaments.svg": "image/svg+xml", |
| 405 | "sky/placeholder-light.png": "image/png", |
| 406 | "sky/placeholder-dark.png": "image/png", |
| 407 | } |
| 408 | |
| 409 | func serveStatic(w http.ResponseWriter, r *http.Request) { |
| 410 | name := r.PathValue("name") |
| 411 | kind, ok := staticTypes[name] |
| 412 | if !ok { |
| 413 | http.NotFound(w, r) |
| 414 | return |
| 415 | } |
| 416 | body, err := staticFS.ReadFile("static/" + name) |
| 417 | if err != nil { |
| 418 | http.NotFound(w, r) |
| 419 | return |
| 420 | } |
| 421 | w.Header().Set("Content-Type", kind) |
| 422 | _, _ = w.Write(body) |
| 423 | } |
| 424 | |
| 425 | // pageHead and doorOpen give every grant page Oficina's sign-in door: the |
| 426 | // suite sky, one white card, the app mark and the wordmark. They are the |
| 427 | // same rules and artwork id.oficina.works serves. |
| 428 | const pageHead = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" type="image/svg+xml" href="/static/brand/icon.svg"><link rel="stylesheet" href="/static/grant.css">` |
| 429 | const doorOpen = `<main><div estilo-door estilo-sky-host><div estilo-sky aria-hidden="true"><img estilo-sky-layer="placeholder" estilo-sky-tone="light" src="/static/sky/placeholder-light.png" alt=""><img estilo-sky-layer="placeholder" estilo-sky-tone="dark" src="/static/sky/placeholder-dark.png" alt=""><img estilo-sky-layer="grain" src="/static/sky/grain.svg" alt=""><img estilo-sky-layer="filaments" src="/static/sky/filaments.svg" alt=""></div><section estilo-signin><p estilo-brand><img estilo-brand-icon="listing" src="/static/brand/icon.svg" alt="" width="36" height="36"><span>Oficina</span></p>` |
| 430 | const doorClose = `</section></div></main></html>` |
| 431 | |
| 432 | 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)) |
| 433 | |
| 434 | // refusal uses the sign-in door's existing wording for a request that cannot be |
| 435 | // traced to a client it would be safe to send the person back to. |
| 436 | var refusal = template.Must(template.New("refusal").Parse(pageHead + `<title>Connect to Oficina</title>` + doorOpen + `<h1>Unable to sign in. Start again.</h1>` + doorClose)) |
| 437 | |
| 438 | func refusalPage(w http.ResponseWriter, status int) { |
| 439 | w.Header().Set("Content-Security-Policy", pageCSP) |
| 440 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 441 | w.WriteHeader(status) |
| 442 | _ = refusal.Execute(w, nil) |
| 443 | } |
| 444 | |
| 445 | // handoffText is the hand-off page's one visible link, for a browser that does |
| 446 | // not follow the refresh. Its wording passed copy review on 2026-11-24. |
| 447 | const handoffText = "Continue" |
| 448 | |
| 449 | // handoffPage moves the browser on with a meta refresh. html/template escapes |
| 450 | // the URL in both attributes; a refresh URL that does not start with a quote |
| 451 | // runs to the end of the attribute, so its & and ; need no further care. |
| 452 | 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)) |
| 453 | |
| 454 | // handOff answers the consent form by sending the browser to dest, a trusted |
| 455 | // client's redirect, with a page rather than a 303. Browsers check form-action |
| 456 | // along a form's whole redirect chain, and a client may redirect on to origins |
| 457 | // connect cannot name (Equipo hands a person on to Base), so a 303 would leave |
| 458 | // the person on the consent page. A meta refresh is a fresh navigation that |
| 459 | // form-action does not govern, and the policy stays as strict as before. |
| 460 | func handOff(w http.ResponseWriter, dest string) { |
| 461 | w.Header().Set("Content-Security-Policy", pageCSP) |
| 462 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 463 | // dest carries the authorization code: keep it out of caches and out of |
| 464 | // the Referer the client and anything after it would receive. |
| 465 | w.Header().Set("Cache-Control", "no-store") |
| 466 | w.Header().Set("Referrer-Policy", "no-referrer") |
| 467 | w.WriteHeader(200) |
| 468 | _ = handoffPage.Execute(w, map[string]string{"URL": dest, "Text": handoffText}) |
| 469 | } |
| 470 | |
| 471 | func (s *Server) approve(w http.ResponseWriter, r *http.Request) { |
| 472 | if len(r.Header.Values("Origin")) != 1 || r.Header.Get("Origin") != s.cfg.Origin { |
| 473 | refusalPage(w, 403) |
| 474 | return |
| 475 | } |
| 476 | r.Body = http.MaxBytesReader(w, r.Body, 16384) |
| 477 | if r.ParseForm() != nil || len(r.PostForm["ticket"]) != 1 || len(r.PostForm["decision"]) != 1 { |
| 478 | refusalPage(w, 400) |
| 479 | return |
| 480 | } |
| 481 | t, err := s.unseal(r.PostForm.Get("ticket")) |
| 482 | if err != nil || t.Purpose != "authorize" { |
| 483 | refusalPage(w, 403) |
| 484 | return |
| 485 | } |
| 486 | client, ok := s.clients[t.Client] |
| 487 | if !ok || !client.validRedirect(t.Redirect) { |
| 488 | refusalPage(w, 403) |
| 489 | return |
| 490 | } |
| 491 | // The ticket is this server's own and names a client and redirect that are |
| 492 | // still registered, so from here a refusal goes back to that client. |
| 493 | cookies := r.CookiesNamed("__Host-oficina-consent") |
| 494 | 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 { |
| 495 | s.refuseForm(w, t.Redirect, t.State, "access_denied") |
| 496 | return |
| 497 | } |
| 498 | decision := r.PostForm.Get("decision") |
| 499 | if decision != "approve" && decision != "deny" { |
| 500 | s.refuseForm(w, t.Redirect, t.State, "invalid_request") |
| 501 | return |
| 502 | } |
| 503 | teams, err := s.cfg.Teams(r.Context(), t.Subject) |
| 504 | if err != nil { |
| 505 | s.refuseForm(w, t.Redirect, t.State, "temporarily_unavailable") |
| 506 | return |
| 507 | } |
| 508 | allowed := map[string]bool{} |
| 509 | for _, team := range teams { |
| 510 | allowed[team.ID] = true |
| 511 | } |
| 512 | selected := r.PostForm["team"] |
| 513 | seen := map[string]bool{} |
| 514 | for _, team := range selected { |
| 515 | if !allowed[team] || seen[team] { |
| 516 | s.refuseForm(w, t.Redirect, t.State, "access_denied") |
| 517 | return |
| 518 | } |
| 519 | seen[team] = true |
| 520 | } |
| 521 | if decision == "approve" && len(selected) == 0 { |
| 522 | s.refuseForm(w, t.Redirect, t.State, "access_denied") |
| 523 | return |
| 524 | } |
| 525 | 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()) |
| 526 | if err != nil { |
| 527 | s.refuseForm(w, t.Redirect, t.State, "temporarily_unavailable") |
| 528 | return |
| 529 | } |
| 530 | n, _ := result.RowsAffected() |
| 531 | if n != 1 { |
| 532 | // A spent ticket has already answered the client once; it gets no second answer. |
| 533 | refusalPage(w, 400) |
| 534 | return |
| 535 | } |
| 536 | http.SetCookie(w, &http.Cookie{Name: "__Host-oficina-consent", Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1}) |
| 537 | if decision == "deny" { |
| 538 | s.refuseForm(w, t.Redirect, t.State, "access_denied") |
| 539 | return |
| 540 | } |
| 541 | { |
| 542 | dest, _ := url.Parse(t.Redirect) |
| 543 | q := dest.Query() |
| 544 | q.Set("state", t.State) |
| 545 | q.Set("iss", s.cfg.Origin) |
| 546 | 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}) |
| 547 | if err != nil { |
| 548 | s.refuseForm(w, t.Redirect, t.State, "temporarily_unavailable") |
| 549 | return |
| 550 | } |
| 551 | q.Set("code", code) |
| 552 | dest.RawQuery = q.Encode() |
| 553 | handOff(w, dest.String()) |
| 554 | } |
| 555 | } |
| 556 | func form(w http.ResponseWriter, r *http.Request) bool { |
| 557 | r.Body = http.MaxBytesReader(w, r.Body, 16384) |
| 558 | if r.ParseForm() != nil || !single(r.PostForm) || len(r.URL.RawQuery) > 0 { |
| 559 | fail(w, 400, "invalid_request") |
| 560 | return false |
| 561 | } |
| 562 | return true |
| 563 | } |
| 564 | func (s *Server) token(w http.ResponseWriter, r *http.Request) { |
| 565 | if !form(w, r) { |
| 566 | return |
| 567 | } |
| 568 | if _, ok := s.clients[r.PostForm.Get("client_id")]; !ok { |
| 569 | fail(w, 400, "invalid_client") |
| 570 | return |
| 571 | } |
| 572 | var token TokenResponse |
| 573 | var err error |
| 574 | switch r.PostForm.Get("grant_type") { |
| 575 | case "authorization_code": |
| 576 | token, err = s.cfg.Store.Exchange(r.Context(), r.PostForm.Get("code"), r.PostForm.Get("client_id"), r.PostForm.Get("redirect_uri"), r.PostForm.Get("resource"), r.PostForm.Get("code_verifier")) |
| 577 | case "refresh_token": |
| 578 | token, err = s.cfg.Store.Refresh(r.Context(), r.PostForm.Get("refresh_token"), r.PostForm.Get("client_id"), r.PostForm.Get("resource")) |
| 579 | default: |
| 580 | fail(w, 400, "unsupported_grant_type") |
| 581 | return |
| 582 | } |
| 583 | if errors.Is(err, ErrCredential) { |
| 584 | fail(w, 400, "invalid_grant") |
| 585 | return |
| 586 | } |
| 587 | if err != nil { |
| 588 | fail(w, 503, "temporarily_unavailable") |
| 589 | return |
| 590 | } |
| 591 | write(w, 200, token) |
| 592 | } |
| 593 | func (s *Server) revoke(w http.ResponseWriter, r *http.Request) { |
| 594 | if !form(w, r) { |
| 595 | return |
| 596 | } |
| 597 | if _, ok := s.clients[r.PostForm.Get("client_id")]; !ok { |
| 598 | fail(w, 400, "invalid_client") |
| 599 | return |
| 600 | } |
| 601 | if err := s.cfg.Store.Revoke(r.Context(), r.PostForm.Get("token"), r.PostForm.Get("client_id")); err != nil { |
| 602 | fail(w, 503, "temporarily_unavailable") |
| 603 | return |
| 604 | } |
| 605 | w.WriteHeader(200) |
| 606 | } |
| 607 | func (s *Server) Verify(ctx context.Context, token string) (access.Principal, error) { |
| 608 | p, err := s.cfg.Store.Verify(ctx, token, s.cfg.Resource) |
| 609 | if err != nil { |
| 610 | return access.Principal{}, err |
| 611 | } |
| 612 | teams, err := s.cfg.Teams(ctx, p.Subject) |
| 613 | if err != nil { |
| 614 | return access.Principal{}, access.Fail("unavailable", "Authorization is temporarily unavailable.") |
| 615 | } |
| 616 | allowed := map[string]bool{} |
| 617 | for _, team := range teams { |
| 618 | allowed[team.ID] = true |
| 619 | } |
| 620 | filtered := []string{} |
| 621 | for _, team := range p.Teams { |
| 622 | if allowed[team] { |
| 623 | filtered = append(filtered, team) |
| 624 | } |
| 625 | } |
| 626 | p.Teams = filtered |
| 627 | if len(filtered) == 0 { |
| 628 | return access.Principal{}, access.Fail("unauthenticated", "This connection no longer has access.") |
| 629 | } |
| 630 | return p, nil |
| 631 | } |
| 632 | |
| 633 | // ResourceHandler advertises discovery on failed MCP authentication, while the |
| 634 | // registry still verifies the bearer on each request. |
| 635 | func (s *Server) ResourceHandler(next http.Handler) http.Handler { |
| 636 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 637 | w.Header().Set("WWW-Authenticate", `Bearer resource_metadata="`+s.cfg.Origin+`/.well-known/oauth-protected-resource"`) |
| 638 | next.ServeHTTP(w, r) |
| 639 | }) |
| 640 | } |
| 641 | |
| 642 | func sortedScopes(scopes map[string]string) []string { |
| 643 | out := []string{} |
| 644 | for scope := range scopes { |
| 645 | if scope != "offline_access" { |
| 646 | out = append(out, scope) |
| 647 | } |
| 648 | } |
| 649 | sort.Strings(out) |
| 650 | return out |
| 651 | } |
| 652 | |
| 653 | // The bearer proves possession; the supplied resource is checked against the |
| 654 | // token's stored audience. Apps use their configured audience, never user input. |
| 655 | func (s *Server) credential(w http.ResponseWriter, r *http.Request) { |
| 656 | parts := strings.Fields(r.Header.Get("Authorization")) |
| 657 | if len(r.Header.Values("Authorization")) != 1 || len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { |
| 658 | fail(w, 401, "invalid_token") |
| 659 | return |
| 660 | } |
| 661 | body, err := io.ReadAll(io.LimitReader(r.Body, 8193)) |
| 662 | if err != nil || len(body) > 8192 || access.UniqueJSON(body) != nil { |
| 663 | fail(w, 400, "invalid_request") |
| 664 | return |
| 665 | } |
| 666 | var in struct { |
| 667 | Resource string `json:"resource"` |
| 668 | } |
| 669 | if json.Unmarshal(body, &in) != nil || in.Resource == "" { |
| 670 | fail(w, 400, "invalid_request") |
| 671 | return |
| 672 | } |
| 673 | p, err := s.cfg.Store.Verify(r.Context(), parts[1], in.Resource) |
| 674 | if err != nil { |
| 675 | if access.SafeFailure(err).Code == "unavailable" { |
| 676 | fail(w, 503, "temporarily_unavailable") |
| 677 | } else { |
| 678 | fail(w, 401, "invalid_token") |
| 679 | } |
| 680 | return |
| 681 | } |
| 682 | lookup := s.cfg.Teams |
| 683 | if in.Resource != s.cfg.Resource { |
| 684 | if s.cfg.ResourceTeams == nil { |
| 685 | fail(w, 401, "invalid_token") |
| 686 | return |
| 687 | } |
| 688 | lookup = func(ctx context.Context, subject string) ([]Team, error) { |
| 689 | return s.cfg.ResourceTeams(ctx, subject, in.Resource) |
| 690 | } |
| 691 | } |
| 692 | teams, err := lookup(r.Context(), p.Subject) |
| 693 | if err != nil { |
| 694 | fail(w, 503, "temporarily_unavailable") |
| 695 | return |
| 696 | } |
| 697 | allowed := map[string]bool{} |
| 698 | for _, team := range teams { |
| 699 | allowed[team.ID] = true |
| 700 | } |
| 701 | filtered := []string{} |
| 702 | for _, team := range p.Teams { |
| 703 | if allowed[team] { |
| 704 | filtered = append(filtered, team) |
| 705 | } |
| 706 | } |
| 707 | p.Teams = filtered |
| 708 | if len(filtered) == 0 { |
| 709 | fail(w, 401, "invalid_token") |
| 710 | return |
| 711 | } |
| 712 | write(w, 200, map[string]any{"resource": in.Resource, "identity_issuer": s.cfg.IdentityIssuer, "principal": p}) |
| 713 | } |
| 714 | |