package web import ( "context" "crypto/ed25519" "crypto/rand" "errors" "net/http" "strings" "sync" "time" "amadan.net/oficina/base/internal/equipo" "amadan.net/oficina/base/internal/store" ) // askNext is where connecting Equipo comes back to; "home" opens the panel. var askNext = map[string]string{"home": "/#ask", "settings": "/settings", "ask": "/ask"} func nextOf(v string) string { if _, ok := askNext[v]; ok { return v } return "ask" } // pollEvery is Equipo's shortest interval between two exchange attempts. // exchangeHold keeps other polls off the link while one exchange runs: the // client's 20-second call timeout and a margin. const ( pollEvery = 5 * time.Second exchangeHold = 30 * time.Second ) type connectView struct { Name, Label, State, Next string Code, Verify, Back string Problem string } // askConnectStart is POST /ask/connect: Connect Equipo (or Reconnect). Base // makes the member a device key pair, asks Equipo for a sign-in code and // shows it; the member approves it in Equipo. func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) next := nextOf(r.PostFormValue("next")) ctx := r.Context() // Reconnecting ends the connection there is now, before anything below // can fail: read and marked lost (its host token going with it) in one // locked step, then its device revoked. var ended store.EquipoLink var endedSec deviceSecrets err := a.changeLink(me.ID, func() error { l, sec, state, e := a.askLink(ctx, me) if e != nil || state != askReady { return e } ended, endedSec = l, sec return store.LoseEquipoLink(ctx, a.db, me.ID, l.DeviceID) }) if err != nil { a.fail(w, err) return } a.revokeDisplaced(ctx, ended, endedSec, "") pub, key, err := ed25519.GenerateKey(rand.Reader) if err != nil { a.fail(w, err) return } ch, err := a.ask.client.BeginDevice(ctx, pub, a.ask.label) if err != nil { a.logger.Warn("ask: begin device", "err", err) a.renderConnect(w, r, http.StatusBadGateway, connectView{State: askConnect, Next: next, Problem: "Ask Base isn't answering. Try again in a minute."}) return } sealed, err := a.sealSecrets(me.ID, deviceSecrets{Seed: key.Seed(), Secret: ch.DeviceSecret, Challenge: ch.Challenge, Nonce: rand.Text()}) if err != nil { a.fail(w, err) return } exp := ch.ExpiresAt if exp.IsZero() { exp = time.Now().Add(10 * time.Minute) } // The new link replaces whatever link there is now (a connection made // with Oficina ID while Equipo answered, say), read in the same locked // step, whose device is then revoked. Saving it forgets the host token // with it: a new connection may be another Equipo person. var old store.EquipoLink var oldSec deviceSecrets err = a.changeLink(me.ID, func() (e error) { if old, oldSec, _, e = a.askLink(ctx, me); e != nil { return e } return store.SaveEquipoLink(ctx, a.db, store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(), State: store.EquipoPending, DeviceID: ch.ID, UserCode: ch.UserCode, VerificationURI: a.verifyURI(ch), Sealed: sealed, ExpiresAt: exp}) }) if err != nil { a.fail(w, err) return } a.revokeDisplaced(ctx, old, oldSec, ch.ID) http.Redirect(w, r, "/ask/connect?next="+next, http.StatusSeeOther) } // verifyURI is Equipo's approval page for ch, which must be on Equipo's // own origin: Base links to nothing else. func (a *app) verifyURI(ch equipo.Challenge) string { if origin := a.ask.client.Origin(); strings.HasPrefix(ch.VerificationURI, origin+"/") { return ch.VerificationURI } return a.ask.client.Origin() + "/auth/devices/" + ch.ID } // askConnectPage is GET /ask/connect. It only shows: the code to approve // while one waits, or what happened to it (?ended=expired or refused). The // exchange is POST /ask/connect/check, behind Base's CSRF check. func (a *app) askConnectPage(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) q := r.URL.Query() next := nextOf(q.Get("next")) l, _, state, err := a.askLink(r.Context(), me) if err != nil { a.fail(w, err) return } if state == askReady { http.Redirect(w, r, askNext[next], http.StatusSeeOther) return } v := connectView{State: state, Next: next, Code: l.UserCode, Verify: l.VerificationURI} if ended := q.Get("ended"); state == askConnect && (ended == askExpired || ended == askRefused || ended == askFailed) { v.State = ended } if q.Get("problem") != "" && state == askPending { v.Problem = "Ask Base isn't answering. It will keep trying." } a.renderConnect(w, r, http.StatusOK, v) } // askConnectCheck is POST /ask/connect/check: Check again, and what the // connect page's script posts every five seconds. It finishes the // exchange once the member has approved the code. The panel's script gets // JSON: the state, and the location the form would go to. func (a *app) askConnectCheck(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) next := nextOf(r.PostFormValue("next")) l, sec, state, err := a.askLink(r.Context(), me) if err != nil { a.fail(w, err) return } problem := false if state == askPending { if state, err = a.poll(r.Context(), me, l, sec); err != nil { a.logger.Warn("ask: exchange", "err", err) problem = true } } target := "/ask/connect?next=" + next switch { case state == askReady: target = askNext[next] case state == askExpired || state == askRefused || state == askFailed: target += "&ended=" + state case problem: target += "&problem=1" } if wantsJSON(r) { writeJSON(w, http.StatusOK, map[string]string{"state": state, "next": askNext[next], "location": target}) return } http.Redirect(w, r, target, http.StatusSeeOther) } // poll asks Equipo whether the member approved the code, and stores the // bearer if so. Only one caller can claim each poll, and not within // pollEvery of the last. The bearer is stored only while the link is still // this pending device; if it is not (Disconnect, or a newer Connect, came // in between), the bearer is revoked at once. func (a *app) poll(ctx context.Context, me store.Member, l store.EquipoLink, sec deviceSecrets) (string, error) { claimed, err := store.ClaimEquipoPoll(ctx, a.db, me.ID, l.DeviceID, time.Now(), pollEvery, exchangeHold) if err != nil || !claimed { return askPending, err } // Whatever happens, the next poll may go once this one has ended. defer func() { if err := store.ReleaseEquipoPoll(context.WithoutCancel(ctx), a.db, me.ID, l.DeviceID); err != nil { a.logger.Error("ask: release poll", "err", err) } }() ch := equipo.Challenge{ID: l.DeviceID, DeviceSecret: sec.Secret, Challenge: sec.Challenge} proof, err := equipo.Prove(ed25519.NewKeyFromSeed(sec.Seed), ch, sec.Nonce) if err != nil { return askPending, err } cred, err := a.ask.client.Exchange(ctx, proof) var e *equipo.Error switch { case errors.Is(err, equipo.ErrPending), errors.Is(err, equipo.ErrSlowDown): return askPending, nil case errors.Is(err, equipo.ErrExpired): return askExpired, a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) }) case errors.As(err, &e) && e.Status == http.StatusForbidden: return askRefused, a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) }) case err != nil: return askPending, err } return a.keep(ctx, me, l, sec, cred), nil } // storeTimeout bounds storing a new bearer, and revoking it if that fails. const storeTimeout = 10 * time.Second // keep stores the bearer an exchange brought back, on its own clock: a // browser that went away must not leave a credential Base lost. The link // must still be this pending device. If it is this device and already // connected (a duplicate exchange won), that connection stays. Otherwise // (disconnected, replaced, or the store failed) the device is revoked in // Equipo, and the person is told to start again (askFailed) or, if they // disconnected, sees that. func (a *app) keep(ctx context.Context, me store.Member, l store.EquipoLink, sec deviceSecrets, cred equipo.Credential) string { ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), storeTimeout) defer cancel() sec.Token = cred.Token l.Revision = cred.Revision sealed, err := a.sealSecrets(me.ID, sec) if err == nil { // Only while the link is still this pending device, as it is at // that moment: after Disconnect, or once anything else replaced // it, the bearer is this device's alone to give up. var stored, duplicate bool err = a.changeLink(me.ID, func() (e error) { if stored, e = store.ConnectEquipoLink(ctx, a.db, me.ID, l.DeviceID, sealed, cred.ExpiresAt, cred.Revision); stored || e != nil { return e } now, found, e := store.EquipoLinkFor(ctx, a.db, me.ID) duplicate = found && now.DeviceID == l.DeviceID && now.State == store.EquipoConnected return e }) switch { case stored: a.hostFor(ctx, me, l.DeviceID, cred.Token, true) return askReady case duplicate: return askReady case err == nil: a.revoke(ctx, l, sec) return askConnect } } a.logger.Error("ask: store bearer", "device", l.DeviceID, "err", err) a.revoke(ctx, l, sec) if e := a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) }); e != nil { a.logger.Error("ask: forget device", "device", l.DeviceID, "err", e) } return askFailed } // revoke revokes the member's device in Equipo, as itself. It is best // effort: the bearer is about to be forgotten either way. func (a *app) revoke(ctx context.Context, l store.EquipoLink, sec deviceSecrets) { ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), storeTimeout) defer cancel() err := a.ask.client.RevokeDevice(ctx, sec.Token, l.DeviceID, l.Revision) if err != nil && !errors.Is(err, equipo.ErrUnauthenticated) { a.logger.Warn("ask: revoke device", "device", l.DeviceID, "err", err) } } // revokeDisplaced revokes the device of link old, which a change to the // member's link has just replaced or removed, read in that change's locked // step: unless it is the device that replaced it (kept), or never had a // bearer (a code never approved, which Equipo lets lapse). func (a *app) revokeDisplaced(ctx context.Context, old store.EquipoLink, sec deviceSecrets, kept string) { if old.DeviceID != "" && old.DeviceID != kept && sec.Token != "" { a.revoke(ctx, old, sec) } } // askDisconnect is POST /ask/disconnect, from Settings. func (a *app) askDisconnect(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) ctx := r.Context() // Whatever link there is at that moment goes, with the host token, in // one locked step, or Disconnect fails; then its device is revoked. var old store.EquipoLink var oldSec deviceSecrets err := a.changeLink(me.ID, func() (e error) { if old, oldSec, _, e = a.askLink(ctx, me); e != nil { return e } return store.DisconnectEquipo(ctx, a.db, me.ID) }) if err != nil { a.fail(w, err) return } a.revokeDisplaced(ctx, old, oldSec, "") http.Redirect(w, r, "/settings", http.StatusSeeOther) } // registerHost gives Equipo a new host token for the member, with the // bearer token of their device dev: where Base's operations live (Base's // own origin) and what the Assistant presents to call them for this // member. The new token replaces the member's last one, which names // nobody from then on. It mints nothing unless dev is still the member's // connected device: a read that outlived a Disconnect or a new Connect // leaves no token behind. func (a *app) registerHost(ctx context.Context, me store.Member, dev, token string) error { host, ok, err := store.MintHostTokenFor(ctx, a.db, me.ID, dev) if err != nil || !ok { return err } if err := a.ask.client.RegisterHost(ctx, token, a.cfg.Origin, host); err != nil { return err } return store.MarkHostRegistered(ctx, a.db, me.ID) } // hostFor registers the host of the member's device dev with Equipo: // always when fresh (a connection that just became ready), else only if // Equipo does not hold their current token yet. It holds the member's // lock (lockMember), so registrations, Connect, Disconnect and a lost // bearer happen one at a time for each member, and two reads cannot // leave Equipo holding a token Base has replaced. A failure is logged // (never a token) and tried again on the next read: it neither breaks // the chat nor disconnects anyone. func (a *app) hostFor(ctx context.Context, me store.Member, dev, token string, fresh bool) { ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), storeTimeout) defer cancel() a.zoneFor(ctx, me, token, fresh) defer a.lockMember(me.ID)() if !fresh { done, err := store.HostRegistered(ctx, a.db, me.ID) if err != nil { a.logger.Error("ask: host registered", "err", err) return } if done { return } } if err := a.registerHost(ctx, me, dev, token); err != nil { a.logger.Warn("ask: register host", "err", err) } } // zoneWait bounds one time-zone call; zoneRetry is how long Base waits // after one that failed (5xx, 429, no answer in time) before trying again. const ( zoneWait = 5 * time.Second zoneRetry = time.Hour ) // zoneTold is where telling Equipo a member's time zone has got to: a // call in flight (busy; again if a new connection came meanwhile), an // answer that settles it (any 2xx, or a 4xx but 404 and 429: the same call // would get the same answer), or a failure, after which it waits until // retryAt. A 404 is an Equipo without the route yet, which may get it // (deployed after Base), so it waits like a failure. type zoneTold struct { busy, again, settled bool retryAt time.Time } // zoneFor tells Equipo the member's time zone, the team's (BASE_TIMEZONE), // for the times the Assistant writes for them ("Paused until 21:00"), // only if they have none of their own yet (SetTimeZone): once each time // Base starts, which is when BASE_TIMEZONE can change, and again on a new // connection (fresh). It never holds up the page or the member's lock: // the call runs on its own, bounded by zoneWait. After a failure (5xx, // 429, 404, no answer in time) it is tried again no sooner than zoneRetry. func (a *app) zoneFor(parent context.Context, me store.Member, token string, fresh bool) { if a.ask.zone == "" { return } a.ask.zoneMu.Lock() z := a.ask.zones[me.ID] if z == nil { z = &zoneTold{} a.ask.zones[me.ID] = z } switch { case fresh && z.busy: z.again = true case fresh: z.settled, z.retryAt = false, time.Time{} } if z.busy || z.settled || time.Now().Before(z.retryAt) { a.ask.zoneMu.Unlock() return } z.busy = true a.ask.zoneMu.Unlock() caps := equipo.CapabilitiesFuncOf(parent) go func() { ctx, cancel := context.WithTimeout(equipo.WithCapabilitiesFunc(context.Background(), caps), zoneWait) defer cancel() err := a.ask.client.SetTimeZone(ctx, token, a.ask.zone) var e *equipo.Error refused := errors.As(err, &e) settled := err == nil || refused && e.Status >= 400 && e.Status < 500 && e.Status != http.StatusTooManyRequests && e.Status != http.StatusNotFound switch { case refused && e.Status == http.StatusNotFound: // An Equipo from before the route: expected, not a fault. a.logger.Info("ask: time zone: Equipo has no such route yet", "err", err) case err != nil: a.logger.Warn("ask: time zone", "err", err, "settled", settled) } a.ask.zoneMu.Lock() defer a.ask.zoneMu.Unlock() z.busy, z.settled = false, settled && !z.again z.again = false if !settled { z.retryAt = time.Now().Add(zoneRetry) } }() } // memberConn is a member's lock, held while their connection changes or // their host is registered, and their connection's generation, which every // change to their link moves on (changeLink). The lock is not reentrant: // nothing holding it calls hostFor. type memberConn struct { mu sync.Mutex gen uint64 } func (a *app) memberConn(id string) *memberConn { c, _ := a.ask.hosts.LoadOrStore(id, &memberConn{}) return c.(*memberConn) } // lockMember takes the member's lock and returns its release. func (a *app) lockMember(id string) func() { c := a.memberConn(id) c.mu.Lock() return c.mu.Unlock } // changeLink runs change, which changes the member's link (Connect, its // approval or end, Disconnect, Ask set up with Oficina ID), under their // lock, and moves their connection's generation on: a set-up with Oficina // ID that began before it then yields (askOficina). Equipo refusing a key // (askLost) is not a change of this kind: a set-up may replace that key. func (a *app) changeLink(id string, change func() error) error { c := a.memberConn(id) c.mu.Lock() defer c.mu.Unlock() c.gen++ return change() } // linkGenDisconnected is the member's connection generation now, and // whether they have disconnected Ask, read together under their lock: // Disconnect sets the one and moves the other in one locked step. func (a *app) linkGenDisconnected(ctx context.Context, id string) (uint64, bool, error) { c := a.memberConn(id) c.mu.Lock() defer c.mu.Unlock() disconnected, err := store.AskDisconnected(ctx, a.db, id) return c.gen, disconnected, err } func (a *app) renderConnect(w http.ResponseWriter, r *http.Request, status int, v connectView) { v.Name, v.Label, v.Back = a.cfg.Name, a.ask.label, askNext[v.Next] w.Header().Set("Cache-Control", "no-store") if err := a.pages.PageTheme(w, status, "ask_connect", v, themeOf(r)); err != nil { a.fail(w, err) } } func (a *app) fail(w http.ResponseWriter, err error) { a.logger.Error("ask", "err", err) http.Error(w, "unavailable", http.StatusServiceUnavailable) }