oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1package calls
2
3import (
4 "amadan.net/oficina/home/roster"
5 "amadan.net/oficina/home/teammode"
6 "context"
7 "encoding/json"
8 "errors"
9 "io"
10 "net/http"
11 "strconv"
12 "strings"
13 "time"
14
15 "github.com/go-chi/chi/v5"
16)
17
18// maxAPIBody is the drive surface's request cap: 16 KB, refused before
19// anything is decoded. An agent posts a title and a timestamp; nothing
20// legitimate comes close.
21const maxAPIBody = 16 * 1024
22
23// The per-agent budget (spec §8, Global Constraints): sixty requests a
24// minute, burst sixty — one token a second into a bucket of sixty, so
25// a run of sixty back to back is fine and a loop is not. maxAgentBuckets
26// bounds the map for the same reason maxSignalBuckets does.
27const (
28 apiRatePerSecond = 1
29 apiBurst = 60
30 maxAgentBuckets = 4096
31)
32
33// agentCtxKey carries the resolved agent and its operator from
34// requireAgent to the handler. Nothing else reads it, and no handler
35// re-derives either.
36type agentCtxKey struct{}
37
38type agentPrincipal struct {
39 agent Agent
40 operator Person
41}
42
43func currentAgent(r *http.Request) (agentPrincipal, bool) {
44 ap, ok := r.Context().Value(agentCtxKey{}).(agentPrincipal)
45 return ap, ok
46}
47
48// apiJSON is every answer the drive surface makes. no-store because a
49// response can carry a link token (§8.2) and because an agent's cache
50// is not a place a meeting's state should live.
51func apiJSON(w http.ResponseWriter, status int, body any) {
52 w.Header().Set("Content-Type", "application/json")
53 w.Header().Set("Cache-Control", "no-store")
54 w.WriteHeader(status)
55 if body != nil {
56 _ = json.NewEncoder(w).Encode(body)
57 }
58}
59
60// apiNotFound is the one not-found shape this surface ever answers: an
61// unknown token, a revoked token, a token whose operator has left the
62// team, and a meeting that does not exist are all these same bytes, so
63// nothing about which it was is observable (spec §8.1, §2.5).
64func apiNotFound() map[string]any { return map[string]any{"error": "not-found"} }
65
66// apiRoutes is the drive surface, mounted at the router root OUTSIDE
67// csrf.Protect and outside the session middlewares (see build).
68//
69// Outside csrf.Protect because rastrillo's csrf.SameOrigin refuses a
70// state-changing request carrying none of Sec-Fetch-Site, Origin or
71// Referer, and an agent — which is not a browser — sends none of the
72// three; a POST from one would be a 403 before it reached a handler.
73// That is safe precisely because this surface honours no cookie: the
74// attack CSRF defends against is a browser spending a session it holds
75// ambiently, and there is no ambient credential here to spend. The
76// bearer is the only thing that authenticates a request, and a page on
77// another origin cannot read it.
78//
79// Outside the session middlewares because RequireSession would redirect
80// a bearer-only request to the sign-in page and requirePerson would
81// never run.
82func (a *app) apiRoutes(r chi.Router) {
83 r.Route("/api/v1", func(r chi.Router) {
84 r.Use(capAPIBody)
85 r.Use(a.requireAgent)
86 // A path or method this surface does not have is the same
87 // not-found body everything else answers — and it is answered
88 // behind requireAgent, so an unauthenticated caller cannot map
89 // the routes at all.
90 r.NotFound(func(w http.ResponseWriter, r *http.Request) {
91 a.refuseAPI(w, r, http.StatusNotFound, apiNotFound(), "no-route")
92 })
93 r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
94 a.refuseAPI(w, r, http.StatusNotFound, apiNotFound(), "no-route")
95 })
96 r.Get("/meetings", a.apiListMeetings)
97 r.Post("/meetings", a.apiCreateMeeting)
98 r.Get("/meetings/{sqid}", a.apiGetMeeting)
99 r.Post("/meetings/{sqid}/links", a.apiReplaceLink)
100 r.Post("/meetings/{sqid}/end", a.apiEndMeeting)
101 })
102}
103
104// capAPIBody puts every request on this surface under the 16 KB cap
105// before a handler runs — the operations that read a body and the ones
106// that do not alike. A cap applied inside the decoder only would leave
107// the bodyless writes (`/links`, `/end`) reading nothing and refusing
108// nothing, so a megabyte posted at `/end` would perform the write
109// (review S5-1). MaxBytesReader takes the ResponseWriter so an
110// over-cap body also stops the connection being reused for a body the
111// server never read.
112func capAPIBody(next http.Handler) http.Handler {
113 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
114 if r.Body != nil {
115 r.Body = http.MaxBytesReader(w, r.Body, maxAPIBody)
116 }
117 next.ServeHTTP(w, r)
118 })
119}
120
121// requireAgent is spec §2.5's `/api/v1/*` row: the bearer names an
122// unrevoked agent AND its operator holds member standing right now
123// (§8.1). Both halves are re-derived per request, so an operator
124// dropped from the team takes their agent's reach with them at the next
125// call, with no revocation step (§13's slice-5 gate).
126//
127// A cookie is never read here — not for identity, not for anything.
128func (a *app) requireAgent(next http.Handler) http.Handler {
129 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
130 token, ok := bearerToken(r.Header.Get("Authorization"))
131 if !ok {
132 // The header is missing or is not a bearer at all. This is
133 // the one refusal that is not the not-found body: it says
134 // "you presented no credential", which is true of every
135 // caller and tells an attacker nothing they did not send.
136 w.Header().Set("WWW-Authenticate", "Bearer")
137 a.refuseAPI(w, r, http.StatusUnauthorized, map[string]any{"error": "unauthorized"}, "unauthorized")
138 return
139 }
140 ag, operator, found, err := a.store.agentByToken(r.Context(), token)
141 if err != nil {
142 a.apiServerError(w, r, "resolve agent", err)
143 return
144 }
145 if !found {
146 a.refuseAPI(w, r, http.StatusNotFound, apiNotFound(), "token")
147 return
148 }
149 if a.team != nil {
150 // Team mode: the operator's standing is the roster's, asked
151 // now; it is carried for the writes' guard and the list's
152 // after-check (team_guard.go, apiListMeetings).
153 acc := a.standingOf(r.Context(), operator.ID)
154 switch acc.State() {
155 case roster.NotMember:
156 a.refuseAPI(w, r.WithContext(withAgent(r.Context(), ag, operator)),
157 http.StatusNotFound, apiNotFound(), "reach")
158 return
159 case roster.Unknown:
160 a.logger.Warn("calls: api refused", "agent_id", ag.ID, "outcome", "standing-unknown")
161 teamUnavailableAPI(w)
162 return
163 }
164 r = r.WithContext(teammode.WithAccess(r.Context(), acc))
165 } else if !a.isMember(operator) {
166 a.refuseAPI(w, r.WithContext(withAgent(r.Context(), ag, operator)),
167 http.StatusNotFound, apiNotFound(), "reach")
168 return
169 }
170 r = r.WithContext(withAgent(r.Context(), ag, operator))
171 if ok, retry := a.apiLimiter.allow(actorForAgent(ag), a.store.now()); !ok {
172 w.Header().Set("Retry-After", strconv.Itoa(retryAfterSeconds(retry)))
173 a.refuseAPI(w, r, http.StatusTooManyRequests, map[string]any{"error": "rate"}, "rate")
174 return
175 }
176 next.ServeHTTP(w, r)
177 })
178}
179
180func withAgent(ctx context.Context, ag Agent, operator Person) context.Context {
181 return context.WithValue(ctx, agentCtxKey{}, agentPrincipal{agent: ag, operator: operator})
182}
183
184// bearerToken reads RFC 6750's Authorization: Bearer <token>. The
185// scheme is matched case-insensitively, as HTTP requires; the token
186// itself is taken exactly as sent and is not inspected for shape —
187// whether it looks like one of ours is not this function's question,
188// and answering it here would make a made-up token distinguishable
189// from an unknown one by status alone.
190func bearerToken(header string) (string, bool) {
191 scheme, rest, found := strings.Cut(strings.TrimSpace(header), " ")
192 if !found || !strings.EqualFold(scheme, "bearer") {
193 return "", false
194 }
195 token := strings.TrimSpace(rest)
196 return token, token != ""
197}
198
199// retryAfterSeconds rounds a wait up to whole seconds, never below one:
200// Retry-After is expressed in seconds, and a zero would invite an
201// immediate retry that is certain to be refused again.
202func retryAfterSeconds(d time.Duration) int {
203 s := int((d + time.Second - 1) / time.Second)
204 if s < 1 {
205 return 1
206 }
207 return s
208}
209
210// refuseAPI is every refusal this surface makes: one log line carrying
211// the agent (when the bearer resolved to one) and the outcome, and
212// nothing else — never the token, never its hash, never a link token,
213// never a title (spec §0.1, §8.1). Nothing at all is logged on success.
214func (a *app) refuseAPI(w http.ResponseWriter, r *http.Request, status int, body map[string]any, outcome string) {
215 if ap, ok := currentAgent(r); ok {
216 a.logger.Warn("calls: api refused", "agent_id", ap.agent.ID, "outcome", outcome)
217 } else {
218 a.logger.Warn("calls: api refused", "outcome", outcome)
219 }
220 apiJSON(w, status, body)
221}
222
223func (a *app) apiServerError(w http.ResponseWriter, r *http.Request, what string, err error) {
224 a.logger.Error("calls: api: "+what, "err", err)
225 apiJSON(w, http.StatusInternalServerError, map[string]any{"error": "server"})
226}
227
228// apiMeetingBody is one meeting on the wire (spec §8.2). It is built
229// field by field from the stored row: no model is ever marshalled.
230type apiMeetingBody struct {
231 Sqid string `json:"sqid"`
232 Title string `json:"title"`
233 StartsAt *string `json:"starts_at"`
234 EndedAt *string `json:"ended_at"`
235 LinkPresent bool `json:"link_present"`
236 CreatedBy string `json:"created_by"`
237}
238
239// apiTime is RFC 3339 in UTC, or null. Every moment on this surface is
240// UTC: an agent has no instance zone to render in.
241func apiTime(t *time.Time) *string {
242 if t == nil {
243 return nil
244 }
245 s := t.UTC().Format(time.RFC3339)
246 return &s
247}
248
249// apiBody renders one view. created_by is v.CreatedByPrincipal,
250// already resolved by meetingViewOfCached (a list shares one label
251// cache across its rows; a single-row read passes its own throwaway
252// one) — apiBody used to re-resolve it a second time through its own
253// labels map, which cost every single-row API path two lookups where
254// one would do.
255func (a *app) apiBody(v meetingView) apiMeetingBody {
256 return apiMeetingBody{
257 Sqid: v.Sqid, Title: v.Title,
258 StartsAt: apiTime(v.StartsAt), EndedAt: apiTime(v.EndedAt),
259 LinkPresent: v.LinkPresent, CreatedBy: v.CreatedByPrincipal,
260 }
261}
262
263func (a *app) apiListMeetings(w http.ResponseWriter, r *http.Request) {
264 views, err := a.store.listMeetings(r.Context())
265 if err != nil {
266 a.apiServerError(w, r, "list meetings", err)
267 return
268 }
269 if a.team != nil {
270 views = a.settleHosts(r.Context(), views)
271 // A JSON list cannot carry the partial notice, so a list built
272 // while standing lapsed is a retryable 503, never a short one
273 // (Paul's ruling; asked after building, of the same Access).
274 if acc, _ := teammode.FromContext(r.Context()); acc.Partial() {
275 teamUnavailableAPI(w)
276 return
277 }
278 }
279 out := make([]apiMeetingBody, 0, len(views))
280 for _, v := range views {
281 out = append(out, a.apiBody(v))
282 }
283 apiJSON(w, http.StatusOK, map[string]any{"meetings": out})
284}
285
286// apiCreateRequest is the only shape POST /api/v1/meetings accepts.
287// StartsAt is a *string rather than a time so an unparseable moment is
288// this surface's own 400 rather than encoding/json's.
289type apiCreateRequest struct {
290 Title string `json:"title"`
291 StartsAt *string `json:"starts_at"`
292}
293
294func (a *app) apiCreateMeeting(w http.ResponseWriter, r *http.Request) {
295 var req apiCreateRequest
296 if !a.apiDecode(w, r, &req) {
297 return
298 }
299 // Copied out field by field, never bound onto a model.
300 title := strings.TrimSpace(req.Title)
301 if title == "" || titleTooLong(title) {
302 a.refuseAPI(w, r, http.StatusBadRequest, map[string]any{"error": "bad-request"}, "title")
303 return
304 }
305 var start *time.Time
306 if req.StartsAt != nil {
307 t, err := time.Parse(time.RFC3339, *req.StartsAt)
308 if err != nil {
309 a.refuseAPI(w, r, http.StatusBadRequest, map[string]any{"error": "bad-request"}, "starts-at")
310 return
311 }
312 u := t.UTC()
313 start = &u
314 }
315
316 ap, _ := currentAgent(r)
317 m, token, err := a.store.createMeeting(r.Context(), title, start, actorForAgent(ap.agent))
318 if isTeamUnavailable(err) {
319 teamUnavailableAPI(w)
320 return
321 }
322 if err != nil {
323 a.apiServerError(w, r, "create meeting", err)
324 return
325 }
326 view, err := a.store.meetingViewOf(r.Context(), m)
327 if err != nil {
328 a.apiServerError(w, r, "read the new meeting", err)
329 return
330 }
331 apiJSON(w, http.StatusCreated, map[string]any{
332 "meeting": a.apiBody(view),
333 "link": a.linkURL(token),
334 })
335}
336
337func (a *app) apiGetMeeting(w http.ResponseWriter, r *http.Request) {
338 m, ok := a.apiMeetingFor(w, r)
339 if !ok {
340 return
341 }
342 view, err := a.store.meetingViewOf(r.Context(), m)
343 if err != nil {
344 a.apiServerError(w, r, "read meeting", err)
345 return
346 }
347 body := map[string]any{"meeting": a.apiBody(view)}
348 // While it runs, and only while it runs: how many peers are in the
349 // call, never who they are or anything they said (spec §8.2).
350 if m.EndedAt == nil {
351 body["admitted"] = a.hub.AdmittedCount(m.Sqid)
352 }
353 apiJSON(w, http.StatusOK, body)
354}
355
356func (a *app) apiReplaceLink(w http.ResponseWriter, r *http.Request) {
357 m, ok := a.apiMeetingFor(w, r)
358 if !ok {
359 return
360 }
361 if !a.apiNoBody(w, r) {
362 return
363 }
364 // No ended check on the snapshot read above. A meeting can end
365 // between that read and this write (review S5-2); the authority is
366 // store.replaceLink's own re-read of ended_at inside its own
367 // transaction, which answers errMeetingEnded.
368 ap, _ := currentAgent(r)
369 token, err := a.store.replaceLink(r.Context(), m.ID, actorForAgent(ap.agent))
370 if isTeamUnavailable(err) {
371 teamUnavailableAPI(w)
372 return
373 }
374 if errors.Is(err, errMeetingEnded) {
375 a.refuseAPI(w, r, http.StatusConflict, map[string]any{"error": "ended"}, "ended")
376 return
377 }
378 if err != nil {
379 a.apiServerError(w, r, "replace link", err)
380 return
381 }
382 view, err := a.store.meetingViewOf(r.Context(), m)
383 if err != nil {
384 a.apiServerError(w, r, "read meeting", err)
385 return
386 }
387 apiJSON(w, http.StatusOK, map[string]any{
388 "meeting": a.apiBody(view),
389 "link": a.linkURL(token),
390 })
391}
392
393func (a *app) apiEndMeeting(w http.ResponseWriter, r *http.Request) {
394 m, ok := a.apiMeetingFor(w, r)
395 if !ok {
396 return
397 }
398 if !a.apiNoBody(w, r) {
399 return
400 }
401 // As with replace: the ended check is the conditional UPDATE inside
402 // store.endMeeting, not the snapshot read above (review S5-2). The
403 // end that changed no row is the 409, so exactly one of two racing
404 // ends gets the 200.
405 ap, _ := currentAgent(r)
406 ended, err := a.store.endMeeting(r.Context(), m.ID, actorForAgent(ap.agent))
407 if isTeamUnavailable(err) {
408 teamUnavailableAPI(w)
409 return
410 }
411 if err != nil {
412 a.apiServerError(w, r, "end meeting", err)
413 return
414 }
415 if !ended {
416 a.refuseAPI(w, r, http.StatusConflict, map[string]any{"error": "ended"}, "ended")
417 return
418 }
419 // The row is the authority; the hub is told so every open stream
420 // gets lost{ended} now rather than at the next tick (spec §2.4),
421 // exactly as the screen's own end does.
422 a.hub.End(m.Sqid)
423
424 row, ok, err := a.store.meetingBySqid(r.Context(), m.Sqid)
425 if err != nil {
426 a.apiServerError(w, r, "read the ended meeting", err)
427 return
428 }
429 if !ok {
430 a.refuseAPI(w, r, http.StatusNotFound, apiNotFound(), "meeting")
431 return
432 }
433 view, err := a.store.meetingViewOf(r.Context(), row)
434 if err != nil {
435 a.apiServerError(w, r, "read the ended meeting", err)
436 return
437 }
438 apiJSON(w, http.StatusOK, map[string]any{"meeting": a.apiBody(view)})
439}
440
441// apiMeetingFor loads the meeting named in the path, or answers the
442// one not-found body. The id is checked for shape first, as every
443// other sqid-taking endpoint does: chi hands back whatever the request
444// line contained, and an unbounded string has no business reaching a
445// query or a log line.
446func (a *app) apiMeetingFor(w http.ResponseWriter, r *http.Request) (Meeting, bool) {
447 sqid := chi.URLParam(r, "sqid")
448 if !validSqid(sqid) {
449 a.refuseAPI(w, r, http.StatusNotFound, apiNotFound(), "bad-room")
450 return Meeting{}, false
451 }
452 m, ok, err := a.store.meetingBySqid(r.Context(), sqid)
453 if err != nil {
454 a.apiServerError(w, r, "load meeting", err)
455 return Meeting{}, false
456 }
457 if !ok {
458 a.refuseAPI(w, r, http.StatusNotFound, apiNotFound(), "meeting")
459 return Meeting{}, false
460 }
461 if a.team != nil && m.EndedAt == nil {
462 // A meeting stands on its host (team_host.go): one whose host
463 // has left is ended now, and read again so the answer says so.
464 switch _, st := a.meetingStands(r.Context(), m); st {
465 case roster.Unknown:
466 teamUnavailableAPI(w)
467 return Meeting{}, false
468 case roster.NotMember:
469 if m, ok, err = a.store.meetingBySqid(r.Context(), sqid); err != nil || !ok {
470 a.refuseAPI(w, r, http.StatusNotFound, apiNotFound(), "meeting")
471 return Meeting{}, false
472 }
473 }
474 }
475 return m, true
476}
477
478// apiDecode reads the body as dst: under capAPIBody's 16 KB cap,
479// unknown fields refused, and EOF required after the one object — so a
480// second document, a stray `]` or `}`, or any other tail behind the
481// first value is a 400 rather than a silently ignored remainder.
482//
483// EOF is required rather than dec.More() asked (review S5-1). More()
484// answers "is another array or object element waiting", which is not
485// the same question: it is false for a trailing `]`, false for a
486// trailing `}`, and — worse — it swallows the decoder's stored read
487// error, so a valid object followed by 17 KB of whitespace came back as
488// a clean decode rather than the 413 the cap promises. A second Decode
489// asks the honest question and hands back the honest error.
490func (a *app) apiDecode(w http.ResponseWriter, r *http.Request, dst any) bool {
491 dec := json.NewDecoder(r.Body)
492 dec.DisallowUnknownFields()
493 if err := dec.Decode(dst); err != nil {
494 return a.refuseBody(w, r, err)
495 }
496 // Anything at all after the first value — a second value (err nil),
497 // a syntax error, or bytes past the cap — is a refusal. Only io.EOF
498 // means "that was the whole body".
499 var tail json.RawMessage
500 if err := dec.Decode(&tail); !errors.Is(err, io.EOF) {
501 return a.refuseBody(w, r, err)
502 }
503 return true
504}
505
506// refuseBody is the one place a body error becomes a status: a cap
507// breach is 413 and everything else — malformed JSON, an unknown field,
508// a trailing value, an empty body, a read that failed — is 400. Always
509// returns false, so a caller can `return a.refuseBody(...)`.
510func (a *app) refuseBody(w http.ResponseWriter, r *http.Request, err error) bool {
511 var tooBig *http.MaxBytesError
512 if errors.As(err, &tooBig) {
513 a.refuseAPI(w, r, http.StatusRequestEntityTooLarge, map[string]any{"error": "too-large"}, "size")
514 return false
515 }
516 a.refuseAPI(w, r, http.StatusBadRequest, map[string]any{"error": "bad-request"}, "shape")
517 return false
518}
519
520// apiNoBody is the bodyless writes' half of the same rule (review
521// S5-1): `/links` and `/end` take no body at all, so the body is read
522// to its end — under capAPIBody's cap — and refused if it carried
523// anything, before the write rather than after it. Over the cap is 413;
524// any other content is 400. An absent body and a Content-Length: 0 body
525// are the two shapes that pass.
526func (a *app) apiNoBody(w http.ResponseWriter, r *http.Request) bool {
527 if r.Body == nil {
528 return true
529 }
530 n, err := io.Copy(io.Discard, r.Body)
531 if err != nil {
532 return a.refuseBody(w, r, err)
533 }
534 if n > 0 {
535 a.refuseAPI(w, r, http.StatusBadRequest, map[string]any{"error": "bad-request"}, "body")
536 return false
537 }
538 return true
539}
540