oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1package web
2
3import (
4 "context"
5 "crypto/ed25519"
6 "crypto/rand"
7 "errors"
8 "net/http"
9 "strings"
10 "sync"
11 "time"
12
13 "amadan.net/oficina/base/internal/equipo"
14 "amadan.net/oficina/base/internal/store"
15)
16
17// askNext is where connecting Equipo comes back to; "home" opens the panel.
18var askNext = map[string]string{"home": "/#ask", "settings": "/settings", "ask": "/ask"}
19
20func nextOf(v string) string {
21 if _, ok := askNext[v]; ok {
22 return v
23 }
24 return "ask"
25}
26
27// pollEvery is Equipo's shortest interval between two exchange attempts.
28// exchangeHold keeps other polls off the link while one exchange runs: the
29// client's 20-second call timeout and a margin.
30const (
31 pollEvery = 5 * time.Second
32 exchangeHold = 30 * time.Second
33)
34
35type connectView struct {
36 Name, Label, State, Next string
37 Code, Verify, Back string
38 Problem string
39}
40
41// askConnectStart is POST /ask/connect: Connect Equipo (or Reconnect). Base
42// makes the member a device key pair, asks Equipo for a sign-in code and
43// shows it; the member approves it in Equipo.
44func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) {
45 me, _ := CurrentMember(r)
46 next := nextOf(r.PostFormValue("next"))
47 ctx := r.Context()
48 // Reconnecting ends the connection there is now, before anything below
49 // can fail: read and marked lost (its host token going with it) in one
50 // locked step, then its device revoked.
51 var ended store.EquipoLink
52 var endedSec deviceSecrets
53 err := a.changeLink(me.ID, func() error {
54 l, sec, state, e := a.askLink(ctx, me)
55 if e != nil || state != askReady {
56 return e
57 }
58 ended, endedSec = l, sec
59 return store.LoseEquipoLink(ctx, a.db, me.ID, l.DeviceID)
60 })
61 if err != nil {
62 a.fail(w, err)
63 return
64 }
65 a.revokeDisplaced(ctx, ended, endedSec, "")
66 pub, key, err := ed25519.GenerateKey(rand.Reader)
67 if err != nil {
68 a.fail(w, err)
69 return
70 }
71 ch, err := a.ask.client.BeginDevice(ctx, pub, a.ask.label)
72 if err != nil {
73 a.logger.Warn("ask: begin device", "err", err)
74 a.renderConnect(w, r, http.StatusBadGateway, connectView{State: askConnect, Next: next,
75 Problem: "Ask Base isn't answering. Try again in a minute."})
76 return
77 }
78 sealed, err := a.sealSecrets(me.ID, deviceSecrets{Seed: key.Seed(), Secret: ch.DeviceSecret,
79 Challenge: ch.Challenge, Nonce: rand.Text()})
80 if err != nil {
81 a.fail(w, err)
82 return
83 }
84 exp := ch.ExpiresAt
85 if exp.IsZero() {
86 exp = time.Now().Add(10 * time.Minute)
87 }
88 // The new link replaces whatever link there is now (a connection made
89 // with Oficina ID while Equipo answered, say), read in the same locked
90 // step, whose device is then revoked. Saving it forgets the host token
91 // with it: a new connection may be another Equipo person.
92 var old store.EquipoLink
93 var oldSec deviceSecrets
94 err = a.changeLink(me.ID, func() (e error) {
95 if old, oldSec, _, e = a.askLink(ctx, me); e != nil {
96 return e
97 }
98 return store.SaveEquipoLink(ctx, a.db, store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(),
99 State: store.EquipoPending, DeviceID: ch.ID, UserCode: ch.UserCode,
100 VerificationURI: a.verifyURI(ch), Sealed: sealed, ExpiresAt: exp})
101 })
102 if err != nil {
103 a.fail(w, err)
104 return
105 }
106 a.revokeDisplaced(ctx, old, oldSec, ch.ID)
107 http.Redirect(w, r, "/ask/connect?next="+next, http.StatusSeeOther)
108}
109
110// verifyURI is Equipo's approval page for ch, which must be on Equipo's
111// own origin: Base links to nothing else.
112func (a *app) verifyURI(ch equipo.Challenge) string {
113 if origin := a.ask.client.Origin(); strings.HasPrefix(ch.VerificationURI, origin+"/") {
114 return ch.VerificationURI
115 }
116 return a.ask.client.Origin() + "/auth/devices/" + ch.ID
117}
118
119// askConnectPage is GET /ask/connect. It only shows: the code to approve
120// while one waits, or what happened to it (?ended=expired or refused). The
121// exchange is POST /ask/connect/check, behind Base's CSRF check.
122func (a *app) askConnectPage(w http.ResponseWriter, r *http.Request) {
123 me, _ := CurrentMember(r)
124 q := r.URL.Query()
125 next := nextOf(q.Get("next"))
126 l, _, state, err := a.askLink(r.Context(), me)
127 if err != nil {
128 a.fail(w, err)
129 return
130 }
131 if state == askReady {
132 http.Redirect(w, r, askNext[next], http.StatusSeeOther)
133 return
134 }
135 v := connectView{State: state, Next: next, Code: l.UserCode, Verify: l.VerificationURI}
136 if ended := q.Get("ended"); state == askConnect && (ended == askExpired || ended == askRefused || ended == askFailed) {
137 v.State = ended
138 }
139 if q.Get("problem") != "" && state == askPending {
140 v.Problem = "Ask Base isn't answering. It will keep trying."
141 }
142 a.renderConnect(w, r, http.StatusOK, v)
143}
144
145// askConnectCheck is POST /ask/connect/check: Check again, and what the
146// connect page's script posts every five seconds. It finishes the
147// exchange once the member has approved the code. The panel's script gets
148// JSON: the state, and the location the form would go to.
149func (a *app) askConnectCheck(w http.ResponseWriter, r *http.Request) {
150 me, _ := CurrentMember(r)
151 next := nextOf(r.PostFormValue("next"))
152 l, sec, state, err := a.askLink(r.Context(), me)
153 if err != nil {
154 a.fail(w, err)
155 return
156 }
157 problem := false
158 if state == askPending {
159 if state, err = a.poll(r.Context(), me, l, sec); err != nil {
160 a.logger.Warn("ask: exchange", "err", err)
161 problem = true
162 }
163 }
164 target := "/ask/connect?next=" + next
165 switch {
166 case state == askReady:
167 target = askNext[next]
168 case state == askExpired || state == askRefused || state == askFailed:
169 target += "&ended=" + state
170 case problem:
171 target += "&problem=1"
172 }
173 if wantsJSON(r) {
174 writeJSON(w, http.StatusOK, map[string]string{"state": state, "next": askNext[next], "location": target})
175 return
176 }
177 http.Redirect(w, r, target, http.StatusSeeOther)
178}
179
180// poll asks Equipo whether the member approved the code, and stores the
181// bearer if so. Only one caller can claim each poll, and not within
182// pollEvery of the last. The bearer is stored only while the link is still
183// this pending device; if it is not (Disconnect, or a newer Connect, came
184// in between), the bearer is revoked at once.
185func (a *app) poll(ctx context.Context, me store.Member, l store.EquipoLink, sec deviceSecrets) (string, error) {
186 claimed, err := store.ClaimEquipoPoll(ctx, a.db, me.ID, l.DeviceID, time.Now(), pollEvery, exchangeHold)
187 if err != nil || !claimed {
188 return askPending, err
189 }
190 // Whatever happens, the next poll may go once this one has ended.
191 defer func() {
192 if err := store.ReleaseEquipoPoll(context.WithoutCancel(ctx), a.db, me.ID, l.DeviceID); err != nil {
193 a.logger.Error("ask: release poll", "err", err)
194 }
195 }()
196 ch := equipo.Challenge{ID: l.DeviceID, DeviceSecret: sec.Secret, Challenge: sec.Challenge}
197 proof, err := equipo.Prove(ed25519.NewKeyFromSeed(sec.Seed), ch, sec.Nonce)
198 if err != nil {
199 return askPending, err
200 }
201 cred, err := a.ask.client.Exchange(ctx, proof)
202 var e *equipo.Error
203 switch {
204 case errors.Is(err, equipo.ErrPending), errors.Is(err, equipo.ErrSlowDown):
205 return askPending, nil
206 case errors.Is(err, equipo.ErrExpired):
207 return askExpired, a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) })
208 case errors.As(err, &e) && e.Status == http.StatusForbidden:
209 return askRefused, a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) })
210 case err != nil:
211 return askPending, err
212 }
213 return a.keep(ctx, me, l, sec, cred), nil
214}
215
216// storeTimeout bounds storing a new bearer, and revoking it if that fails.
217const storeTimeout = 10 * time.Second
218
219// keep stores the bearer an exchange brought back, on its own clock: a
220// browser that went away must not leave a credential Base lost. The link
221// must still be this pending device. If it is this device and already
222// connected (a duplicate exchange won), that connection stays. Otherwise
223// (disconnected, replaced, or the store failed) the device is revoked in
224// Equipo, and the person is told to start again (askFailed) or, if they
225// disconnected, sees that.
226func (a *app) keep(ctx context.Context, me store.Member, l store.EquipoLink, sec deviceSecrets, cred equipo.Credential) string {
227 ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), storeTimeout)
228 defer cancel()
229 sec.Token = cred.Token
230 l.Revision = cred.Revision
231 sealed, err := a.sealSecrets(me.ID, sec)
232 if err == nil {
233 // Only while the link is still this pending device, as it is at
234 // that moment: after Disconnect, or once anything else replaced
235 // it, the bearer is this device's alone to give up.
236 var stored, duplicate bool
237 err = a.changeLink(me.ID, func() (e error) {
238 if stored, e = store.ConnectEquipoLink(ctx, a.db, me.ID, l.DeviceID, sealed, cred.ExpiresAt, cred.Revision); stored || e != nil {
239 return e
240 }
241 now, found, e := store.EquipoLinkFor(ctx, a.db, me.ID)
242 duplicate = found && now.DeviceID == l.DeviceID && now.State == store.EquipoConnected
243 return e
244 })
245 switch {
246 case stored:
247 a.hostFor(ctx, me, l.DeviceID, cred.Token, true)
248 return askReady
249 case duplicate:
250 return askReady
251 case err == nil:
252 a.revoke(ctx, l, sec)
253 return askConnect
254 }
255 }
256 a.logger.Error("ask: store bearer", "device", l.DeviceID, "err", err)
257 a.revoke(ctx, l, sec)
258 if e := a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) }); e != nil {
259 a.logger.Error("ask: forget device", "device", l.DeviceID, "err", e)
260 }
261 return askFailed
262}
263
264// revoke revokes the member's device in Equipo, as itself. It is best
265// effort: the bearer is about to be forgotten either way.
266func (a *app) revoke(ctx context.Context, l store.EquipoLink, sec deviceSecrets) {
267 ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), storeTimeout)
268 defer cancel()
269 err := a.ask.client.RevokeDevice(ctx, sec.Token, l.DeviceID, l.Revision)
270 if err != nil && !errors.Is(err, equipo.ErrUnauthenticated) {
271 a.logger.Warn("ask: revoke device", "device", l.DeviceID, "err", err)
272 }
273}
274
275// revokeDisplaced revokes the device of link old, which a change to the
276// member's link has just replaced or removed, read in that change's locked
277// step: unless it is the device that replaced it (kept), or never had a
278// bearer (a code never approved, which Equipo lets lapse).
279func (a *app) revokeDisplaced(ctx context.Context, old store.EquipoLink, sec deviceSecrets, kept string) {
280 if old.DeviceID != "" && old.DeviceID != kept && sec.Token != "" {
281 a.revoke(ctx, old, sec)
282 }
283}
284
285// askDisconnect is POST /ask/disconnect, from Settings.
286func (a *app) askDisconnect(w http.ResponseWriter, r *http.Request) {
287 me, _ := CurrentMember(r)
288 ctx := r.Context()
289 // Whatever link there is at that moment goes, with the host token, in
290 // one locked step, or Disconnect fails; then its device is revoked.
291 var old store.EquipoLink
292 var oldSec deviceSecrets
293 err := a.changeLink(me.ID, func() (e error) {
294 if old, oldSec, _, e = a.askLink(ctx, me); e != nil {
295 return e
296 }
297 return store.DisconnectEquipo(ctx, a.db, me.ID)
298 })
299 if err != nil {
300 a.fail(w, err)
301 return
302 }
303 a.revokeDisplaced(ctx, old, oldSec, "")
304 http.Redirect(w, r, "/settings", http.StatusSeeOther)
305}
306
307// registerHost gives Equipo a new host token for the member, with the
308// bearer token of their device dev: where Base's operations live (Base's
309// own origin) and what the Assistant presents to call them for this
310// member. The new token replaces the member's last one, which names
311// nobody from then on. It mints nothing unless dev is still the member's
312// connected device: a read that outlived a Disconnect or a new Connect
313// leaves no token behind.
314func (a *app) registerHost(ctx context.Context, me store.Member, dev, token string) error {
315 host, ok, err := store.MintHostTokenFor(ctx, a.db, me.ID, dev)
316 if err != nil || !ok {
317 return err
318 }
319 if err := a.ask.client.RegisterHost(ctx, token, a.cfg.Origin, host); err != nil {
320 return err
321 }
322 return store.MarkHostRegistered(ctx, a.db, me.ID)
323}
324
325// hostFor registers the host of the member's device dev with Equipo:
326// always when fresh (a connection that just became ready), else only if
327// Equipo does not hold their current token yet. It holds the member's
328// lock (lockMember), so registrations, Connect, Disconnect and a lost
329// bearer happen one at a time for each member, and two reads cannot
330// leave Equipo holding a token Base has replaced. A failure is logged
331// (never a token) and tried again on the next read: it neither breaks
332// the chat nor disconnects anyone.
333func (a *app) hostFor(ctx context.Context, me store.Member, dev, token string, fresh bool) {
334 ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), storeTimeout)
335 defer cancel()
336 a.zoneFor(ctx, me, token, fresh)
337 defer a.lockMember(me.ID)()
338 if !fresh {
339 done, err := store.HostRegistered(ctx, a.db, me.ID)
340 if err != nil {
341 a.logger.Error("ask: host registered", "err", err)
342 return
343 }
344 if done {
345 return
346 }
347 }
348 if err := a.registerHost(ctx, me, dev, token); err != nil {
349 a.logger.Warn("ask: register host", "err", err)
350 }
351}
352
353// zoneWait bounds one time-zone call; zoneRetry is how long Base waits
354// after one that failed (5xx, 429, no answer in time) before trying again.
355const (
356 zoneWait = 5 * time.Second
357 zoneRetry = time.Hour
358)
359
360// zoneTold is where telling Equipo a member's time zone has got to: a
361// call in flight (busy; again if a new connection came meanwhile), an
362// answer that settles it (any 2xx, or a 4xx but 404 and 429: the same call
363// would get the same answer), or a failure, after which it waits until
364// retryAt. A 404 is an Equipo without the route yet, which may get it
365// (deployed after Base), so it waits like a failure.
366type zoneTold struct {
367 busy, again, settled bool
368 retryAt time.Time
369}
370
371// zoneFor tells Equipo the member's time zone, the team's (BASE_TIMEZONE),
372// for the times the Assistant writes for them ("Paused until 21:00"),
373// only if they have none of their own yet (SetTimeZone): once each time
374// Base starts, which is when BASE_TIMEZONE can change, and again on a new
375// connection (fresh). It never holds up the page or the member's lock:
376// the call runs on its own, bounded by zoneWait. After a failure (5xx,
377// 429, 404, no answer in time) it is tried again no sooner than zoneRetry.
378func (a *app) zoneFor(parent context.Context, me store.Member, token string, fresh bool) {
379 if a.ask.zone == "" {
380 return
381 }
382 a.ask.zoneMu.Lock()
383 z := a.ask.zones[me.ID]
384 if z == nil {
385 z = &zoneTold{}
386 a.ask.zones[me.ID] = z
387 }
388 switch {
389 case fresh && z.busy:
390 z.again = true
391 case fresh:
392 z.settled, z.retryAt = false, time.Time{}
393 }
394 if z.busy || z.settled || time.Now().Before(z.retryAt) {
395 a.ask.zoneMu.Unlock()
396 return
397 }
398 z.busy = true
399 a.ask.zoneMu.Unlock()
400 caps := equipo.CapabilitiesFuncOf(parent)
401 go func() {
402 ctx, cancel := context.WithTimeout(equipo.WithCapabilitiesFunc(context.Background(), caps), zoneWait)
403 defer cancel()
404 err := a.ask.client.SetTimeZone(ctx, token, a.ask.zone)
405 var e *equipo.Error
406 refused := errors.As(err, &e)
407 settled := err == nil || refused && e.Status >= 400 && e.Status < 500 &&
408 e.Status != http.StatusTooManyRequests && e.Status != http.StatusNotFound
409 switch {
410 case refused && e.Status == http.StatusNotFound:
411 // An Equipo from before the route: expected, not a fault.
412 a.logger.Info("ask: time zone: Equipo has no such route yet", "err", err)
413 case err != nil:
414 a.logger.Warn("ask: time zone", "err", err, "settled", settled)
415 }
416 a.ask.zoneMu.Lock()
417 defer a.ask.zoneMu.Unlock()
418 z.busy, z.settled = false, settled && !z.again
419 z.again = false
420 if !settled {
421 z.retryAt = time.Now().Add(zoneRetry)
422 }
423 }()
424}
425
426// memberConn is a member's lock, held while their connection changes or
427// their host is registered, and their connection's generation, which every
428// change to their link moves on (changeLink). The lock is not reentrant:
429// nothing holding it calls hostFor.
430type memberConn struct {
431 mu sync.Mutex
432 gen uint64
433}
434
435func (a *app) memberConn(id string) *memberConn {
436 c, _ := a.ask.hosts.LoadOrStore(id, &memberConn{})
437 return c.(*memberConn)
438}
439
440// lockMember takes the member's lock and returns its release.
441func (a *app) lockMember(id string) func() {
442 c := a.memberConn(id)
443 c.mu.Lock()
444 return c.mu.Unlock
445}
446
447// changeLink runs change, which changes the member's link (Connect, its
448// approval or end, Disconnect, Ask set up with Oficina ID), under their
449// lock, and moves their connection's generation on: a set-up with Oficina
450// ID that began before it then yields (askOficina). Equipo refusing a key
451// (askLost) is not a change of this kind: a set-up may replace that key.
452func (a *app) changeLink(id string, change func() error) error {
453 c := a.memberConn(id)
454 c.mu.Lock()
455 defer c.mu.Unlock()
456 c.gen++
457 return change()
458}
459
460// linkGenDisconnected is the member's connection generation now, and
461// whether they have disconnected Ask, read together under their lock:
462// Disconnect sets the one and moves the other in one locked step.
463func (a *app) linkGenDisconnected(ctx context.Context, id string) (uint64, bool, error) {
464 c := a.memberConn(id)
465 c.mu.Lock()
466 defer c.mu.Unlock()
467 disconnected, err := store.AskDisconnected(ctx, a.db, id)
468 return c.gen, disconnected, err
469}
470
471func (a *app) renderConnect(w http.ResponseWriter, r *http.Request, status int, v connectView) {
472 v.Name, v.Label, v.Back = a.cfg.Name, a.ask.label, askNext[v.Next]
473 w.Header().Set("Cache-Control", "no-store")
474 if err := a.pages.PageTheme(w, status, "ask_connect", v, themeOf(r)); err != nil {
475 a.fail(w, err)
476 }
477}
478
479func (a *app) fail(w http.ResponseWriter, err error) {
480 a.logger.Error("ask", "err", err)
481 http.Error(w, "unavailable", http.StatusServiceUnavailable)
482}
483