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 "bytes"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "fmt"
9 "net/http"
10 "strings"
11 "time"
12
13 "github.com/go-chi/chi/v5"
14
15 "amadan.net/oficina/home/roster"
16 "amadan.net/rastrillo/rastrillo/sessions"
17
18 "amadan.net/oficina/calls/internal/calls/hub"
19 "amadan.net/oficina/calls/protocol"
20)
21
22const (
23 // defaultHeartbeat and defaultStreamTTL are Docs' live-sync numbers
24 // (spec §4.1): a comment line every fifteen seconds so a dead stream
25 // is noticed, and a five-minute life so hibernation is never held
26 // off by one. The browser resumes; nothing is lost at the TTL.
27 defaultHeartbeat = 15 * time.Second
28 defaultStreamTTL = 5 * time.Minute
29 streamWriteWindow = 30 * time.Second
30 // minStreamTiming is the floor under both, so a zero or negative
31 // value from SetStreamTimings cannot panic a ticker in a request
32 // goroutine.
33 minStreamTiming = 10 * time.Millisecond
34 // maxLastQuery bounds the resume's ?last= before it is parsed.
35 maxLastQuery = 8 << 10
36)
37
38// sessionKey is the session's identity for the hub (spec §4.2): the
39// session cookie this request presented, keyed through a salt this
40// process chose at boot, so what the hub holds is neither the token nor
41// the hash rastrillo stores. Two tabs of one browser share it, which is
42// what one peer per room and its takeover need; two browsers of one
43// person do not, which §4.4's four streams per person allows.
44//
45// The plan expected the subject plus the session's creation instant.
46// That is not an identity: two sign-ins of one person within one second
47// collide, and the second browser is then refused the room.
48func (a *app) sessionKey(r *http.Request) (string, bool) {
49 s, ok := sessions.Current(r)
50 if !ok || s.Subject == "" {
51 return "", false
52 }
53 c, err := r.Cookie(a.auth.SessionCookie())
54 if err != nil || c.Value == "" {
55 return "", false
56 }
57 return hubSessionKey(a.hubSalt, s.Subject, c.Value), true
58}
59
60// hubSessionKey is the derivation itself, kept apart from the request so
61// its three properties can be gated (review W-4): the subject is bound
62// in as well as the cookie, so the key cannot survive the person it
63// belongs to whatever a cookie value might come to be reused for; the
64// per-boot salt means it is meaningless across a restart; and the
65// result is neither the session token nor the hash rastrillo stores, so
66// a hub key is not a credential.
67func hubSessionKey(salt, subject, cookie string) string {
68 sum := sha256.Sum256([]byte(salt + "|" + subject + "|" + cookie))
69 return hex.EncodeToString(sum[:])
70}
71
72// acceptsEventStream is ruling 15. The attaching stream is only ever
73// opened by EventSource, which always asks for text/event-stream; a
74// cross-site top-level navigation asks for HTML, and without this check
75// it would take the session's one peer slot in the room and hold it for
76// the resume window. Anything else is 406 with {"error":"accept"}. The
77// probe forms are exempt: they attach nothing.
78func acceptsEventStream(r *http.Request) bool {
79 return strings.Contains(strings.ToLower(r.Header.Get("Accept")), "text/event-stream")
80}
81
82// testTTLHeader shortens one stream's life, and only in development.
83// EventSource cannot set a header, so nothing a browser does on its own
84// can reach this; the browser gate rewrites it on the way past, which is
85// the only way to watch a renewal without waiting five minutes. Outside
86// development the header is not read at all: a request may not shorten
87// a stream on its own say-so.
88const testTTLHeader = "X-Calls-Test-TTL"
89
90// streamLifeFor is streamLife with that override applied, through the
91// same floor atLeast puts under every timing — a header cannot panic a
92// timer in a request goroutine any more than SetStreamTimings can.
93func (a *app) streamLifeFor(r *http.Request) time.Duration {
94 if !a.cfg.development() {
95 return a.streamLife()
96 }
97 raw := r.Header.Get(testTTLHeader)
98 if raw == "" {
99 return a.streamLife()
100 }
101 d, err := time.ParseDuration(raw)
102 if err != nil {
103 return a.streamLife()
104 }
105 return atLeast(int64(d))
106}
107
108// streamJSON is every refusal this endpoint makes. The room's client is
109// a script, not a page: spec §4.5 fixes the browser's behaviour per
110// status and body, so a refusal answers JSON rather than the error page
111// a screen would get.
112func streamJSON(w http.ResponseWriter, status int, body map[string]any) {
113 w.Header().Set("Content-Type", "application/json")
114 w.Header().Set("Cache-Control", "no-store")
115 w.WriteHeader(status)
116 if body != nil {
117 _ = json.NewEncoder(w).Encode(body)
118 }
119}
120
121func (a *app) refuseResume(w http.ResponseWriter, re *hub.ResumeError) {
122 body := map[string]any{}
123 if re.Reason != "" {
124 body["reason"] = string(re.Reason)
125 }
126 if re.Boot != "" {
127 body["boot"] = re.Boot
128 }
129 streamJSON(w, re.Status, body)
130}
131
132// stream is GET /m/{sqid}/stream: one SSE stream per peer (spec §4.1),
133// opened fresh on standing or resumed on a participation bound to this
134// session (§2.5). ?probe=1 answers the same statuses and stops there.
135func (a *app) stream(w http.ResponseWriter, r *http.Request) {
136 sqid := chi.URLParam(r, "sqid")
137 person, ok := currentPerson(r)
138 if !ok {
139 a.logger.Error("calls: stream with no person in context", "path", r.URL.Path)
140 streamJSON(w, http.StatusInternalServerError, nil)
141 return
142 }
143 session, ok := a.sessionKey(r)
144 if !ok {
145 a.logger.Error("calls: stream with no session subject", "path", r.URL.Path)
146 streamJSON(w, http.StatusInternalServerError, nil)
147 return
148 }
149 probe := r.URL.Query().Get("probe") == "1"
150 if !probe && !acceptsEventStream(r) {
151 // Not a stream client, so nothing is looked up and nothing is
152 // allocated (ruling 15). This runs before any authorization, so
153 // the answer is identical for every sqid and every person and
154 // discloses nothing — which is why it can afford to be the
155 // truthful 406 rather than the room's 404, and why a
156 // mis-headered client is told to fix its header instead of
157 // being sent round the fresh-stream loop.
158 streamJSON(w, http.StatusNotAcceptable, map[string]any{"error": "accept"})
159 return
160 }
161
162 var sub *hub.Sub
163 var peer hub.PeerID
164 var first []hub.Message
165 // meeting is the row this stream stands on, for team mode's
166 // per-delivery decision (team_stream.go).
167 var meeting Meeting
168
169 if resume := hub.PeerID(r.URL.Query().Get("peer")); resume != "" {
170 // A resume is authorized by the participation, not by standing
171 // (§2.5), but the meeting itself must still be live: End writes
172 // no headstone for a room nobody opened, so ended_at is the only
173 // authority a fresh process has.
174 m, found, err := a.store.meetingBySqid(r.Context(), sqid)
175 if err != nil {
176 a.logger.Error("calls: stream: load meeting", "err", err)
177 streamJSON(w, http.StatusInternalServerError, nil)
178 return
179 }
180 if a.team != nil && found && m.EndedAt == nil {
181 // A call stands on its host (team_host.go). One who has left
182 // has ended it just now, which the tombstone below answers
183 // 410 ended; one who cannot be decided now leaves the
184 // participation to resume and be held (team_stream.go).
185 if _, st := a.meetingStands(r.Context(), m); st == roster.NotMember {
186 m.EndedAt = &time.Time{}
187 }
188 }
189 meeting = m
190 if !found || m.EndedAt != nil {
191 // The hub answers first when it holds a tombstone, so a peer
192 // that was in the room when it ended is told why (410 ended)
193 // rather than sent to open a fresh stream.
194 if re := a.hub.CanResume(r.Context(), sqid, session, resume); re != nil {
195 a.refuseResume(w, re)
196 return
197 }
198 a.refuseResume(w, &hub.ResumeError{Status: http.StatusNotFound, Boot: a.hub.Boot()})
199 return
200 }
201 if probe {
202 if re := a.hub.CanResume(r.Context(), sqid, session, resume); re != nil {
203 a.refuseResume(w, re)
204 return
205 }
206 streamJSON(w, http.StatusNoContent, nil)
207 return
208 }
209 var last map[hub.PeerID]uint64
210 if raw := r.URL.Query().Get("last"); raw != "" {
211 // One seq per peer, sixteen peers to a room: a document this
212 // far past that is not a browser's, and is refused before it
213 // is parsed.
214 if len(raw) > maxLastQuery {
215 streamJSON(w, http.StatusBadRequest, map[string]any{"error": "bad last"})
216 return
217 }
218 if err := json.Unmarshal([]byte(raw), &last); err != nil {
219 streamJSON(w, http.StatusBadRequest, map[string]any{"error": "bad last"})
220 return
221 }
222 }
223 res, err := a.hub.Resume(r.Context(), sqid, session, resume, last)
224 if err != nil {
225 re, ok := err.(*hub.ResumeError)
226 if !ok {
227 a.logger.Error("calls: stream: resume", "err", err)
228 streamJSON(w, http.StatusInternalServerError, nil)
229 return
230 }
231 a.refuseResume(w, re)
232 return
233 }
234 sub, peer = res.Sub, resume
235 // Order matters: the roster, then the replay, then the gaps, all
236 // written before anything the live subscriber carries. The
237 // subscriber is live from the moment Resume returned, and the
238 // browser discards what is at or below the seq it already has,
239 // so a fresh candidate written ahead of the replay would make
240 // the replay look stale.
241 first = append(first, hub.Message{Type: hub.TypeHello, Peer: peer, Boot: a.hub.Boot(), Report: res.ReportToken})
242 if res.Admitted {
243 first = append(first, hub.Message{Type: hub.TypeRoster, Roster: res.Roster})
244 first = append(first, res.Replay...)
245 for _, from := range res.Gap {
246 first = append(first, hub.Message{Type: hub.TypeGap, From: from})
247 }
248 } else {
249 // Waiting or unjoined: nothing about the room (§4.5).
250 first = append(first, hub.Message{Type: hub.TypeState, Waiting: true})
251 }
252 } else {
253 m, found, err := a.store.meetingBySqid(r.Context(), sqid)
254 if err != nil {
255 a.logger.Error("calls: stream: load meeting", "err", err)
256 streamJSON(w, http.StatusInternalServerError, nil)
257 return
258 }
259 if !found || m.EndedAt != nil {
260 if a.requestPartial(r) {
261 // Team mode, standing Unknown: not "gone", which the
262 // browser would take as the end (team_answers.go).
263 teamUnavailableJSON(w)
264 return
265 }
266 streamJSON(w, http.StatusNotFound, map[string]any{"boot": a.hub.Boot()})
267 return
268 }
269 meeting = m
270 st, err := a.standingFor(r.Context(), person, m)
271 if a.team != nil && isTeamUnavailable(err) {
272 // Nothing is allocated for an entry that cannot be decided
273 // now; the browser's ladder asks again.
274 teamUnavailableJSON(w)
275 return
276 }
277 if err != nil {
278 a.logger.Error("calls: stream: standing", "err", err)
279 streamJSON(w, http.StatusInternalServerError, nil)
280 return
281 }
282 if st == StandingNone {
283 // Not this person's meeting to enter: 404, never 403 (§2.5).
284 streamJSON(w, http.StatusNotFound, map[string]any{"boot": a.hub.Boot()})
285 return
286 }
287 if probe {
288 if existing, live := a.hub.LiveForSession(sqid, session); live {
289 streamJSON(w, http.StatusConflict, map[string]any{"peer": string(existing)})
290 return
291 }
292 streamJSON(w, http.StatusNoContent, nil)
293 return
294 }
295 kind := hub.KindGuest
296 if st == StandingMember {
297 kind = hub.KindMember
298 }
299 res, err := a.hub.Open(sqid, session, person.ID, person.Name, kind)
300 switch err {
301 case nil:
302 case hub.ErrSessionHasPeer:
303 streamJSON(w, http.StatusConflict, map[string]any{"peer": string(res.Existing)})
304 return
305 case hub.ErrRoomFull, hub.ErrPersonStreams:
306 streamJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "full"})
307 return
308 default:
309 // ErrUnknownPeer here is the room's headstone: the meeting
310 // ended between the read above and the hub lock.
311 streamJSON(w, http.StatusNotFound, map[string]any{"boot": a.hub.Boot()})
312 return
313 }
314 sub, peer = res.Sub, res.Peer
315 // §15.28: which app, at which version, for the people in the call.
316 a.hub.SetClient(sqid, session, peer, protocol.ClientFor(r.Header.Get(protocol.ClientHeader), r.UserAgent()))
317 first = append(first, hub.Message{Type: hub.TypeHello, Peer: peer, Boot: a.hub.Boot(), Report: res.ReportToken})
318 }
319
320 // From here the participation exists and is this handler's to hold
321 // open. Every exit detaches it — this handler's own subscriber, so a
322 // stream displaced by a second one does not detach its replacement —
323 // which starts the thirty-second resume window (§4.5).
324 defer a.hub.Detach(sqid, peer, sub)
325 if a.team != nil {
326 a.serveTeamStream(w, r, sub, first, meeting, person, sqid, session, peer)
327 return
328 }
329 a.serveStream(w, r, sub, first)
330}
331
332// serveStream writes the events already decided, then the subscriber's,
333// until the client goes, the TTL expires, or the stream is lost.
334func (a *app) serveStream(w http.ResponseWriter, r *http.Request, sub *hub.Sub, first []hub.Message) {
335 rc := http.NewResponseController(w)
336 w.Header().Set("Content-Type", "text/event-stream")
337 w.Header().Set("Cache-Control", "no-store")
338 // Nothing between this process and the browser should buffer an
339 // event stream; nginx and its imitators read this header.
340 w.Header().Set("X-Accel-Buffering", "no")
341 w.WriteHeader(http.StatusOK)
342 if err := rc.Flush(); err != nil {
343 return
344 }
345 for _, m := range first {
346 if !writeEvent(w, rc, m) {
347 return
348 }
349 }
350 heartbeat := time.NewTicker(a.heartbeatEvery())
351 defer heartbeat.Stop()
352 ttl := time.NewTimer(a.streamLifeFor(r))
353 defer ttl.Stop()
354 for {
355 select {
356 case <-r.Context().Done():
357 return
358 case <-a.done:
359 // The process is going down. Shutdown waits for handlers and
360 // does not cancel their contexts, so a live stream would
361 // hold the whole ten-second deadline and turn a clean stop
362 // into a failed one. The browser resumes, as it does at the
363 // TTL.
364 return
365 case <-ttl.C:
366 return
367 case <-heartbeat.C:
368 if !writeRaw(w, rc, ": hb\n\n") {
369 return
370 }
371 case m, ok := <-sub.C():
372 if !ok {
373 return
374 }
375 if !writeEvent(w, rc, m) {
376 return
377 }
378 if m.Type == hub.TypeLost || m.Type == hub.TypeEnded {
379 // Terminal for this stream either way: lost{buffer} is
380 // followed by a resume, the rest by a screen that says
381 // why (§4.5).
382 return
383 }
384 }
385 }
386}
387
388// writeEvent puts one message on the wire as an SSE frame.
389//
390// The encoder, rather than json.Marshal, for one reason: Marshal
391// HTML-escapes `<`, `>` and `&` into <, > and &, and it
392// does so inside a json.RawMessage too. A chat of 2048 literal `<` —
393// validated at 2059 raw bytes, inside §4.4's cap — left this process
394// as 12,299 payload bytes, six times what was measured (Codex S4-2).
395// SSE data is not HTML and no reader of this stream treats it as
396// markup: room.js parses the JSON and puts every string it contains on
397// the page with textContent. Nothing here depends on the escaping.
398//
399// What the escaping never protected against, and what actually matters
400// on a line-oriented wire, is a payload ending its own frame: JSON
401// escapes a newline inside a string as \n rather than emitting one, so
402// no value can produce the blank line that dispatches an event.
403// callstest's TestChatCannotForgeASecondSSEFrame is the gate on that.
404func writeEvent(w http.ResponseWriter, rc *http.ResponseController, m hub.Message) bool {
405 var buf bytes.Buffer
406 enc := json.NewEncoder(&buf)
407 enc.SetEscapeHTML(false)
408 if err := enc.Encode(m); err != nil {
409 return false
410 }
411 // Encode writes its own trailing newline; the frame below supplies
412 // the two this wire format needs.
413 b := bytes.TrimRight(buf.Bytes(), "\n")
414 return writeRaw(w, rc, fmt.Sprintf("event: %s\ndata: %s\n\n", m.Type, b))
415}
416
417// writeRaw writes one SSE frame under a deadline, so a client that has
418// stopped reading cannot hold a goroutine and a participation open.
419func writeRaw(w http.ResponseWriter, rc *http.ResponseController, s string) bool {
420 _ = rc.SetWriteDeadline(time.Now().Add(streamWriteWindow))
421 if _, err := fmt.Fprint(w, s); err != nil {
422 return false
423 }
424 return rc.Flush() == nil
425}
426