oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1package sheets
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "io"
8 "mime"
9 "net/http"
10 "strconv"
11 "strings"
12 "time"
13
14 access "amadan.net/oficina/agent-access.git"
15 "amadan.net/oficina/home/connect"
16 "amadan.net/oficina/home/roster"
17 "amadan.net/oficina/home/teammode"
18 "gorm.io/gorm"
19)
20
21var errAgentConfig = errors.New("sheets: invalid agent access configuration")
22
23func validateAgentConfig(issuer, team, origin string, home *connect.Credentials) error {
24 if issuer == "" && team == "" {
25 return nil
26 }
27 if issuer == "" || team == "" || strings.TrimSpace(team) != team || len(team) > 128 || home == nil {
28 return errAgentConfig
29 }
30 settings, e := connect.DecodeCredentials(home, origin)
31 if e != nil || settings == nil {
32 return errAgentConfig
33 }
34 if _, e = access.NewRemoteVerifier(issuer, origin+"/api/v1", settings.Issuer); e != nil {
35 return errAgentConfig
36 }
37 return nil
38}
39
40// ConfigureAgentAccess is called after Home and before Router. The same config
41// is validated before opening storage by LoadAuthEnv in the executable.
42func (a *App) ConfigureAgentAccess(issuer, team string, home *connect.Credentials) error {
43 if e := validateAgentConfig(issuer, team, a.origin, home); e != nil {
44 return e
45 }
46 if issuer == "" {
47 return nil
48 }
49 if a.home == nil || a.db == nil || a.sealer == nil {
50 return errAgentConfig
51 }
52 if a.team != nil && a.team.Bindings().Team != team {
53 return errAgentConfig
54 }
55 settings, e := connect.DecodeCredentials(home, a.origin)
56 if e != nil || settings == nil {
57 return errAgentConfig
58 }
59 verifier, e := access.NewRemoteVerifier(issuer, a.origin+"/api/v1", settings.Issuer)
60 if e != nil {
61 return errAgentConfig
62 }
63 agent := &sheetAgent{app: a, issuer: issuer, identityIssuer: settings.Issuer, team: team, key: append([]byte(nil), settings.DEK...)}
64 if e = a.db.Transaction(func(tx *gorm.DB) error { return agent.bind(tx) }); e != nil {
65 return e
66 }
67 a.agent, e = agent.httpHandler(verifier)
68 return e
69}
70func sheetAgentWriteFailure(w http.ResponseWriter, err error) {
71 f := access.SafeFailure(err)
72 status := map[string]int{"unauthenticated": 401, "forbidden": 403, "not_found": 404, "invalid": 422, "conflict": 409, "too_large": 413, "unsupported_media_type": 415, "unavailable": 503}[f.Code]
73 if status == 0 {
74 status = 500
75 }
76 if status == 401 {
77 w.Header().Set("WWW-Authenticate", "Bearer")
78 }
79 w.Header().Set("Content-Type", "application/json")
80 w.WriteHeader(status)
81 _ = json.NewEncoder(w).Encode(map[string]any{"error": f})
82}
83func (a *sheetAgent) httpHandler(verifier access.Verifier) (http.Handler, error) {
84 registry, e := a.registry()
85 if e != nil {
86 return nil, e
87 }
88 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
89 w.Header().Set("Cache-Control", "no-store")
90 parts := strings.Fields(r.Header.Get("Authorization"))
91 if len(r.Header.Values("Authorization")) != 1 || len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
92 sheetAgentWriteFailure(w, access.Fail("unauthenticated", "Connect to Oficina first."))
93 return
94 }
95 p, e := verifier.Verify(r.Context(), parts[1])
96 if e != nil {
97 sheetAgentWriteFailure(w, e)
98 return
99 }
100 name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/")
101 write := name == "sheets_create" || name == "sheets_set_range"
102 discovery := r.Method == "GET" && r.URL.Path == "/api/v1/operations"
103 if discovery && !p.Allows(a.team, "sheets:read") {
104 write = true
105 }
106 member, e := a.member(r.Context(), p, write)
107 if e == nil && name == "sheets_create" {
108 e = a.requireCreator(member)
109 }
110 if e != nil {
111 sheetAgentWriteFailure(w, e)
112 return
113 }
114 state := &sheetAgentContext{member: member, sheets: map[uint64]bool{}}
115 state.verify = func(ctx context.Context) error {
116 current, e := verifier.Verify(ctx, parts[1])
117 if e != nil {
118 return e
119 }
120 scope := "sheets:read"
121 if write {
122 scope = "sheets:write"
123 }
124 if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.team, scope) {
125 return access.Fail("forbidden", "This connection is no longer authorized.")
126 }
127 return nil
128 }
129 ctx := context.WithValue(r.Context(), sheetAgentKey{}, state)
130 if member.team != nil {
131 ctx = teammode.WithAccess(ctx, member.team.Access)
132 }
133 var result any
134 if discovery {
135 result = map[string]any{"operations": registry.List(p)}
136 } else {
137 if r.Method != "POST" || !strings.HasPrefix(r.URL.Path, "/api/v1/operations/") || strings.Contains(name, "/") {
138 sheetAgentWriteFailure(w, access.Fail("not_found", "This operation is unavailable."))
139 return
140 }
141 media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
142 if e != nil || media != "application/json" {
143 sheetAgentWriteFailure(w, access.Fail("unsupported_media_type", "Send application/json."))
144 return
145 }
146 raw, e := io.ReadAll(io.LimitReader(r.Body, sheetAgentLimit+1))
147 if e != nil {
148 sheetAgentWriteFailure(w, access.Fail("invalid", "Could not read the request."))
149 return
150 }
151 if len(raw) > sheetAgentLimit {
152 sheetAgentWriteFailure(w, access.Fail("too_large", "The operation input exceeds 1 MiB."))
153 return
154 }
155 result, e = registry.Call(ctx, p, name, raw)
156 if e != nil {
157 sheetAgentWriteFailure(w, e)
158 return
159 }
160 }
161 body, e := json.Marshal(result)
162 if e != nil {
163 sheetAgentWriteFailure(w, sheetAgentFailure(e))
164 return
165 }
166 if len(body) > sheetAgentLimit {
167 sheetAgentWriteFailure(w, access.Fail("too_large", "The sheet result exceeds 1 MiB."))
168 return
169 }
170 controller := http.NewResponseController(w)
171 check := func() error {
172 now := time.Now()
173 deadline := now.Add(5 * time.Second)
174 if a.app.team != nil && state.member.team.state() == roster.Member {
175 remaining := state.member.team.Remaining()
176 if remaining <= 0 {
177 return access.Fail("unavailable", "Team membership cannot be verified now.")
178 }
179 if lease := now.Add(remaining); lease.Before(deadline) {
180 deadline = lease
181 }
182 }
183 if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
184 deadline = d
185 }
186 checkCtx, cancel := context.WithDeadline(ctx, deadline)
187 defer cancel()
188 if e := state.verify(checkCtx); e != nil {
189 return e
190 }
191 fresh, e := a.member(checkCtx, p, write)
192 if e == nil && name == "sheets_create" {
193 e = a.requireCreator(fresh)
194 }
195 if e != nil {
196 return e
197 }
198 if fresh.ID != member.ID || fresh.Address != member.Address {
199 return access.Fail("forbidden", "The current identity changed.")
200 }
201 if e := a.checkVisible(checkCtx, state, fresh); e != nil {
202 return sheetAgentFailure(e)
203 }
204 if e := checkCtx.Err(); e != nil {
205 return sheetAgentFailure(e)
206 }
207 if e := controller.SetWriteDeadline(deadline); e != nil {
208 return sheetAgentFailure(e)
209 }
210 return nil
211 }
212 if e = check(); e != nil {
213 sheetAgentWriteFailure(w, e)
214 return
215 }
216 defer controller.SetWriteDeadline(time.Time{})
217 w.Header().Set("Content-Type", "application/json")
218 w.Header().Set("Content-Length", strconv.Itoa(len(body)))
219 w.WriteHeader(http.StatusOK)
220 for len(body) > 0 {
221 if e = check(); e != nil {
222 panic(http.ErrAbortHandler)
223 }
224 n := min(len(body), 64<<10)
225 wrote, e := w.Write(body[:n])
226 if e != nil || wrote != n {
227 panic(http.ErrAbortHandler)
228 }
229 body = body[n:]
230 }
231 }), nil
232}
233
234func (a *App) agentRoutes(browser http.Handler) http.Handler {
235 if a.agent == nil {
236 return browser
237 }
238 mux := http.NewServeMux()
239 mux.Handle("/api/v1/operations", a.agent)
240 mux.Handle("/api/v1/operations/", a.agent)
241 mux.Handle("/", browser)
242 return mux
243}
244