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 "errors"
5 "net/http"
6 "strconv"
7 "time"
8
9 "github.com/go-chi/chi/v5"
10
11 "amadan.net/oficina/home/roster"
12
13 "amadan.net/oficina/calls/internal/calls/hub"
14 "amadan.net/oficina/calls/internal/calls/relay"
15)
16
17const (
18 // iceLife and iceRenewAfter are §5.2's numbers: a call's credentials
19 // are minted for three hours, inside the platform contract's
20 // four-hour maximum, and the browser is told to renew at 150
21 // minutes (§5.3 step 4) — well ahead of expiry, so a slow renewal
22 // never runs out mid-call.
23 iceLife = 3 * time.Hour
24 iceRenewAfter = 150 * time.Minute
25 // testIceHeader shortens one answer's life, and only in development
26 // (like stream.go's testTTLHeader): a plain GET can set it, unlike
27 // EventSource, so this one needs no browser gate to reach — the
28 // development gate is what keeps it off production.
29 testIceHeader = "X-Calls-Test-Ice-TTL"
30 minIceLife = 2 * time.Second
31)
32
33// ice answers GET /m/{sqid}/ice?peer= with the RTCIceServer list for one
34// call (§5.2). Authority is the §2.5 last row — an admitted
35// participation bound to this session — through hub.Authorize, which
36// also applies the member re-derivation of §15.12. Every refusal is the
37// same 404 as /signal's, so nothing about another session's
38// participation is observable here. Nothing is logged on success: the
39// answer carries a credential.
40func (a *app) ice(w http.ResponseWriter, r *http.Request) {
41 sqid := chi.URLParam(r, "sqid")
42 session, ok := a.sessionKey(r)
43 if !ok {
44 a.logger.Error("calls: ice with no session subject", "path", r.URL.Path)
45 streamJSON(w, http.StatusInternalServerError, nil)
46 return
47 }
48 if !validSqid(sqid) {
49 a.logger.Warn("calls: ice refused", "room", "invalid", "peer", "", "outcome", "shape")
50 streamJSON(w, http.StatusNotFound, a.notFoundBody())
51 return
52 }
53 peer := r.URL.Query().Get("peer")
54 if !validPeerID(hub.PeerID(peer)) {
55 // peer is never logged here, exactly like signal.go's refusal:
56 // it has not been validated as bounded, printable text (review
57 // Important 2's rule, carried over).
58 a.logger.Warn("calls: ice refused", "room", sqid, "peer", "", "outcome", "shape")
59 streamJSON(w, http.StatusNotFound, a.notFoundBody())
60 return
61 }
62
63 // A session with no live participation in this exact room is
64 // refused the identical not-found answer before the store or the
65 // limiter is ever touched — signal.go's own LiveForSession gate
66 // (review Task 5 item 1), carried over here: nothing is spent and
67 // nothing is read for a room this session holds nothing in.
68 if _, live := a.hub.LiveForSession(sqid, session); !live {
69 a.logger.Warn("calls: ice refused", "room", sqid, "peer", "", "outcome", "unbound")
70 streamJSON(w, http.StatusNotFound, a.notFoundBody())
71 return
72 }
73
74 // Rate limiting shares /signal's own bucket: session+room, never
75 // anything the request claims, so a burst against either endpoint
76 // from one session spends the one budget it can ever spend.
77 if allowed, retry := a.signalLimiter.allow(session+"|"+sqid, a.store.now()); !allowed {
78 w.Header().Set("Retry-After", strconv.Itoa(int(retry.Seconds())+1))
79 a.logger.Warn("calls: ice refused", "room", sqid, "peer", peer, "outcome", "rate")
80 streamJSON(w, http.StatusTooManyRequests, map[string]any{"error": "rate"})
81 return
82 }
83
84 // The meeting itself must be live: a fresh process holds no hub
85 // state for a room nobody has opened, so ended_at is the only
86 // authority it has — stream.go's own fresh-open precedent. This is
87 // checked independently of the hub's own admitted state: the hub
88 // may still think a participation here is live and admitted (ruling
89 // 14 keeps an admitted guest through a lapsed grant, and nothing
90 // tells the hub a meeting ended except the End call an ending
91 // request makes), so this store read is what a still-admitted
92 // participation is refused through once the meeting is over.
93 m, found, err := a.store.meetingBySqid(r.Context(), sqid)
94 if err != nil {
95 a.logger.Error("calls: ice: load meeting", "err", err)
96 streamJSON(w, http.StatusInternalServerError, nil)
97 return
98 }
99 if !found || m.EndedAt != nil {
100 a.logger.Warn("calls: ice refused", "room", sqid, "peer", peer, "outcome", "meeting")
101 streamJSON(w, http.StatusNotFound, a.notFoundBody())
102 return
103 }
104 if a.team != nil {
105 // No relay credential on a host who has left (the meeting is
106 // ended now) or who cannot be decided now (team_host.go).
107 switch _, st := a.meetingStands(r.Context(), m); st {
108 case roster.NotMember:
109 a.logger.Warn("calls: ice refused", "room", sqid, "peer", peer, "outcome", "meeting")
110 streamJSON(w, http.StatusNotFound, a.notFoundBody())
111 return
112 case roster.Unknown:
113 a.logger.Warn("calls: ice refused", "room", sqid, "peer", peer, "outcome", "standing-unknown")
114 teamUnavailableJSON(w)
115 return
116 }
117 }
118
119 switch err := a.hub.Authorize(r.Context(), sqid, session, hub.PeerID(peer)); {
120 case err == nil:
121 case errors.Is(err, hub.ErrUnknownPeer), errors.Is(err, hub.ErrNotAdmitted), errors.Is(err, hub.ErrNotYours):
122 a.logger.Warn("calls: ice refused", "room", sqid, "peer", peer, "outcome", "authority")
123 streamJSON(w, http.StatusNotFound, a.notFoundBody())
124 return
125 case a.team != nil && isTeamUnavailable(err):
126 a.logger.Warn("calls: ice refused", "room", sqid, "peer", peer, "outcome", "standing-unknown")
127 teamUnavailableJSON(w)
128 return
129 default:
130 a.logger.Error("calls: ice: authorize", "room", sqid, "peer", peer, "outcome", "internal", "err", err)
131 streamJSON(w, http.StatusInternalServerError, nil)
132 return
133 }
134
135 now := a.store.now()
136 life, renew := iceLife, iceRenewAfter
137 if a.cfg.development() {
138 if d := time.Duration(a.iceLifeTest.Load()); d > 0 {
139 life = min(max(d, minIceLife), iceLife)
140 renew = life * 5 / 6
141 }
142 if d, err := time.ParseDuration(r.Header.Get(testIceHeader)); err == nil {
143 // Clamped both ways: a header cannot hand time.NewTimer a
144 // zero or a negative any more than stream.go's own
145 // testTTLHeader can (the floor), and cannot mint credentials
146 // that outlive the platform's own four-hour ceiling either
147 // (the cap, at this handler's three-hour default).
148 life = min(max(d, minIceLife), iceLife)
149 renew = life * 5 / 6
150 }
151 }
152
153 regions := a.relayRegions()
154 if len(regions) == 0 {
155 streamJSON(w, http.StatusOK, map[string]any{"iceServers": []relay.ICEServer{}, "expiresAt": 0, "renewAt": 0})
156 return
157 }
158 expiry := now.Add(life)
159 streamJSON(w, http.StatusOK, map[string]any{
160 "iceServers": relay.Mint(regions, expiry),
161 "expiresAt": expiry.Unix(),
162 "renewAt": now.Add(renew).Unix(),
163 })
164}
165