package web import ( "context" "crypto/ed25519" "crypto/rand" "errors" "io" "net/http" "sync" "time" jsonv2 "github.com/go-json-experiment/json" "github.com/go-json-experiment/json/jsontext" "amadan.net/oficina/home/connect" "amadan.net/rastrillo/rastrillo/sessions" "amadan.net/oficina/base/internal/equipo" "amadan.net/oficina/base/internal/store" ) // Ask set up with Oficina ID, for the native app: the app fetches an // assertion addressed to Equipo and posts it here, and Base completes // Equipo's own native sign-in for the member (equipo.NativeExchange, then // RegisterNative). The key it gets is the same kind the code flow gets and // is kept the same way, so the relay cannot tell the two apart. It ends with // the Equipo session it was registered with, seven days on (or when the // person signs out of Equipo, is relinked or leaves the roster), so Base // keeps that session's cookie sealed beside the key, never signs it out, // and tells the app when to send a fresh assertion (renewAfter). // askOficinaPath is where the native app posts the assertion. const askOficinaPath = "/api/v1/ask/oficina" // viaOficina marks a key set up with Oficina ID (deviceSecrets.Via). const viaOficina = "oficina" // renewBefore is how long before the Equipo session ends the app should // renew: five days after a seven-day session was minted. const renewBefore = 2 * 24 * time.Hour // askOficinaTimeout bounds the whole set-up, which carries on if the app // goes away: Equipo may already have made the device. const askOficinaTimeout = 45 * time.Second // askNotLinked is the answer for a person Equipo has not linked to their // Oficina ID. It is this route's alone: /ask/state never says it. const askNotLinked = "not_linked" // askSuperseded is the answer for a set-up that something else overtook // while Equipo answered (Disconnect, or a connection from the web): it // saved nothing, and revoked the device it made. const askSuperseded = "superseded" // askDisconnected is the answer to an automatic set-up after the member // disconnected Ask (store.Member.AskDisconnected): nothing was done. const askDisconnected = "disconnected" // renewAfter is when the app should send a fresh assertion for link l, // zero for a key from the code flow. func renewAfter(l store.EquipoLink, sec deviceSecrets) time.Time { if sec.Via != viaOficina { return time.Time{} } return l.ExpiresAt.Add(-renewBefore).UTC() } // askOficinaLock is the member's lock for setting Ask up with Oficina ID: // two posts for the same person run one at a time. It is not lockMember, // which is never held across a call to Equipo: the set-up takes that only // to compare its connection's generation and save (saveOficinaLink). func (a *app) askOficinaLock(id string) func() { mu, _ := a.ask.oficina.LoadOrStore(id, &sync.Mutex{}) mu.(*sync.Mutex).Lock() return mu.(*sync.Mutex).Unlock } // askOficina is POST /api/v1/ask/oficina, {assertion, verifier}, from a // native session only (docs/api/base-native-v1.md). func (a *app) askOficina(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) if s, ok := sessions.Current(r); !ok || s.Method != connect.NativeMethod { writeJSON(w, http.StatusForbidden, map[string]string{"state": "forbidden"}) return } in, ok := readAskOficina(w, r) if !ok { writeJSON(w, http.StatusBadRequest, map[string]string{"state": "invalid"}) return } defer a.askOficinaLock(me.ID)() ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), askOficinaTimeout) defer cancel() // The connection as the set-up begins, and whether the member has // disconnected Ask, read together. Anything that changes it while // Equipo answers (Disconnect, the web's Connect or its approval) wins: // the set-up then saves nothing. gen, disconnected, err := a.linkGenDisconnected(ctx, me.ID) if err != nil { a.logger.Error("ask oficina: disconnected", "err", err) writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable}) return } if in.Auto && disconnected { writeJSON(w, http.StatusConflict, map[string]string{"state": askDisconnected}) return } sess, err := a.ask.client.NativeExchange(ctx, in.Assertion, in.Verifier) if err != nil { a.askOficinaRefused(w, "exchange", err) return } pub, key, err := ed25519.GenerateKey(rand.Reader) if err != nil { a.fail(w, err) return } cred, err := a.ask.client.RegisterNative(ctx, sess, pub, a.ask.label) if err != nil { a.askOficinaRefused(w, "device", err) return } exp := cred.ExpiresAt if exp.IsZero() || exp.After(sess.ExpiresAt) { exp = sess.ExpiresAt } sealed, err := a.sealSecrets(me.ID, deviceSecrets{Seed: key.Seed(), Token: cred.Token, Via: viaOficina, SessionName: sess.Name, SessionValue: sess.Value}) l := store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(), State: store.EquipoConnected, DeviceID: cred.ID, Sealed: sealed, ExpiresAt: exp, Revision: cred.Revision} var superseded bool var old store.EquipoLink var oldSec deviceSecrets if err == nil { superseded, old, oldSec, err = a.saveOficinaLink(ctx, me, gen, l, !in.Auto) } if err != nil || superseded { // Nothing was saved: the device made for it goes. a.revoke(ctx, l, deviceSecrets{Token: cred.Token}) switch { case superseded: writeJSON(w, http.StatusConflict, map[string]string{"state": askSuperseded}) return case errors.Is(err, store.ErrAskDisconnected): writeJSON(w, http.StatusConflict, map[string]string{"state": askDisconnected}) return } a.logger.Error("ask oficina: store", "device", cred.ID, "err", err) writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable}) return } // The key it replaced is over, ready or not: revoke it in Equipo, as // Connect does. A key Equipo already refused refuses this too. a.revokeDisplaced(ctx, old, oldSec, cred.ID) a.hostFor(ctx, me, cred.ID, cred.Token, true) writeJSON(w, http.StatusOK, map[string]string{"state": askReady, "renew_after": renewAfter(l, deviceSecrets{Via: viaOficina}).Format(time.RFC3339)}) } // saveOficinaLink stores l as the member's link, unless their connection // has changed since generation gen (superseded, and nothing is stored). It // answers the link it replaced, read under the member's lock as it saves. // Saving forgets the old host token with it. An explicit save clears the // member's Disconnect; an automatic one is refused while it stands // (store.ErrAskDisconnected), checked again in the save's own transaction. func (a *app) saveOficinaLink(ctx context.Context, me store.Member, gen uint64, l store.EquipoLink, explicit bool) (superseded bool, old store.EquipoLink, oldSec deviceSecrets, err error) { c := a.memberConn(me.ID) c.mu.Lock() defer c.mu.Unlock() if c.gen != gen { return true, old, oldSec, nil } if old, oldSec, _, err = a.askLink(ctx, me); err != nil { return false, store.EquipoLink{}, deviceSecrets{}, err } if err = store.SaveConnectedEquipoLink(ctx, a.db, l, explicit); err != nil { return false, store.EquipoLink{}, deviceSecrets{}, err } c.gen++ return false, old, oldSec, nil } // askOficinaRefused answers for a step of Equipo's sign-in that failed, // having stored nothing. The app never hears a 401 here: that would read // as Base's own session ending. func (a *app) askOficinaRefused(w http.ResponseWriter, step string, err error) { var e *equipo.Error switch { case step == "exchange" && errors.Is(err, equipo.ErrNotLinked): writeJSON(w, http.StatusConflict, map[string]string{"state": askNotLinked}) case step == "exchange" && errors.Is(err, equipo.ErrAssertionFailed): writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": "failed"}) case step == "exchange" && errors.Is(err, equipo.ErrAssertionInvalid): writeJSON(w, http.StatusBadRequest, map[string]string{"state": "invalid"}) default: if errors.As(err, &e) { a.logger.Warn("ask oficina: equipo refused", "step", step, "status", e.Status, "code", e.Code) } else { a.logger.Warn("ask oficina: equipo", "step", step, "err", err) } writeJSON(w, http.StatusBadGateway, map[string]string{"state": askUnavailable}) } } // askOficinaIn is POST /api/v1/ask/oficina's body. type askOficinaIn struct { Assertion, Verifier string // Auto is a set-up the app starts by itself (after sign-in, or to // renew), which yields to the member's Disconnect; without it the // person asked, and it connects Ask again. Auto bool } // readAskOficina reads the body strictly: one JSON object with exactly the // names assertion, verifier and, optionally, auto, each once and spelt so; // auto only true or false (never null, which a client might send for "not // set", and which must not read as the person asking). func readAskOficina(w http.ResponseWriter, r *http.Request) (askOficinaIn, bool) { if !isJSONBody(r) { return askOficinaIn{}, false } raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 16<<10)) if err != nil { return askOficinaIn{}, false } var in struct { Assertion string `json:"assertion"` Verifier string `json:"verifier"` Auto jsontext.Value `json:"auto"` } if jsonv2.Unmarshal(raw, &in, jsonv2.RejectUnknownMembers(true)) != nil || in.Assertion == "" || len(in.Assertion) > 8192 || in.Verifier == "" || len(in.Verifier) > 256 { return askOficinaIn{}, false } out := askOficinaIn{Assertion: in.Assertion, Verifier: in.Verifier} switch string(in.Auto) { case "": case "true": out.Auto = true case "false": default: return askOficinaIn{}, false } return out, true }