oficina / agent-access Public

Clone
git clone https://amadan.net/oficina/agent-access

Plain git — no account needed to clone.

Download this file

1package grant
2
3import (
4 "context"
5 "crypto/subtle"
6 "encoding/json"
7 "html/template"
8 "net/http"
9 "net/url"
10 "time"
11)
12
13type Connection struct {
14 ID string
15 Client string
16 Teams, Scopes []string
17 Expires time.Time
18}
19
20func (s *Store) Connections(ctx context.Context, subject string) ([]Connection, error) {
21 rows, err := s.DB.QueryContext(ctx, `SELECT id,client_id,teams,scopes,expires FROM agent_grants WHERE subject=? AND revoked=0 AND expires>? ORDER BY created DESC,id`, subject, s.Now().Unix())
22 if err != nil {
23 return nil, err
24 }
25 defer rows.Close()
26 out := []Connection{}
27 for rows.Next() {
28 var c Connection
29 var teams, scopes string
30 var expires int64
31 if err = rows.Scan(&c.ID, &c.Client, &teams, &scopes, &expires); err != nil {
32 return nil, err
33 }
34 if err = json.Unmarshal([]byte(teams), &c.Teams); err != nil {
35 return nil, err
36 }
37 if err = json.Unmarshal([]byte(scopes), &c.Scopes); err != nil {
38 return nil, err
39 }
40 c.Expires = time.Unix(expires, 0).UTC()
41 out = append(out, c)
42 }
43 return out, rows.Err()
44}
45func (s *Server) manage(w http.ResponseWriter, r *http.Request) {
46 subject := s.cfg.Subject(r)
47 if subject == "" {
48 dest, _ := url.Parse(s.cfg.SignInPath)
49 q := dest.Query()
50 q.Set("return_to", "/connections")
51 dest.RawQuery = q.Encode()
52 http.Redirect(w, r, dest.String(), 303)
53 return
54 }
55 connections, err := s.cfg.Store.Connections(r.Context(), subject)
56 if err != nil {
57 fail(w, 503, "temporarily_unavailable")
58 return
59 }
60 for i := range connections {
61 if client, ok := s.clients[connections[i].Client]; ok {
62 connections[i].Client = client.Name
63 }
64 for j, scope := range connections[i].Scopes {
65 if label, ok := s.cfg.Scopes[scope]; ok {
66 connections[i].Scopes[j] = label
67 }
68 }
69 }
70 encoded := ""
71 if len(connections) > 0 {
72 t := ticket{Purpose: "revoke", Subject: subject, Nonce: random(), Expires: s.cfg.Store.Now().Add(5 * time.Minute).Unix()}
73 encoded, err = s.seal(t)
74 if err != nil {
75 fail(w, 500, "server_error")
76 return
77 }
78 if _, err = s.cfg.Store.DB.ExecContext(r.Context(), `INSERT INTO agent_pending(hash,expires) VALUES(?,?)`, hash(t.Nonce), t.Expires); err != nil {
79 fail(w, 503, "temporarily_unavailable")
80 return
81 }
82 http.SetCookie(w, &http.Cookie{Name: "__Host-oficina-consent", Value: t.Nonce, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: 300})
83 }
84 w.Header().Set("Content-Security-Policy", pageCSP)
85 w.Header().Set("Content-Type", "text/html; charset=utf-8")
86 _ = connectionsPage.Execute(w, map[string]any{"Connections": connections, "Ticket": encoded})
87}
88
89func (s *Server) disconnect(w http.ResponseWriter, r *http.Request) {
90 if len(r.Header.Values("Origin")) != 1 || r.Header.Get("Origin") != s.cfg.Origin {
91 fail(w, 403, "access_denied")
92 return
93 }
94 if !form(w, r) {
95 return
96 }
97 subject := s.cfg.Subject(r)
98 t, err := s.open(r.PostForm.Get("ticket"))
99 cookies := r.CookiesNamed("__Host-oficina-consent")
100 if err != nil || t.Purpose != "revoke" || subject == "" || t.Subject != subject || len(cookies) != 1 || subtle.ConstantTimeCompare([]byte(cookies[0].Value), []byte(t.Nonce)) != 1 || r.PostForm.Get("id") == "" {
101 fail(w, 403, "access_denied")
102 return
103 }
104 tx, err := s.cfg.Store.DB.BeginTx(r.Context(), nil)
105 if err != nil {
106 fail(w, 503, "temporarily_unavailable")
107 return
108 }
109 defer tx.Rollback()
110 result, err := tx.ExecContext(r.Context(), `DELETE FROM agent_pending WHERE hash=? AND expires>?`, hash(t.Nonce), s.cfg.Store.Now().Unix())
111 if err != nil {
112 fail(w, 503, "temporarily_unavailable")
113 return
114 }
115 n, _ := result.RowsAffected()
116 if n != 1 {
117 fail(w, 400, "invalid_request")
118 return
119 }
120 if _, err = tx.ExecContext(r.Context(), `UPDATE agent_grants SET revoked=1 WHERE subject=? AND id=?`, subject, r.PostForm.Get("id")); err != nil {
121 fail(w, 503, "temporarily_unavailable")
122 return
123 }
124 if err = tx.Commit(); err != nil {
125 fail(w, 503, "temporarily_unavailable")
126 return
127 }
128 http.SetCookie(w, &http.Cookie{Name: "__Host-oficina-consent", Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
129 http.Redirect(w, r, "/connections", 303)
130}
131
132var connectionsPage = template.Must(template.New("connections").Parse(pageHead + `<title>Oficina connections</title>` + doorOpen + `<h1>Your connections</h1><p>Connected clients can act within the permissions you approved and your current app access. Disconnecting stops future requests across all apps.</p>{{range .Connections}}<section><h2>{{.Client}}</h2><p>Teams: {{range .Teams}}{{.}} {{end}}</p><ul>{{range .Scopes}}<li>{{.}}</li>{{end}}</ul><p>Expires {{.Expires.Format "2 January 2006"}}</p><form method="post" action="/connections/revoke"><input type="hidden" name="ticket" value="{{$.Ticket}}"><input type="hidden" name="id" value="{{.ID}}"><button>Disconnect {{.Client}}</button></form></section>{{else}}<p>You have no active connections. Connect from your agent app or the Oficina CLI.</p>{{end}}` + doorClose))
133