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/estilo.git/brand"
5 "amadan.net/oficina/estilo.git/chrome"
6 "amadan.net/oficina/estilo.git/sky"
7 "amadan.net/oficina/estilo.git/theme"
8 "amadan.net/oficina/home/connect"
9 "amadan.net/oficina/home/teammode"
10 "context"
11 "crypto/rand"
12 "encoding/hex"
13 "fmt"
14 "log/slog"
15 "net/http"
16 "sync/atomic"
17 "time"
18
19 "github.com/go-chi/chi/v5"
20 gormlogger "gorm.io/gorm/logger"
21
22 rauth "amadan.net/rastrillo/rastrillo/auth"
23 "amadan.net/rastrillo/rastrillo/csrf"
24 "amadan.net/rastrillo/rastrillo/db"
25 "amadan.net/rastrillo/rastrillo/migrate"
26
27 "amadan.net/oficina/calls/internal/calls/apns"
28 "amadan.net/oficina/calls/internal/calls/hub"
29 "amadan.net/oficina/calls/internal/calls/relay"
30 "amadan.net/oficina/calls/internal/calls/seal"
31)
32
33// app holds what every handler needs.
34type app struct {
35 // signinMail is the queue sign-in links go through (signin_mail.go).
36 signinMail *mailQueue
37 db *db.DB
38 cfg resolved
39 sealer *seal.Sealer
40 store *store
41 logger *slog.Logger
42 auth *rauth.Auth
43 home *homeIntegration
44 delegated http.Handler
45 agentIssuer, agentTeam string
46 nativeAuth *nativeAuthorization
47 linkBudget *budget
48 outsiderBudget *budget
49 // overBudget counts outsider sign-in attempts the budgets refused,
50 // for sweepHourly to report: never logged on the response path.
51 overBudget atomic.Int64
52 hub *hub.Hub
53 // push is the APNs sender, or nil where no key is configured — which
54 // is every test and every deployment that has not been given one.
55 // Nil is not a degraded mode: knocks still reach every member who is
56 // in the room, exactly as before. It is only the member who is not
57 // there who goes untold.
58 push knockPusher
59 // hubSalt keys the session cookie into the hub's session id, so the
60 // hub holds no session material it did not have to.
61 hubSalt string
62 // signalLimiter is POST /m/{sqid}/signal's per-peer token bucket
63 // (spec §4.4): thirty a second, burst sixty.
64 signalLimiter *rateLimiter
65 // apiLimiter is the drive surface's per-agent token bucket (spec
66 // §8): sixty requests a minute, burst sixty, keyed "agent:<id>".
67 apiLimiter *rateLimiter
68 // qualityLimiter and problemLimiter are the report endpoints' (spec
69 // §15.26), keyed on the reporting participation's tag: a quality
70 // report every ten seconds, burst six; a problem report a minute,
71 // burst three.
72 qualityLimiter *rateLimiter
73 problemLimiter *rateLimiter
74 // autoGate is the automatic report's (spec §15.29): one every ten
75 // minutes and three in all per participation, keyed on its tag.
76 autoGate *autoReportGate
77 // reportLog is where the reports go: Config.ReportLogger.
78 reportLog *slog.Logger
79
80 // tickPass is the housekeeping pass tickLoop runs, nil in production
81 // and everywhere but the one test that records what deadline the
82 // scheduling path hands it (see tickLoop).
83 tickPass func(ctx context.Context, within time.Duration)
84
85 // done closes when the context App was given is cancelled — a
86 // SIGTERM, in the deployed shape. Live streams watch it and return,
87 // because http.Server.Shutdown waits for handlers without
88 // cancelling their contexts: one open stream would otherwise hold
89 // the whole shutdown deadline.
90 done <-chan struct{}
91
92 // The stream's two timings, held as atomics because a test moves
93 // them (SetStreamTimings) while stream handlers are reading them.
94 heartbeat atomic.Int64
95 ttl atomic.Int64
96 // iceLifeTest, when set (tests, development only), is the life every
97 // /ice answer is minted with (SetIceLife).
98 iceLifeTest atomic.Int64
99
100 // allow is the team, held as an atomic for the same reason: a test
101 // drops a member from it (SetAllowlist) while the tick goroutine is
102 // re-deriving standing. Nil means "as resolved at boot"; nothing in
103 // production ever stores into it. Read it with allowNow().
104 allow atomic.Pointer[allowlist]
105
106 // relay is the parsed CARLOS_RELAY contract, held as an atomic so a
107 // test can hand the app a relay after boot (TestHandle.SetRelay)
108 // while a request is reading it. build stores rc.relay once;
109 // production never stores again. Read it with relayRegions().
110 relay atomic.Value
111
112 // team is the roster runtime with team mode on, nil off
113 // (team_config.go). Every team-mode branch keys on it, so with team
114 // mode off none of them runs.
115 team *teamRuntime
116}
117
118// relayRegions is the parsed contract, swapped atomically so a test can
119// hand the app a relay after boot (TestHandle.SetRelay). Production
120// sets it once in build.
121func (a *app) relayRegions() []relay.Region {
122 v, _ := a.relay.Load().([]relay.Region)
123 return v
124}
125
126func (a *app) relayConfigured() bool { return len(a.relayRegions()) > 0 }
127
128func (a *app) heartbeatEvery() time.Duration { return atLeast(a.heartbeat.Load()) }
129func (a *app) streamLife() time.Duration { return atLeast(a.ttl.Load()) }
130
131// atLeast keeps a timing above the floor: time.NewTicker panics on a
132// zero or negative duration, and that would be inside a request.
133func atLeast(ns int64) time.Duration {
134 if d := time.Duration(ns); d > minStreamTiming {
135 return d
136 }
137 return minStreamTiming
138}
139
140// TestHandle is the test-only control surface NewForTest hands back:
141// the app's clock, and the sweep that would otherwise only run on a
142// timer. Tests only; nothing in production holds one.
143type TestHandle struct {
144 a *app
145 stop context.CancelFunc
146}
147
148// ShutdownForTest cancels the context the app was built on, which is
149// what a SIGTERM does to the deployed process: live streams see it and
150// return. It does not stop the handler serving requests.
151func (h *TestHandle) ShutdownForTest() { h.stop() }
152
153// SetStreamTimings shortens the SSE heartbeat and TTL so a test can
154// watch a stream expire without waiting five minutes. Set it before any
155// stream opens: a stream reads both once, when it starts.
156func (h *TestHandle) SetStreamTimings(heartbeat, ttl time.Duration) {
157 h.a.heartbeat.Store(int64(heartbeat))
158 h.a.ttl.Store(int64(ttl))
159}
160
161// SetIceLife shortens the relay credentials /ice mints, for every request
162// (the X-Calls-Test-Ice-TTL header does it for one): a gate that needs a
163// renewal mid-call cannot add a header to the native core's fetch. Zero
164// puts the production life back. Tests only; development only.
165func (h *TestHandle) SetIceLife(d time.Duration) { h.a.iceLifeTest.Store(int64(d)) }
166
167// SetAllowlist replaces the team, so a test can drop a member and watch
168// the next tick apply spec §2.4's transition to everyone that member
169// holds a participation for. The addresses are normalized exactly as
170// resolveAllowlist normalizes $CALLS_ALLOWED_ADDRESSES, and the list is
171// always non-nil: SetAllowlist() with no addresses means "nobody is a
172// member", never development's "everybody is".
173func (h *TestHandle) SetAllowlist(addrs ...string) {
174 list := allowlist{addrs: map[string]struct{}{}}
175 for _, addr := range addrs {
176 if addr = normalizeAddress(addr); addr != "" {
177 list.addrs[addr] = struct{}{}
178 }
179 }
180 h.a.allow.Store(&list)
181}
182
183// SetRelay hands the app a CARLOS_RELAY value after boot. Tests only.
184func (h *TestHandle) SetRelay(raw string) error {
185 regions, err := relay.Parse(raw)
186 if err != nil {
187 return err
188 }
189 h.a.relay.Store(regions)
190 return nil
191}
192
193// TickForTest runs one pass of the hub housekeeping App runs every
194// fifteen seconds: unjoined and lapsed participations dropped,
195// tombstones expired, every joined kind re-derived from standing.
196func (h *TestHandle) TickForTest() {
197 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
198 defer cancel()
199 h.a.hub.Tick(ctx)
200}
201
202// SetClock replaces the store's clock, so a test can expire grants,
203// pending rows and magic links without sleeping.
204func (h *TestHandle) SetClock(now func() time.Time) { h.a.store.clk.set(now) }
205
206// SweepForTest runs one bounded pass of what the hourly ticker runs,
207// using now for both store.sweep and auth.Sweep — Internal 5's one
208// clock for the whole pass, given explicitly rather than read back off
209// the store, so a test does not have to keep the two in step by hand.
210func (h *TestHandle) SweepForTest(now time.Time) {
211 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
212 defer cancel()
213 h.a.sweepOnce(ctx, now)
214}
215
216// NextDue answers what Runtime.NextDue would answer right now — the
217// platform wake-up time App wires to Options.NextDue. Exposed so a
218// black-box callstest test can check it after driving a real request,
219// without reaching into the store directly.
220func (h *TestHandle) NextDue() time.Time { return h.a.nextDue() }
221
222// SignalLimiterSize answers how many keys the signal endpoint's rate
223// limiter currently holds — a black-box test's only window into
224// whether a request minted a bucket at all (review Task 5 item 1: a
225// room id rotation, or anything else refused before the limiter, must
226// leave this unchanged).
227func (h *TestHandle) SignalLimiterSize() int { return h.a.signalLimiter.size() }
228
229// gormWriter is GORM's logger.Writer over the app's slog logger, so
230// GORM's warnings land in one log stream rather than a second stdout
231// format. rastrillo/db has the same adapter, unexported.
232type gormWriter struct{ log *slog.Logger }
233
234func (w gormWriter) Printf(format string, args ...any) {
235 w.log.Warn(fmt.Sprintf(format, args...))
236}
237
238// sweepEvery is how often expired rows are cleared. Nothing depends on
239// it for correctness — every read filters on expiry — so the interval
240// is about not keeping records past their life, not about safety.
241const sweepEvery = time.Hour
242
243// sweepOnce clears Calls' expired pending rows and rastrillo's expired
244// auth links and sessions (review C1-7), one bounded call to
245// store.sweep — not looped, so a caller with a deadline (the boot sweep,
246// SweepForTest) gets one page of work done and returns. An unclicked
247// magic link holds a plaintext address in auth_links, and rastrillo only
248// deletes it when the token is presented or when Sweep is called; nobody
249// was calling Sweep.
250//
251// now drives both halves: one clock for the whole pass (Internal 5), so
252// a test that advances Calls' clock expires rastrillo's auth_links rows
253// too. In production the caller passes the store's own clock, so it is
254// simply time.Now.
255func (a *app) sweepOnce(ctx context.Context, now time.Time) {
256 if n, err := a.store.sweep(ctx, now); err != nil {
257 a.logger.Error("calls: sweep pending joins", "err", err)
258 } else if n > 0 {
259 a.logger.Info("calls: swept pending joins", "deleted", n)
260 }
261 if err := a.auth.Sweep(now); err != nil {
262 a.logger.Error("calls: sweep auth links and sessions", "err", err)
263 }
264}
265
266// sweepHourly is what the ticker runs: store.sweep is bounded to
267// sweepLimit rows a call (review C2-3), so a backlog bigger than that
268// needs more than one call to actually clear it — the loop the boot
269// sweep and SweepForTest deliberately do not do, because a deadline-
270// bound or test-driven caller wants one page of work, not "until done".
271func (a *app) sweepHourly(ctx context.Context) {
272 if n := a.overBudget.Swap(0); n > 0 {
273 a.logger.Warn("calls: outsider sign-in attempts over budget", "count", n)
274 }
275 now := a.store.now()
276 for {
277 n, err := a.store.sweep(ctx, now)
278 if err != nil {
279 a.logger.Error("calls: sweep pending joins", "err", err)
280 break
281 }
282 if n > 0 {
283 a.logger.Info("calls: swept pending joins", "deleted", n)
284 }
285 if n < sweepLimit {
286 break
287 }
288 }
289 if err := a.auth.Sweep(now); err != nil {
290 a.logger.Error("calls: sweep auth links and sessions", "err", err)
291 }
292}
293
294// sweepForever is started by App and not by NewForTest: a test builds an
295// app per case, and an hourly ticker per case is a goroutine per case
296// that outlives it holding the store and the database open. It exits on
297// ctx.Done, so App's caller can stop it by cancelling the context it
298// passed in.
299func (a *app) sweepForever(ctx context.Context) {
300 t := time.NewTicker(sweepEvery)
301 defer t.Stop()
302 for {
303 select {
304 case <-ctx.Done():
305 return
306 case <-t.C:
307 a.sweepHourly(ctx)
308 }
309 }
310}
311
312// tickEvery is the hub's housekeeping interval (spec §2.4): the quiet
313// case, for participations nothing else is touching.
314const tickEvery = 15 * time.Second
315
316// tickForever is started by App and not by NewForTest, for the reason
317// sweepForever is: a ticker per test app is a goroutine per test that
318// outlives it. Tests drive it with TestHandle.TickForTest.
319func (a *app) tickForever(ctx context.Context) { a.tickLoop(ctx, tickEvery) }
320
321// tickLoop is the scheduling path, with the interval as a parameter so
322// the one property that matters can be gated in milliseconds rather than
323// in fifteen-second slots: the deadline each pass is given is the
324// interval between passes, so a pass can never overrun the slot the next
325// one needs. `every` goes to the ticker and to the pass, in one place,
326// and there is no second constant to drift from the first.
327//
328// tickPass is nil everywhere but in that test, which substitutes a
329// recorder for it; the alternative — asserting a constant equals itself
330// — left the relationship unprotected (Codex S2-14).
331func (a *app) tickLoop(ctx context.Context, every time.Duration) {
332 pass := a.tickPass
333 if pass == nil {
334 pass = a.tickOnce
335 }
336 t := time.NewTicker(every)
337 defer t.Stop()
338 for {
339 select {
340 case <-ctx.Done():
341 return
342 case <-t.C:
343 pass(ctx, every)
344 }
345 }
346}
347
348// tickOnce is one housekeeping pass under a deadline of its own (review
349// W-12). The read phase does one standing lookup per joined
350// participation, serially, with the hub lock down; given only the
351// process context, a driver that stops answering would stall §2.4's
352// quiet case for as long as it stayed stuck, and a removed member would
353// then be dropped only by the next thing they did. A pass that runs
354// past the interval has already lost its slot, so `within` is that
355// interval: the reads that did answer are applied, the ones that did
356// not wait for the next pass, which is what Tick already does with a
357// failed lookup.
358func (a *app) tickOnce(ctx context.Context, within time.Duration) {
359 ctx, cancel := context.WithTimeout(ctx, within)
360 defer cancel()
361 a.hub.Tick(ctx)
362}
363
364// build wires the whole app: refusals, schema, router, static files. It
365// returns the *app alongside the mux so tests can reach into it (see
366// NewForTest); production code uses App, which discards the *app.
367//
368// ctx bounds the sweep at boot, and its cancellation is what tells live
369// streams the process is stopping (a.done). The hourly ticker is not
370// started here: App starts it, NewForTest does not, so a test suite does
371// not leak a goroutine per app it builds.
372func build(ctx context.Context, d *db.DB, cfg Config) (*http.ServeMux, *app, error) {
373 rc, err := resolve(cfg)
374 if err != nil {
375 return nil, nil, err
376 }
377 sealer, err := seal.New(rc.dek)
378 if err != nil {
379 return nil, nil, err
380 }
381 // rastrillo/db configures GORM's logger without ParameterizedQueries,
382 // so a slow or failing query is logged with its values interpolated
383 // into the SQL. ensurePerson looks a person up by address, so that
384 // one log line would carry an outsider's plaintext address (review
385 // C1-2). Same thresholds as db.Open, placeholders instead of values.
386 d.G.Logger = gormlogger.New(gormWriter{rc.Logger}, gormlogger.Config{
387 SlowThreshold: 200 * time.Millisecond,
388 LogLevel: gormlogger.Warn,
389 IgnoreRecordNotFoundError: true,
390 ParameterizedQueries: true,
391 })
392
393 // The team marker is read before anything migrates. Off, this is one
394 // sqlite_master read and boot is unchanged; an activated database
395 // without the same binding refuses here (team_config.go).
396 boot, err := teamBootSchema(context.Background(), d.Writer(), rc.team, BootSchema)
397 if err != nil {
398 return nil, nil, fmt.Errorf("calls: team mode: %w", err)
399 }
400 migrated, err := migrate.Apply(context.Background(), d, boot)
401 if err != nil {
402 return nil, nil, err
403 }
404 rc.Logger.Info("migrate", "applied", migrated.Applied,
405 "skipped", migrated.Skipped, "adopted", migrated.Adopted)
406
407 st := &store{g: d.G, sealer: sealer, clk: newClock(time.Now), logger: rc.Logger}
408 a := &app{
409 db: d, cfg: rc, sealer: sealer, store: st, logger: rc.Logger,
410 linkBudget: newBudget(5, 15*time.Minute),
411 outsiderBudget: newBudget(10, 15*time.Minute),
412 }
413 salt := make([]byte, 16)
414 if _, err := rand.Read(salt); err != nil {
415 return nil, nil, err
416 }
417 a.hubSalt = hex.EncodeToString(salt)
418 a.done = ctx.Done()
419 a.heartbeat.Store(int64(defaultHeartbeat))
420 a.ttl.Store(int64(defaultStreamTTL))
421 a.relay.Store(rc.relay)
422 if len(rc.relay) > 0 {
423 rc.Logger.Info("calls: relay configured", "regions", len(rc.relay))
424 }
425 // The hub reads standing back through the app, and never under its
426 // own lock: hubStanding is a database read.
427 // The APNs sender, where a key was configured. Built before the hub
428 // so that a.knocked has something to send with the first time it is
429 // called, which on a busy instance can be immediately.
430 if rc.apns != nil {
431 client, err := apns.New(*rc.apns)
432 if err != nil {
433 return nil, nil, fmt.Errorf("calls: Apple push: %w", err)
434 }
435 a.push = client
436 rc.Logger.Info("calls: Apple push configured", "sandbox", rc.APNsSandbox)
437 }
438 // The hub reads standing back through the app, and never under its
439 // own lock: hubStanding is a database read. Knocked is the same
440 // arrangement for the other direction.
441 a.hub = hub.New(hub.Config{
442 Now: st.now, Logger: rc.Logger, StandingFor: a.hubStanding, Knocked: a.knocked,
443 WaitingRoom: func(ctx context.Context, sqid string) (bool, error) {
444 m, _, err := st.meetingBySqid(ctx, sqid)
445 return m.WaitingRoom, err
446 },
447 })
448 a.signalLimiter = newRateLimiter(30, 60, maxSignalBuckets)
449 a.apiLimiter = newRateLimiter(apiRatePerSecond, apiBurst, maxAgentBuckets)
450 a.qualityLimiter = newRateLimiterEvery(10*time.Second, 6, maxReportBuckets)
451 a.problemLimiter = newRateLimiterEvery(time.Minute, 3, maxReportBuckets)
452 a.autoGate = newAutoReportGate(maxReportBuckets)
453 a.reportLog = rc.ReportLogger
454 if !rc.qualityReports {
455 rc.Logger.Info("calls: quality reports off (CALLS_QUALITY_REPORTS=off)")
456 }
457
458 writer, err := d.G.DB()
459 if err != nil {
460 return nil, nil, err
461 }
462 // Sign-in links go out after the response, from a worker that asks
463 // authorize first (signin_mail.go). It is NOT closed when ctx ends:
464 // ctx ends at SIGTERM, while Server.Shutdown is still letting
465 // accepted requests finish, and a request that reaches the queue
466 // after that must still have its link sent (Astra on #25, round 2).
467 // Whoever built the app closes it once no request can arrive:
468 // Runtime.Close (main, after rastrillo.Serve returns) or the
469 // TestHandle's stop. Only a failed build closes it here.
470 a.signinMail = newMailQueue(a.cfg.mailer, a.authorize, mayMail, a.logger)
471 if w, ok := cfg.Mailer.(queueAttacher); ok {
472 w.AttachSigninQueue(a.signinMail.wait)
473 }
474 authPlugin, err := a.newAuthPlugin(writer)
475 if err != nil {
476 a.signinMail.close()
477 return nil, nil, err
478 }
479 a.auth = authPlugin
480 if err := a.wireHome(); err != nil {
481 a.signinMail.close()
482 return nil, nil, err
483 }
484 if err := a.configureTeam(); err != nil {
485 a.signinMail.close()
486 return nil, nil, fmt.Errorf("calls: team mode: %w", err)
487 }
488
489 if err := a.wireDelegated(); err != nil {
490 a.signinMail.close()
491 return nil, nil, err
492 }
493
494 if err := a.wireNativeAuth(); err != nil {
495 a.signinMail.close()
496 return nil, nil, err
497 }
498
499 // Bounded, not open-ended: a boot sweep runs on the caller's ctx but
500 // must still finish, so an app never fails to start (or hangs a
501 // test) because of a stuck sweep (review C2-3).
502 bootCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
503 a.sweepOnce(bootCtx, a.store.now())
504 cancel()
505
506 r := chi.NewRouter()
507 // Every panic inside the router is the 500 page with a reference and
508 // the viewer's own chrome (errors.go); an unknown route is the 404
509 // page, not chi's plain text (shared chrome spec §3.3).
510 r.Use(a.recoverToErrorPage)
511 r.NotFound(a.notFound)
512 r.MethodNotAllowed(a.methodNotAllowed(r))
513
514 // The drive surface (spec §8.2) is mounted at the router root,
515 // outside csrf.Protect and outside the session middlewares: an
516 // agent is not a browser and sends none of the headers
517 // csrf.SameOrigin needs (a POST carrying none of them is refused),
518 // while RequireSession would redirect its bearer to the sign-in
519 // page. apiRoutes says why that is safe — this surface honours no
520 // cookie, so there is no ambient credential for CSRF to protect.
521 r.Group(a.apiRoutes)
522 if a.delegated != nil {
523 r.Handle("/api/v1/operations", a.delegated)
524 r.Handle("/api/v1/operations/*", a.delegated)
525 }
526 // The team readiness probe: unauthenticated, outside every session
527 // middleware, and {"team_mode":false} with team mode off.
528 r.Get(teammode.ProbePath, a.teamProbe)
529 r.Post("/native/request", a.nativeRequest)
530 r.Post("/native/exchange", a.nativeExchange)
531
532 r.Group(func(r chi.Router) {
533 if a.home == nil {
534 r.Use(csrf.Protect(rc.Origin))
535 } else {
536 r.Use(a.home.routes.Middleware)
537 }
538 r.Use(a.nativeResume)
539 r.Get("/native/start", a.nativeStart)
540 r.Get("/help/open-source", a.credits)
541 // Appearance is inside the CSRF check and outside the session
542 // group: a session that expired mid-page must not turn the click
543 // into a sign-in loop (spec §8.3).
544 r.Post("/appearance", chrome.HandleAppearance)
545 // The sign-in door is rastrillo's screen in estilo's door
546 // (signin.go). With Home its three routes (home/connect
547 // MIGRATING.md, step 6): /signin is always the door, offering
548 // Continue with Oficina ID; /signin/local is the door with email
549 // as the one way in, where connect sends people Oficina ID cannot
550 // help; /signin/oficina starts the Home exchange. connect hands
551 // both door routes to Calls' door (RoutesConfig.LocalSignin). All
552 // three sit behind the admission check (admittedOnly), which asks
553 // requirePerson's question of a live web sign-in first.
554 r.Get(signinPath, a.signinRoute)
555 // "Use a different email" on the door and "Forget me on this
556 // device" on the signed-out page: a same-origin POST, inside the
557 // CSRF check like any form, and auth's own. With Home, the
558 // signed-out page's chains on to Oficina ID's own Forget
559 // (signin.go's forget).
560 r.Post(signinForgetPath, a.forget)
561 // The handlers rastrillo/auth expects an app to mount. Verify
562 // answers GET with the confirm door (renderConfirm), which spends
563 // nothing, and POST with the redemption, so it is mounted for
564 // both methods in both modes, wrapped alike: without the POST the
565 // door's Sign in button gets a 405 and nobody signs in. The path
566 // is baked into every emailed link. A verified address authorize
567 // refuses is answered by auth's Refused hook (refused), inside
568 // Callback and Verify. POST /signin is Begin behind gateBegin,
569 // with the destination kept Calls' way (beginSignin).
570 if a.home == nil {
571 r.Post(signinPath, a.beginSignin(a.gateBegin(authPlugin.Begin)))
572 r.Get("/auth/callback", authPlugin.Callback)
573 r.Get("/auth/verify", authPlugin.Verify)
574 r.Post("/auth/verify", authPlugin.Verify)
575 r.Post("/signout", a.standaloneSignout(authPlugin.Signout))
576 r.Get("/signed-out", a.signedOut)
577 } else {
578 r.Post(signinPath, a.home.routes.LocalGuard(a.beginSignin(a.gateBegin(authPlugin.Begin))))
579 r.Get("/auth/callback", a.home.routes.LocalGuard(authPlugin.Callback))
580 r.Get("/auth/verify", a.home.routes.LocalGuard(authPlugin.Verify))
581 r.Post("/auth/verify", a.home.routes.LocalGuard(authPlugin.Verify))
582 r.Post("/signout", a.homeSignout)
583 r.Get(connect.SigninLocalPath, a.home.routes.LocalGuard(a.homeDoor(a.home.routes.SigninLocal)))
584 r.Get(connect.SigninOficinaPath, a.homeDoor(a.oficinaJoinLanding(a.home.routes.SigninOficina)))
585 r.Get("/signed-out", a.home.routes.SignedOut)
586 r.Get("/auth/start", a.home.bridge.Start)
587 r.Post("/auth/assertion", a.home.bridge.Callback)
588 r.Get("/auth/finish", a.home.bridge.Finish)
589 r.Get("/auth/local/complete", a.home.routes.LocalComplete)
590 // The member choice (team mode; connect answers 404 without
591 // the team hooks): no session yet, and the POST inside the
592 // CSRF check like any form (connect also demands this Origin).
593 r.Get(connect.ChoosePath, a.home.bridge.ChoosePage)
594 r.Post(connect.ChoosePath, a.chooseJoinLanding(a.home.bridge.ChoosePost))
595 }
596 r.Get("/j/{token}", a.followLink)
597 r.Post("/j/{token}/guest", a.joinGuest)
598
599 // A verified or guest session, with a persons row. Guest sessions are
600 // restricted to participation and native authorization routes.
601 r.Group(func(r chi.Router) {
602 r.Use(a.requireParticipant)
603 r.Get("/", a.index)
604 r.Get("/native/complete", a.nativeComplete)
605 r.Get("/native/authorize", a.nativeAuthorize)
606 r.Post("/native/authorize", a.nativeApprove)
607 r.Get("/continue", a.continueSignedIn)
608 r.Get("/welcome", a.welcome)
609 r.Get("/m/{sqid}/join", a.holding)
610 r.Get("/m/{sqid}/app", a.appOffer)
611 r.Get("/native/offer", a.offerPage)
612 r.Get("/m/{sqid}", a.room)
613 r.Get("/m/{sqid}/info", a.roomInfo)
614 r.Get("/m/{sqid}/remove/{peer}", a.confirmRemove)
615 r.Post("/m/{sqid}/remove/{peer}", a.remove)
616 r.Get("/m/{sqid}/takeover", a.confirmTakeover)
617 r.Post("/m/{sqid}/takeover", a.takeover)
618 if a.team != nil {
619 // Team mode: linking a local account is the local door's
620 // business, not standing's (team_access.go).
621 r.Group(func(r chi.Router) {
622 r.Use(a.requireLinkable)
623 r.Get("/account/home", a.home.routes.Account)
624 r.Post("/account/home", a.home.routes.LinkStart)
625 r.Get("/account/home/confirm", a.home.bridge.ConfirmPage)
626 r.Post("/account/home/confirm", a.home.routes.ConfirmPost)
627 })
628 }
629 r.Group(func(r chi.Router) {
630 r.Use(a.requireMember)
631 if a.home != nil && a.team == nil {
632 r.Get("/account/home", a.home.routes.Account)
633 r.Post("/account/home", a.home.routes.LinkStart)
634 r.Get("/account/home/confirm", a.home.bridge.ConfirmPage)
635 r.Post("/account/home/confirm", a.home.routes.ConfirmPost)
636 }
637 r.Post("/meetings/start", a.startCall)
638 r.Post("/native/meetings/start", a.nativeStartMeeting)
639 r.Post("/native/devices", a.registerDevice)
640 r.Post("/meetings", a.createMeeting)
641 r.Post("/m/{sqid}/share", a.shareMeeting)
642 r.Get("/meetings/{sqid}/links/replace", a.confirmReplaceLink)
643 r.Post("/meetings/{sqid}/links", a.replaceLink)
644 r.Get("/meetings/{sqid}/end", a.confirmEnd)
645 r.Post("/meetings/{sqid}/end", a.endMeeting)
646 r.Get("/settings", a.settings)
647 r.Post("/settings/defaults", a.saveDefaults)
648 r.Get("/meetings/{sqid}/settings", a.meetingSettings)
649 r.Post("/meetings/{sqid}/settings", a.saveSettings)
650 r.Post("/settings/agents", a.createAgentHandler)
651 r.Get("/settings/agents/{id}/revoke", a.confirmRevokeAgent)
652 r.Post("/settings/agents/{id}/revoke", a.revokeAgentHandler)
653 })
654 r.Get("/m/{sqid}/stream", a.stream)
655 r.Post("/m/{sqid}/signal", a.signal)
656 r.Get("/m/{sqid}/ice", a.ice)
657 r.Post("/m/{sqid}/quality", a.quality)
658 r.Post("/m/{sqid}/problem", a.problem)
659 r.Post("/m/{sqid}/auto-report", a.autoReport)
660 })
661 })
662
663 mux := http.NewServeMux()
664 mux.HandleFunc("GET /static/credits.css", serveCreditsCSS)
665 mux.Handle("GET /static/", assets.Handler())
666 // The sky behind the sign-in door: estilo's closed set of public
667 // SVGs, sessionless, more specific than /static/ above.
668 mux.Handle("GET "+sky.Prefix, sky.Handler())
669 // estilo's retired v1 Onest files, kept answering so a page cached
670 // before the chrome moved to the system face (estilo AGENTS.md row 9)
671 // still resolves its stylesheet. No page links them.
672 mux.Handle("GET "+theme.FontPrefix, theme.FontHandler())
673 // The app switcher's tile icons: estilo's suite brand marks, public
674 // and sessionless like the sky.
675 mux.Handle("GET "+brand.Prefix, brand.Handler())
676 mux.Handle("/", r)
677 return mux, a, nil
678}
679
680// Runtime is what App hands main beyond the mux: the platform's
681// scheduled-wake function (review C2-2), the error page, and the
682// shutdown drain. It is a struct rather than a bare func so a later
683// addition does not change App's signature again.
684type Runtime struct {
685 // NextDue answers rastrillo.Options.NextDue: the next moment this
686 // app has work, or the zero time when nothing is scheduled.
687 NextDue func() time.Time
688 // ErrorPage answers rastrillo.Options.ErrorPage: the app's own error
689 // page for a panic outside the router.
690 ErrorPage func(w http.ResponseWriter, r *http.Request, status int, ref string)
691 // Close stops the sign-in mail queue taking links and drains it,
692 // within its bounded deadline, returning when that is done. The
693 // queue is NOT closed when App's ctx ends: that happens at SIGTERM,
694 // while Server.Shutdown still lets accepted requests finish, and
695 // their links must go out. So main calls Close after rastrillo.Serve
696 // returns (no request can arrive any more) and before the database
697 // closes; SMTP runs after the response, so Shutdown does not wait
698 // for it. Every caller of App must call Close, or the queue's worker
699 // outlives the app. A second call joins the first.
700 Close func()
701}
702
703// nextDue is Runtime.NextDue's implementation: the earliest of the next
704// nextExpiry (across pending_joins, auth_links and sessions) and one
705// hour from now — the hourly sweep's own interval, so the platform
706// never lets the app sleep past a sweep it would otherwise have run —
707// or the zero time when nothing at all is outstanding, meaning there is
708// nothing to wake early for.
709//
710// A read failure does NOT answer the zero time: zero means "nothing
711// scheduled" to the platform (serve.go's contract), so returning it on
712// a transient error would cancel the wake entirely rather than merely
713// delay it. An hour out is the same retry deadline the healthy path
714// already uses for "nothing due sooner than the next sweep," so a
715// flaky read gets one more try at the next poll instead of going quiet
716// (Codex round 3, C3-1).
717func (a *app) nextDue() time.Time {
718 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
719 defer cancel()
720 retry := a.store.now().Add(sweepEvery)
721 exp, err := a.store.nextExpiry(ctx)
722 if err != nil {
723 a.logger.Error("calls: next due: read next expiry", "err", err)
724 return retry
725 }
726 if exp.IsZero() {
727 return time.Time{}
728 }
729 if retry.Before(exp) {
730 return retry
731 }
732 return exp
733}
734
735// App wires the whole app: refusals, schema, router, static files. It
736// returns a *http.ServeMux because rastrillo.Options.Mux is typed that
737// way; the chi router mounts inside it, and a *Runtime carrying the
738// platform wake function main.go wires to Options.NextDue. It also
739// starts the hourly sweep and the hub tick on ctx, which run until ctx
740// is cancelled or the process exits.
741//
742// Cancel ctx on SIGTERM: live SSE streams end when it is cancelled, and
743// http.Server.Shutdown waits for handlers without cancelling their
744// contexts, so a stream that does not watch this holds the shutdown
745// deadline open.
746func App(ctx context.Context, d *db.DB, cfg Config) (*http.ServeMux, *Runtime, error) {
747 mux, a, err := build(ctx, d, cfg)
748 if err != nil {
749 return nil, nil, err
750 }
751 go a.sweepForever(ctx)
752 go a.tickForever(ctx)
753 // ctx's end stops streams, the sweep and the tick; the sign-in mail
754 // queue keeps taking links until Runtime.Close (see build).
755 return mux, &Runtime{NextDue: a.nextDue, ErrorPage: a.ErrorPage, Close: a.signinMail.close}, nil
756}
757
758// NewForTest builds the app and returns the handler and its test
759// controls. No sweep ticker is started: see build. Tests only;
760// production uses App.
761func NewForTest(d *db.DB, cfg Config) (*http.ServeMux, *TestHandle, error) {
762 ctx, cancel := context.WithCancel(context.Background())
763 mux, a, err := build(ctx, d, cfg)
764 if err != nil {
765 cancel()
766 return nil, nil, err
767 }
768 // A test's stop (ShutdownForTest) ends the app outright, mail queue
769 // included: no server is draining requests in front of it.
770 go func() { <-ctx.Done(); a.signinMail.close() }()
771 return mux, &TestHandle{a: a, stop: cancel}, nil
772}
773