| 1 | // Package oficinatest is a fake oficina-connect for tests: the OAuth 2 |
| 2 | // authorization code flow with S256 PKCE for public clients, rotating |
| 3 | // refresh tokens (reusing a consumed one revokes the connection, as |
| 4 | // connect does), revocation, and the operations API behind a bearer. |
| 5 | // It approves every consent itself, for the teams it was given. |
| 6 | package oficinatest |
| 7 | |
| 8 | import ( |
| 9 | "crypto/rand" |
| 10 | "crypto/sha256" |
| 11 | "encoding/base64" |
| 12 | "encoding/json" |
| 13 | "io" |
| 14 | "net/http" |
| 15 | "net/http/httptest" |
| 16 | "net/url" |
| 17 | "slices" |
| 18 | "strings" |
| 19 | "sync" |
| 20 | "testing" |
| 21 | "time" |
| 22 | ) |
| 23 | |
| 24 | // Operation is a descriptor the fake lists, in agent-access's shape. |
| 25 | type Operation struct { |
| 26 | Name string `json:"name"` |
| 27 | Description string `json:"description"` |
| 28 | Scope string `json:"scope"` |
| 29 | ReadOnly bool `json:"read_only"` |
| 30 | Destructive bool `json:"destructive"` |
| 31 | Idempotent bool `json:"idempotent"` |
| 32 | External bool `json:"external,omitempty"` |
| 33 | Input json.RawMessage `json:"input_schema"` |
| 34 | Output json.RawMessage `json:"output_schema"` |
| 35 | } |
| 36 | |
| 37 | // Call is one operation call the fake answered. |
| 38 | type Call struct { |
| 39 | Name string |
| 40 | Bearer string |
| 41 | Input map[string]any |
| 42 | } |
| 43 | |
| 44 | // UUIDSchema is a required client_id as the apps declare it: a string |
| 45 | // of exactly 36 characters. |
| 46 | const UUIDSchema = `{"type":"string","minLength":36,"maxLength":36}` |
| 47 | |
| 48 | // Operations is the fake's default list: a read, a client_id-keyed |
| 49 | // write, a write without a key, one destructive and one external write. |
| 50 | func Operations() []Operation { |
| 51 | in := func(props string, required ...string) json.RawMessage { |
| 52 | req, _ := json.Marshal(append([]string{"team"}, required...)) |
| 53 | return json.RawMessage(`{"type":"object","additionalProperties":false,"required":` + string(req) + `,"properties":{"team":{"type":"string","maxLength":64}` + props + `}}`) |
| 54 | } |
| 55 | out := json.RawMessage(`{"type":"object"}`) |
| 56 | return []Operation{ |
| 57 | {Name: "calendar_free_busy", Description: "Busy spans in a range.", Scope: "calendar:read", ReadOnly: true, Idempotent: true, Input: in(`,"start":{"type":"string"},"end":{"type":"string"}`, "start", "end"), Output: out}, |
| 58 | {Name: "calendar_create_event", Description: "Create an event. Sends no invitations.", Scope: "calendar:write", Idempotent: true, Input: in(`,"client_id":`+UUIDSchema+`,"title":{"type":"string"},"start_local":{"type":"string"}`, "client_id", "title", "start_local"), Output: out}, |
| 59 | {Name: "docs_append", Description: "Append to a document without a client_id.", Scope: "docs:write", Idempotent: false, Input: in(`,"id":{"type":"string"},"text":{"type":"string"}`, "id", "text"), Output: out}, |
| 60 | {Name: "docs_delete", Description: "Delete a document.", Scope: "docs:write", Destructive: true, Idempotent: true, Input: in(`,"client_id":`+UUIDSchema+`,"id":{"type":"string"}`, "client_id", "id"), Output: out}, |
| 61 | {Name: "calls_invite", Description: "Invite a guest.", Scope: "calls:write", External: true, Idempotent: true, Input: in(`,"client_id":`+UUIDSchema+`,"email":{"type":"string"}`, "client_id", "email"), Output: out}, |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | type grant struct { |
| 66 | teams []string |
| 67 | revoked bool |
| 68 | } |
| 69 | |
| 70 | type code struct { |
| 71 | grant *grant |
| 72 | redirect, resource string |
| 73 | challenge string |
| 74 | expires time.Time |
| 75 | } |
| 76 | |
| 77 | type token struct { |
| 78 | grant *grant |
| 79 | refresh bool |
| 80 | used bool |
| 81 | expires time.Time |
| 82 | } |
| 83 | |
| 84 | // Connect is a running fake oficina-connect. |
| 85 | type Connect struct { |
| 86 | URL string |
| 87 | ClientID string |
| 88 | // Redirect is the client's one registered redirect; empty takes any. |
| 89 | Redirect string |
| 90 | // Teams are what consent selects; Ops what the operations API lists. |
| 91 | Teams []string |
| 92 | Ops []Operation |
| 93 | // AccessTTL is an access token's lifetime (5 minutes by default). |
| 94 | AccessTTL time.Duration |
| 95 | // Deny makes the next consent a refusal. |
| 96 | Deny bool |
| 97 | // Down makes the token endpoint answer 503. |
| 98 | Down bool |
| 99 | // FailNext makes the next operation call answer 503 once it is |
| 100 | // recorded. |
| 101 | FailNext bool |
| 102 | |
| 103 | mu sync.Mutex |
| 104 | codes map[string]*code |
| 105 | tokens map[string]*token |
| 106 | calls []Call |
| 107 | exchanges int |
| 108 | refreshes int |
| 109 | revokes []string |
| 110 | srv *httptest.Server |
| 111 | } |
| 112 | |
| 113 | // Start serves a fake connect on 127.0.0.1 until the test ends. |
| 114 | func Start(t testing.TB) *Connect { |
| 115 | t.Helper() |
| 116 | c := &Connect{ClientID: "8d3f6c1e-7a52-4c1b-9f60-2b7e4d1a9c33", Teams: []string{"acme"}, Ops: Operations(), AccessTTL: 5 * time.Minute, codes: map[string]*code{}, tokens: map[string]*token{}} |
| 117 | mux := http.NewServeMux() |
| 118 | mux.HandleFunc("GET /.well-known/oauth-authorization-server", c.metadata) |
| 119 | mux.HandleFunc("GET /oauth/authorize", c.authorize) |
| 120 | mux.HandleFunc("POST /oauth/token", c.token) |
| 121 | mux.HandleFunc("POST /oauth/revoke", c.revoke) |
| 122 | mux.HandleFunc("GET /api/v1/connection", c.bearer(c.connection)) |
| 123 | mux.HandleFunc("GET /api/v1/operations", c.bearer(c.operations)) |
| 124 | mux.HandleFunc("POST /api/v1/operations/{name}", c.bearer(c.invoke)) |
| 125 | c.srv = httptest.NewServer(mux) |
| 126 | c.URL = c.srv.URL |
| 127 | t.Cleanup(c.srv.Close) |
| 128 | return c |
| 129 | } |
| 130 | |
| 131 | // Resource is the audience every token is for, as connect's /mcp. |
| 132 | func (c *Connect) Resource() string { return c.URL + "/mcp" } |
| 133 | |
| 134 | // Grant mints an access token for teams directly, with no consent. |
| 135 | func (c *Connect) Grant(teams ...string) string { |
| 136 | c.mu.Lock() |
| 137 | defer c.mu.Unlock() |
| 138 | g := &grant{teams: teams} |
| 139 | access := random() |
| 140 | c.tokens[access] = &token{grant: g, expires: time.Now().Add(c.AccessTTL)} |
| 141 | return access |
| 142 | } |
| 143 | |
| 144 | // Calls are the operation calls the fake answered, oldest first. |
| 145 | func (c *Connect) Calls() []Call { |
| 146 | c.mu.Lock() |
| 147 | defer c.mu.Unlock() |
| 148 | return slices.Clone(c.calls) |
| 149 | } |
| 150 | |
| 151 | // Counts are the code exchanges and refreshes the fake answered. |
| 152 | func (c *Connect) Counts() (exchanges, refreshes int) { |
| 153 | c.mu.Lock() |
| 154 | defer c.mu.Unlock() |
| 155 | return c.exchanges, c.refreshes |
| 156 | } |
| 157 | |
| 158 | // Revoked are the tokens revoked through /oauth/revoke. |
| 159 | func (c *Connect) Revoked() []string { |
| 160 | c.mu.Lock() |
| 161 | defer c.mu.Unlock() |
| 162 | return slices.Clone(c.revokes) |
| 163 | } |
| 164 | |
| 165 | // Live says a token is current: known, unexpired, unused and its |
| 166 | // connection not revoked. |
| 167 | func (c *Connect) Live(tok string) bool { |
| 168 | c.mu.Lock() |
| 169 | defer c.mu.Unlock() |
| 170 | k, ok := c.tokens[tok] |
| 171 | return ok && !k.used && !k.grant.revoked && time.Now().Before(k.expires) |
| 172 | } |
| 173 | |
| 174 | // RevokeAll revokes every connection, as /connections would. |
| 175 | func (c *Connect) RevokeAll() { |
| 176 | c.mu.Lock() |
| 177 | defer c.mu.Unlock() |
| 178 | for _, k := range c.tokens { |
| 179 | k.grant.revoked = true |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | // Expire makes every access token expire now. |
| 184 | func (c *Connect) Expire() { |
| 185 | c.mu.Lock() |
| 186 | defer c.mu.Unlock() |
| 187 | for _, k := range c.tokens { |
| 188 | if !k.refresh { |
| 189 | k.expires = time.Now().Add(-time.Second) |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | func (c *Connect) metadata(w http.ResponseWriter, _ *http.Request) { |
| 195 | scopes := []string{"offline_access"} |
| 196 | c.mu.Lock() |
| 197 | for _, op := range c.Ops { |
| 198 | if !slices.Contains(scopes, op.Scope) { |
| 199 | scopes = append(scopes, op.Scope) |
| 200 | } |
| 201 | } |
| 202 | c.mu.Unlock() |
| 203 | scopes = append(scopes, "calls:share") |
| 204 | write(w, 200, map[string]any{"issuer": c.URL, "authorization_endpoint": c.URL + "/oauth/authorize", "token_endpoint": c.URL + "/oauth/token", "revocation_endpoint": c.URL + "/oauth/revoke", "code_challenge_methods_supported": []string{"S256"}, "scopes_supported": scopes}) |
| 205 | } |
| 206 | |
| 207 | func (c *Connect) authorize(w http.ResponseWriter, r *http.Request) { |
| 208 | q := r.URL.Query() |
| 209 | challenge, err := base64.RawURLEncoding.DecodeString(q.Get("code_challenge")) |
| 210 | if q.Get("client_id") != c.ClientID || c.Redirect != "" && q.Get("redirect_uri") != c.Redirect || err != nil || len(challenge) != 32 || |
| 211 | q.Get("code_challenge_method") != "S256" || q.Get("response_type") != "code" || q.Get("resource") != c.Resource() || len(q.Get("state")) < 16 { |
| 212 | fail(w, 400, "invalid_request") |
| 213 | return |
| 214 | } |
| 215 | scopes := strings.Fields(q.Get("scope")) |
| 216 | if len(scopes) == 0 || !slices.Contains(scopes, "offline_access") || slices.Contains(scopes, "calls:share") { |
| 217 | fail(w, 400, "invalid_scope") |
| 218 | return |
| 219 | } |
| 220 | dest, _ := url.Parse(q.Get("redirect_uri")) |
| 221 | v := dest.Query() |
| 222 | v.Set("state", q.Get("state")) |
| 223 | v.Set("iss", c.URL) |
| 224 | c.mu.Lock() |
| 225 | if c.Deny { |
| 226 | c.Deny = false |
| 227 | v.Set("error", "access_denied") |
| 228 | } else { |
| 229 | k := random() |
| 230 | c.codes[k] = &code{grant: &grant{teams: slices.Clone(c.Teams)}, redirect: q.Get("redirect_uri"), resource: q.Get("resource"), challenge: q.Get("code_challenge"), expires: time.Now().Add(2 * time.Minute)} |
| 231 | v.Set("code", k) |
| 232 | } |
| 233 | c.mu.Unlock() |
| 234 | dest.RawQuery = v.Encode() |
| 235 | http.Redirect(w, r, dest.String(), http.StatusSeeOther) |
| 236 | } |
| 237 | |
| 238 | func (c *Connect) token(w http.ResponseWriter, r *http.Request) { |
| 239 | if r.ParseForm() != nil || r.URL.RawQuery != "" { |
| 240 | fail(w, 400, "invalid_request") |
| 241 | return |
| 242 | } |
| 243 | f := r.PostForm |
| 244 | c.mu.Lock() |
| 245 | defer c.mu.Unlock() |
| 246 | if c.Down { |
| 247 | fail(w, 503, "temporarily_unavailable") |
| 248 | return |
| 249 | } |
| 250 | if f.Get("client_id") != c.ClientID { |
| 251 | fail(w, 400, "invalid_client") |
| 252 | return |
| 253 | } |
| 254 | switch f.Get("grant_type") { |
| 255 | case "authorization_code": |
| 256 | c.exchanges++ |
| 257 | k, ok := c.codes[f.Get("code")] |
| 258 | delete(c.codes, f.Get("code")) |
| 259 | sum := sha256.Sum256([]byte(f.Get("code_verifier"))) |
| 260 | if !ok || time.Now().After(k.expires) || k.redirect != f.Get("redirect_uri") || k.resource != f.Get("resource") || len(f.Get("code_verifier")) < 43 || |
| 261 | base64.RawURLEncoding.EncodeToString(sum[:]) != k.challenge { |
| 262 | fail(w, 400, "invalid_grant") |
| 263 | return |
| 264 | } |
| 265 | write(w, 200, c.mint(k.grant)) |
| 266 | case "refresh_token": |
| 267 | c.refreshes++ |
| 268 | k, ok := c.tokens[f.Get("refresh_token")] |
| 269 | if !ok || !k.refresh || k.grant.revoked || f.Get("resource") != c.Resource() { |
| 270 | fail(w, 400, "invalid_grant") |
| 271 | return |
| 272 | } |
| 273 | if k.used { |
| 274 | // Reuse of a consumed refresh token revokes the connection. |
| 275 | k.grant.revoked = true |
| 276 | fail(w, 400, "invalid_grant") |
| 277 | return |
| 278 | } |
| 279 | k.used = true |
| 280 | write(w, 200, c.mint(k.grant)) |
| 281 | default: |
| 282 | fail(w, 400, "unsupported_grant_type") |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | func (c *Connect) mint(g *grant) map[string]any { |
| 287 | access, refresh := random(), random() |
| 288 | c.tokens[access] = &token{grant: g, expires: time.Now().Add(c.AccessTTL)} |
| 289 | c.tokens[refresh] = &token{grant: g, refresh: true, expires: time.Now().Add(30 * 24 * time.Hour)} |
| 290 | return map[string]any{"access_token": access, "token_type": "Bearer", "expires_in": int(c.AccessTTL / time.Second), "refresh_token": refresh, "scope": "offline_access"} |
| 291 | } |
| 292 | |
| 293 | func (c *Connect) revoke(w http.ResponseWriter, r *http.Request) { |
| 294 | if r.ParseForm() != nil || r.PostForm.Get("client_id") != c.ClientID { |
| 295 | fail(w, 400, "invalid_client") |
| 296 | return |
| 297 | } |
| 298 | c.mu.Lock() |
| 299 | defer c.mu.Unlock() |
| 300 | c.revokes = append(c.revokes, r.PostForm.Get("token")) |
| 301 | if k, ok := c.tokens[r.PostForm.Get("token")]; ok { |
| 302 | k.grant.revoked = true |
| 303 | } |
| 304 | w.WriteHeader(200) |
| 305 | } |
| 306 | |
| 307 | func (c *Connect) bearer(next func(http.ResponseWriter, *http.Request, string, *grant)) http.HandlerFunc { |
| 308 | return func(w http.ResponseWriter, r *http.Request) { |
| 309 | tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") |
| 310 | c.mu.Lock() |
| 311 | k, known := c.tokens[tok] |
| 312 | live := ok && known && !k.refresh && !k.grant.revoked && time.Now().Before(k.expires) |
| 313 | c.mu.Unlock() |
| 314 | if !live { |
| 315 | write(w, 401, map[string]any{"error": map[string]string{"code": "unauthenticated", "message": "Connect to Oficina first."}}) |
| 316 | return |
| 317 | } |
| 318 | next(w, r, tok, k.grant) |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | func (c *Connect) connection(w http.ResponseWriter, _ *http.Request, _ string, g *grant) { |
| 323 | write(w, 200, map[string]any{"teams": g.teams, "scopes": []string{"calendar:read", "calendar:write"}}) |
| 324 | } |
| 325 | |
| 326 | func (c *Connect) operations(w http.ResponseWriter, _ *http.Request, _ string, _ *grant) { |
| 327 | c.mu.Lock() |
| 328 | ops := slices.Clone(c.Ops) |
| 329 | c.mu.Unlock() |
| 330 | write(w, 200, map[string]any{"operations": ops}) |
| 331 | } |
| 332 | |
| 333 | func (c *Connect) invoke(w http.ResponseWriter, r *http.Request, tok string, g *grant) { |
| 334 | if r.Header.Get("Content-Type") != "application/json" { |
| 335 | write(w, 415, map[string]any{"error": map[string]string{"code": "unsupported_media_type", "message": "Send application/json."}}) |
| 336 | return |
| 337 | } |
| 338 | raw, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) |
| 339 | var in map[string]any |
| 340 | if json.Unmarshal(raw, &in) != nil { |
| 341 | write(w, 422, map[string]any{"error": map[string]string{"code": "invalid", "message": "Send an object."}}) |
| 342 | return |
| 343 | } |
| 344 | c.mu.Lock() |
| 345 | c.calls = append(c.calls, Call{Name: r.PathValue("name"), Bearer: tok, Input: in}) |
| 346 | failed := c.FailNext |
| 347 | c.FailNext = false |
| 348 | c.mu.Unlock() |
| 349 | if failed { |
| 350 | write(w, 503, map[string]any{"error": map[string]string{"code": "unavailable", "message": "The app is unavailable."}}) |
| 351 | return |
| 352 | } |
| 353 | team, _ := in["team"].(string) |
| 354 | if !slices.Contains(g.teams, team) { |
| 355 | write(w, 403, map[string]any{"error": map[string]string{"code": "forbidden", "message": "Select one of this connection's teams."}}) |
| 356 | return |
| 357 | } |
| 358 | write(w, 200, map[string]any{"ok": true, "team": team, "client_id": in["client_id"]}) |
| 359 | } |
| 360 | |
| 361 | func write(w http.ResponseWriter, status int, v any) { |
| 362 | w.Header().Set("Content-Type", "application/json") |
| 363 | w.WriteHeader(status) |
| 364 | _ = json.NewEncoder(w).Encode(v) |
| 365 | } |
| 366 | |
| 367 | func fail(w http.ResponseWriter, status int, code string) { |
| 368 | write(w, status, map[string]string{"error": code}) |
| 369 | } |
| 370 | |
| 371 | func random() string { |
| 372 | b := make([]byte, 32) |
| 373 | _, _ = rand.Read(b) |
| 374 | return base64.RawURLEncoding.EncodeToString(b) |
| 375 | } |
| 376 | |