oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1// Package oficina is Equipo's client of oficina-connect, the Oficina
2// apps' connection service: a pre-registered public OAuth 2 client with
3// S256 PKCE. A person connects once (Start, then Finish at the
4// redirect); their rotating refresh token is kept sealed with the
5// instance key, their 5-minute access token only in memory. Host gives
6// the assist registry's oficina provider a current token; Disconnect
7// revokes the connection at connect and forgets it.
8package oficina
9
10import (
11 "context"
12 "crypto/rand"
13 "crypto/sha256"
14 "encoding/base64"
15 "encoding/json"
16 "errors"
17 "io"
18 "net"
19 "net/http"
20 "net/url"
21 "slices"
22 "strings"
23 "sync"
24 "time"
25)
26
27// Domain binds a sealed refresh token to its use.
28const Domain = "oficina.connect"
29
30// The audit kinds; their detail is a code, never a token.
31const (
32 AuditConnect = "oficina.connect"
33 AuditConnectFailed = "oficina.connect_failed"
34 AuditRefreshFailed = "oficina.refresh_failed"
35 AuditDisconnect = "oficina.disconnect"
36)
37
38const (
39 // pendingTTL is how long a started consent may take.
40 pendingTTL = 10 * time.Minute
41 // maxPending bounds the consents started and not finished.
42 maxPending = 1000
43 // early is how long before its expiry an access token is replaced.
44 early = 30 * time.Second
45 timeout = 20 * time.Second
46 maxAnswer = 64 << 10
47)
48
49var (
50 // ErrExpired: the callback is not one this instance is waiting for
51 // from this person (unknown, used, too old, another issuer), or
52 // connect did not accept its code.
53 ErrExpired = errors.New("oficina: consent expired")
54 // ErrDenied: the person did not allow the connection.
55 ErrDenied = errors.New("oficina: consent denied")
56 // ErrUnavailable: connect could not be reached or answered wrongly.
57 ErrUnavailable = errors.New("oficina: connect unavailable")
58 // ErrConfig: the configuration is incomplete or not allowed.
59 ErrConfig = errors.New("oficina: invalid configuration")
60 // ErrNotYours: the consent was started for another person. Its
61 // state is used up all the same.
62 ErrNotYours = errors.New("oficina: consent not this person's")
63)
64
65// Config is the client as connect registered it.
66type Config struct {
67 // Origin is oficina-connect's: https, or http on loopback.
68 Origin string
69 // ClientID is Equipo's pre-registered public client.
70 ClientID string
71 // Redirect is the instance's callback, exactly as registered.
72 Redirect string
73 // Client makes the requests (a default one when nil); Now is the
74 // clock (time.Now when nil).
75 Client *http.Client
76 Now func() time.Time
77}
78
79// Store keeps each person's sealed refresh token. Save and Delete audit
80// the kind they are given (none when empty) in their own transaction.
81type Store interface {
82 Load(ctx context.Context, person string) (sealed string, err error)
83 Save(ctx context.Context, person, sealed, audit string) error
84 Delete(ctx context.Context, person, audit, detail string) error
85 Audit(ctx context.Context, person, kind, detail string) error
86}
87
88// Sealer seals with the instance key, bound to a domain.
89type Sealer interface {
90 Seal(domain string, v any) (string, error)
91 Open(domain, raw string, v any) error
92}
93
94// pending is a consent started and not finished: who it is for, the
95// PKCE verifier (never sent until the exchange) and where to send the
96// browser after.
97type pending struct {
98 person, verifier, returnTo string
99 expires time.Time
100}
101
102// Result is whose consent a callback finished, and where its browser
103// goes next ("" for none given at Start).
104type Result struct {
105 Person, ReturnTo string
106}
107
108// session is a person's tokens in memory: the access token until it
109// expires, and the newest refresh token, unsaved when the store did not
110// take it (it is saved again before anything else).
111type session struct {
112 access string
113 expires time.Time
114 refresh string
115 unsaved bool
116}
117
118// Connector is the client for every person on the instance.
119type Connector struct {
120 cfg Config
121 store Store
122 sealer Sealer
123 client *http.Client
124 now func() time.Time
125
126 mu sync.Mutex
127 pending map[string]pending // sha256 of the state -> who started it
128 sessions map[string]*session
129 locks map[string]*sync.Mutex
130 // allowed, when set (SetAllowed), is asked right before a token
131 // request is sent (a refresh or a consent's code exchange), after the
132 // person's lock is held: a person who may not read their apps has no
133 // token request made (abilities §6.1).
134 allowed func(ctx context.Context, person string) error
135}
136
137// SetAllowed sets the check run right before every token request: a
138// refresh, and a consent's code exchange.
139func (c *Connector) SetAllowed(f func(ctx context.Context, person string) error) {
140 c.mu.Lock()
141 defer c.mu.Unlock()
142 c.allowed = f
143}
144
145// checkAllowed runs the SetAllowed check for person, if any. The caller
146// holds the person's lock and sends its token request next.
147func (c *Connector) checkAllowed(ctx context.Context, person string) error {
148 c.mu.Lock()
149 allowed := c.allowed
150 c.mu.Unlock()
151 if allowed == nil {
152 return nil
153 }
154 return allowed(ctx, person)
155}
156
157// New checks cfg and returns its connector.
158func New(cfg Config, store Store, sealer Sealer) (*Connector, error) {
159 if !allowedOrigin(cfg.Origin, false) || cfg.ClientID == "" || !allowedOrigin(cfg.Redirect, true) || store == nil || sealer == nil {
160 return nil, ErrConfig
161 }
162 c := http.Client{}
163 if cfg.Client != nil {
164 c = *cfg.Client
165 }
166 c.Timeout = timeout
167 c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
168 now := cfg.Now
169 if now == nil {
170 now = time.Now
171 }
172 return &Connector{cfg: cfg, store: store, sealer: sealer, client: &c, now: now, pending: map[string]pending{}, sessions: map[string]*session{}, locks: map[string]*sync.Mutex{}}, nil
173}
174
175// allowedOrigin: an https origin (http only on loopback), with a path
176// only when path is allowed.
177func allowedOrigin(raw string, path bool) bool {
178 u, err := url.Parse(raw)
179 if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || !path && u.Path != "" {
180 return false
181 }
182 host := u.Hostname()
183 ip := net.ParseIP(host)
184 return u.Scheme == "https" || u.Scheme == "http" && (host == "localhost" || ip != nil && ip.IsLoopback())
185}
186
187// Origin is connect's origin.
188func (c *Connector) Origin() string { return c.cfg.Origin }
189
190func (c *Connector) resource() string { return c.cfg.Origin + "/mcp" }
191
192// Start begins a consent for person: the address to send their browser
193// to. The state it carries is 256 random bits, kept here with person,
194// the verifier and returnTo (the caller checks it): one use, ten
195// minutes. The scopes are every read and write scope connect offers,
196// and offline_access; never a share scope.
197func (c *Connector) Start(ctx context.Context, person, returnTo string) (string, error) {
198 scopes, err := c.scopes(ctx)
199 if err != nil {
200 return "", err
201 }
202 verifier, state := random(), random()
203 sum := sha256.Sum256([]byte(verifier))
204 now := c.now()
205 c.mu.Lock()
206 for k, p := range c.pending {
207 if !now.Before(p.expires) {
208 delete(c.pending, k)
209 }
210 }
211 if len(c.pending) >= maxPending {
212 c.mu.Unlock()
213 return "", ErrUnavailable
214 }
215 c.pending[digest(state)] = pending{person: person, verifier: verifier, returnTo: returnTo, expires: now.Add(pendingTTL)}
216 c.mu.Unlock()
217 q := url.Values{}
218 q.Set("response_type", "code")
219 q.Set("client_id", c.cfg.ClientID)
220 q.Set("redirect_uri", c.cfg.Redirect)
221 q.Set("scope", strings.Join(scopes, " "))
222 q.Set("state", state)
223 q.Set("code_challenge", base64.RawURLEncoding.EncodeToString(sum[:]))
224 q.Set("code_challenge_method", "S256")
225 q.Set("resource", c.resource())
226 return c.cfg.Origin + "/oauth/authorize?" + q.Encode(), nil
227}
228
229// scopes are the scopes to ask for, from connect's metadata.
230func (c *Connector) scopes(ctx context.Context) ([]string, error) {
231 req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.cfg.Origin+"/.well-known/oauth-authorization-server", nil)
232 if err != nil {
233 return nil, ErrUnavailable
234 }
235 var meta struct {
236 Scopes []string `json:"scopes_supported"`
237 }
238 if status, err := c.do(req, &meta); err != nil || status != http.StatusOK {
239 return nil, ErrUnavailable
240 }
241 out := []string{"offline_access"}
242 for _, s := range meta.Scopes {
243 app, kind, ok := strings.Cut(s, ":")
244 if ok && app != "" && (kind == "read" || kind == "write") && !slices.Contains(out, s) {
245 out = append(out, s)
246 }
247 }
248 if len(out) == 1 {
249 return nil, ErrUnavailable
250 }
251 return out, nil
252}
253
254// Peek checks the callback's query without finishing anything: the state
255// must be one Start issued, current, from connect's issuer, and the
256// consent allowed. An unknown state is nobody's (Result empty). A state
257// that fails is used up; one that passes stays for Finish, which a
258// proven person (bearer or session) calls with it and the code. The
259// callback alone never exchanges the code: whoever's browser brings it
260// back, only the person who started the consent can finish it.
261func (c *Connector) Peek(ctx context.Context, q url.Values) (Result, error) {
262 key := digest(q.Get("state"))
263 c.mu.Lock()
264 p, ok := c.pending[key]
265 failed := ok && (!c.now().Before(p.expires) || q.Get("iss") != c.cfg.Origin || q.Get("error") != "" || q.Get("code") == "")
266 if failed {
267 delete(c.pending, key)
268 }
269 c.mu.Unlock()
270 if !ok {
271 return Result{}, ErrExpired
272 }
273 res := Result{Person: p.person, ReturnTo: p.returnTo}
274 switch {
275 case !c.now().Before(p.expires) || q.Get("iss") != c.cfg.Origin:
276 return res, c.failed(ctx, p.person, "state", ErrExpired)
277 case q.Get("error") != "":
278 return res, c.failed(ctx, p.person, "access_denied", ErrDenied)
279 case q.Get("code") == "":
280 return res, c.failed(ctx, p.person, "state", ErrExpired)
281 }
282 return res, nil
283}
284
285// Finish completes person's consent: the state is used up whatever
286// happens, must be one Start issued for this person (ErrNotYours) and
287// current; then the code is exchanged with its PKCE verifier. The
288// refresh token is stored sealed; the access token kept in memory.
289func (c *Connector) Finish(ctx context.Context, person, state, code string) error {
290 key := digest(state)
291 c.mu.Lock()
292 p, ok := c.pending[key]
293 delete(c.pending, key)
294 c.mu.Unlock()
295 if !ok {
296 return ErrExpired
297 }
298 if p.person != person {
299 return c.failed(ctx, person, "not_theirs", ErrNotYours)
300 }
301 if !c.now().Before(p.expires) {
302 return c.failed(ctx, person, "state", ErrExpired)
303 }
304 form := url.Values{}
305 form.Set("grant_type", "authorization_code")
306 form.Set("code", code)
307 form.Set("client_id", c.cfg.ClientID)
308 form.Set("redirect_uri", c.cfg.Redirect)
309 form.Set("resource", c.resource())
310 form.Set("code_verifier", p.verifier)
311 lock := c.lock(person)
312 lock.Lock()
313 defer lock.Unlock()
314 // Checked again here, once the lock is held: reading may have been
315 // switched off while this waited on a refresh in flight.
316 if err := c.checkAllowed(ctx, person); err != nil {
317 return err
318 }
319 tok, err := c.token(ctx, form)
320 if errors.Is(err, errGrant) {
321 return c.failed(ctx, person, "invalid_grant", ErrExpired)
322 }
323 if err != nil || tok.Refresh == "" {
324 return c.failed(ctx, person, "unavailable", ErrUnavailable)
325 }
326 sealed, err := c.sealer.Seal(Domain, tok.Refresh)
327 if err != nil {
328 return err
329 }
330 if err := c.store.Save(ctx, person, sealed, AuditConnect); err != nil {
331 return err
332 }
333 c.mu.Lock()
334 c.sessions[person] = &session{access: tok.Access, expires: c.now().Add(tok.lifetime()), refresh: tok.Refresh}
335 c.mu.Unlock()
336 return nil
337}
338
339// failed audits a consent that did not finish and returns err.
340func (c *Connector) failed(ctx context.Context, person, detail string, err error) error {
341 if aerr := c.store.Audit(ctx, person, AuditConnectFailed, detail); aerr != nil {
342 return aerr
343 }
344 return err
345}
346
347// Connected says the person has a connection stored.
348func (c *Connector) Connected(ctx context.Context, person string) (bool, error) {
349 sealed, err := c.store.Load(ctx, person)
350 return sealed != "", err
351}
352
353// Host is connect's origin and a current access token for person: the
354// one in memory until it nearly expires, then a refreshed one, the
355// rotated refresh token stored first. Not ok when the person has no
356// connection, or connect no longer accepts it (then it is forgotten).
357//
358// The per-person lock makes one refresh at a time; a session's fields
359// are read and written only under c.mu (Rejected takes only that), so
360// Host works from a copy.
361func (c *Connector) Host(ctx context.Context, person string) (origin, token string, ok bool, err error) {
362 lock := c.lock(person)
363 lock.Lock()
364 defer lock.Unlock()
365 c.mu.Lock()
366 var s session
367 known := c.sessions[person] != nil
368 if known {
369 s = *c.sessions[person]
370 }
371 c.mu.Unlock()
372 if known && s.unsaved {
373 if err := c.save(ctx, person, s.refresh); err != nil {
374 return "", "", false, err
375 }
376 c.mu.Lock()
377 if cur := c.sessions[person]; cur != nil && cur.refresh == s.refresh {
378 cur.unsaved = false
379 }
380 c.mu.Unlock()
381 }
382 if known && s.access != "" && c.now().Add(early).Before(s.expires) {
383 return c.cfg.Origin, s.access, true, nil
384 }
385 refresh := ""
386 if known {
387 refresh = s.refresh
388 } else {
389 sealed, err := c.store.Load(ctx, person)
390 if err != nil || sealed == "" {
391 return "", "", false, err
392 }
393 if err := c.sealer.Open(Domain, sealed, &refresh); err != nil {
394 return "", "", false, err
395 }
396 }
397 if err := c.checkAllowed(ctx, person); err != nil {
398 return "", "", false, err
399 }
400 form := url.Values{}
401 form.Set("grant_type", "refresh_token")
402 form.Set("refresh_token", refresh)
403 form.Set("client_id", c.cfg.ClientID)
404 form.Set("resource", c.resource())
405 tok, err := c.token(ctx, form)
406 if errors.Is(err, errGrant) {
407 c.drop(person)
408 return "", "", false, c.store.Delete(ctx, person, AuditRefreshFailed, "invalid_grant")
409 }
410 if err != nil {
411 if aerr := c.store.Audit(ctx, person, AuditRefreshFailed, "unavailable"); aerr != nil {
412 return "", "", false, aerr
413 }
414 return "", "", false, err
415 }
416 if tok.Refresh == "" {
417 tok.Refresh = refresh
418 }
419 next := &session{access: tok.Access, expires: c.now().Add(tok.lifetime()), refresh: tok.Refresh}
420 c.mu.Lock()
421 c.sessions[person] = next
422 c.mu.Unlock()
423 if err := c.save(ctx, person, tok.Refresh); err != nil {
424 // Kept in memory, the consumed token is never sent again;
425 // saving is tried again first thing next time.
426 c.mu.Lock()
427 next.unsaved = true
428 c.mu.Unlock()
429 return "", "", false, err
430 }
431 return c.cfg.Origin, tok.Access, true, nil
432}
433
434func (c *Connector) save(ctx context.Context, person, refresh string) error {
435 sealed, err := c.sealer.Seal(Domain, refresh)
436 if err != nil {
437 return err
438 }
439 return c.store.Save(ctx, person, sealed, "")
440}
441
442// Rejected drops the person's access token, which connect refused: the
443// next Host refreshes.
444func (c *Connector) Rejected(person string) {
445 c.mu.Lock()
446 if s := c.sessions[person]; s != nil {
447 s.access = ""
448 }
449 c.mu.Unlock()
450}
451
452// Disconnect revokes the person's connection at connect and forgets it.
453// A revocation connect did not confirm is audited as such; the
454// connection is forgotten either way.
455func (c *Connector) Disconnect(ctx context.Context, person string) error {
456 lock := c.lock(person)
457 lock.Lock()
458 defer lock.Unlock()
459 refresh := ""
460 c.mu.Lock()
461 if s := c.sessions[person]; s != nil {
462 refresh = s.refresh
463 }
464 c.mu.Unlock()
465 if refresh == "" {
466 sealed, err := c.store.Load(ctx, person)
467 if err != nil {
468 return err
469 }
470 if sealed == "" {
471 return nil
472 }
473 if err := c.sealer.Open(Domain, sealed, &refresh); err != nil {
474 return err
475 }
476 }
477 detail := ""
478 form := url.Values{}
479 form.Set("token", refresh)
480 form.Set("client_id", c.cfg.ClientID)
481 req, err := c.post(ctx, "/oauth/revoke", form)
482 if err == nil {
483 var status int
484 if status, err = c.do(req, nil); err == nil && status != http.StatusOK {
485 err = ErrUnavailable
486 }
487 }
488 if err != nil {
489 detail = "revoke_failed"
490 }
491 c.drop(person)
492 return c.store.Delete(ctx, person, AuditDisconnect, detail)
493}
494
495func (c *Connector) drop(person string) {
496 c.mu.Lock()
497 delete(c.sessions, person)
498 c.mu.Unlock()
499}
500
501func (c *Connector) lock(person string) *sync.Mutex {
502 c.mu.Lock()
503 defer c.mu.Unlock()
504 l := c.locks[person]
505 if l == nil {
506 l = &sync.Mutex{}
507 c.locks[person] = l
508 }
509 return l
510}
511
512// errGrant: connect refused the code or refresh token (invalid_grant).
513var errGrant = errors.New("oficina: invalid grant")
514
515type tokens struct {
516 Access string `json:"access_token"`
517 Type string `json:"token_type"`
518 ExpiresIn int `json:"expires_in"`
519 Refresh string `json:"refresh_token"`
520}
521
522func (t tokens) lifetime() time.Duration { return time.Duration(t.ExpiresIn) * time.Second }
523
524// token posts form to connect's token endpoint.
525func (c *Connector) token(ctx context.Context, form url.Values) (tokens, error) {
526 req, err := c.post(ctx, "/oauth/token", form)
527 if err != nil {
528 return tokens{}, ErrUnavailable
529 }
530 var raw json.RawMessage
531 status, err := c.do(req, &raw)
532 if err != nil {
533 return tokens{}, ErrUnavailable
534 }
535 if status == http.StatusBadRequest {
536 var e struct {
537 Error string `json:"error"`
538 }
539 if json.Unmarshal(raw, &e) == nil && e.Error == "invalid_grant" {
540 return tokens{}, errGrant
541 }
542 }
543 var t tokens
544 if status != http.StatusOK || json.Unmarshal(raw, &t) != nil || t.Access == "" || !strings.EqualFold(t.Type, "bearer") || t.ExpiresIn <= 0 {
545 return tokens{}, ErrUnavailable
546 }
547 return t, nil
548}
549
550func (c *Connector) post(ctx context.Context, path string, form url.Values) (*http.Request, error) {
551 req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.cfg.Origin+path, strings.NewReader(form.Encode()))
552 if err != nil {
553 return nil, err
554 }
555 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
556 return req, nil
557}
558
559// do sends req and reads a JSON answer into out (nil: none), at most
560// 64 KiB.
561func (c *Connector) do(req *http.Request, out any) (int, error) {
562 req.Header.Set("Accept", "application/json")
563 resp, err := c.client.Do(req)
564 if err != nil {
565 return 0, ErrUnavailable
566 }
567 defer resp.Body.Close()
568 body, err := io.ReadAll(io.LimitReader(resp.Body, maxAnswer+1))
569 if err != nil || len(body) > maxAnswer {
570 return 0, ErrUnavailable
571 }
572 if out != nil && len(body) > 0 && json.Unmarshal(body, out) != nil {
573 return 0, ErrUnavailable
574 }
575 return resp.StatusCode, nil
576}
577
578func random() string {
579 b := make([]byte, 32)
580 _, _ = rand.Read(b)
581 return base64.RawURLEncoding.EncodeToString(b)
582}
583
584func digest(s string) string {
585 sum := sha256.Sum256([]byte(s))
586 return base64.RawURLEncoding.EncodeToString(sum[:])
587}
588