| 1 | package web |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/ed25519" |
| 6 | "crypto/rand" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "sync" |
| 11 | "time" |
| 12 | |
| 13 | jsonv2 "github.com/go-json-experiment/json" |
| 14 | "github.com/go-json-experiment/json/jsontext" |
| 15 | |
| 16 | "amadan.net/oficina/home/connect" |
| 17 | "amadan.net/rastrillo/rastrillo/sessions" |
| 18 | |
| 19 | "amadan.net/oficina/base/internal/equipo" |
| 20 | "amadan.net/oficina/base/internal/store" |
| 21 | ) |
| 22 | |
| 23 | // Ask set up with Oficina ID, for the native app: the app fetches an |
| 24 | // assertion addressed to Equipo and posts it here, and Base completes |
| 25 | // Equipo's own native sign-in for the member (equipo.NativeExchange, then |
| 26 | // RegisterNative). The key it gets is the same kind the code flow gets and |
| 27 | // is kept the same way, so the relay cannot tell the two apart. It ends with |
| 28 | // the Equipo session it was registered with, seven days on (or when the |
| 29 | // person signs out of Equipo, is relinked or leaves the roster), so Base |
| 30 | // keeps that session's cookie sealed beside the key, never signs it out, |
| 31 | // and tells the app when to send a fresh assertion (renewAfter). |
| 32 | |
| 33 | // askOficinaPath is where the native app posts the assertion. |
| 34 | const askOficinaPath = "/api/v1/ask/oficina" |
| 35 | |
| 36 | // viaOficina marks a key set up with Oficina ID (deviceSecrets.Via). |
| 37 | const viaOficina = "oficina" |
| 38 | |
| 39 | // renewBefore is how long before the Equipo session ends the app should |
| 40 | // renew: five days after a seven-day session was minted. |
| 41 | const renewBefore = 2 * 24 * time.Hour |
| 42 | |
| 43 | // askOficinaTimeout bounds the whole set-up, which carries on if the app |
| 44 | // goes away: Equipo may already have made the device. |
| 45 | const askOficinaTimeout = 45 * time.Second |
| 46 | |
| 47 | // askNotLinked is the answer for a person Equipo has not linked to their |
| 48 | // Oficina ID. It is this route's alone: /ask/state never says it. |
| 49 | const askNotLinked = "not_linked" |
| 50 | |
| 51 | // askSuperseded is the answer for a set-up that something else overtook |
| 52 | // while Equipo answered (Disconnect, or a connection from the web): it |
| 53 | // saved nothing, and revoked the device it made. |
| 54 | const askSuperseded = "superseded" |
| 55 | |
| 56 | // askDisconnected is the answer to an automatic set-up after the member |
| 57 | // disconnected Ask (store.Member.AskDisconnected): nothing was done. |
| 58 | const askDisconnected = "disconnected" |
| 59 | |
| 60 | // renewAfter is when the app should send a fresh assertion for link l, |
| 61 | // zero for a key from the code flow. |
| 62 | func renewAfter(l store.EquipoLink, sec deviceSecrets) time.Time { |
| 63 | if sec.Via != viaOficina { |
| 64 | return time.Time{} |
| 65 | } |
| 66 | return l.ExpiresAt.Add(-renewBefore).UTC() |
| 67 | } |
| 68 | |
| 69 | // askOficinaLock is the member's lock for setting Ask up with Oficina ID: |
| 70 | // two posts for the same person run one at a time. It is not lockMember, |
| 71 | // which is never held across a call to Equipo: the set-up takes that only |
| 72 | // to compare its connection's generation and save (saveOficinaLink). |
| 73 | func (a *app) askOficinaLock(id string) func() { |
| 74 | mu, _ := a.ask.oficina.LoadOrStore(id, &sync.Mutex{}) |
| 75 | mu.(*sync.Mutex).Lock() |
| 76 | return mu.(*sync.Mutex).Unlock |
| 77 | } |
| 78 | |
| 79 | // askOficina is POST /api/v1/ask/oficina, {assertion, verifier}, from a |
| 80 | // native session only (docs/api/base-native-v1.md). |
| 81 | func (a *app) askOficina(w http.ResponseWriter, r *http.Request) { |
| 82 | me, _ := CurrentMember(r) |
| 83 | if s, ok := sessions.Current(r); !ok || s.Method != connect.NativeMethod { |
| 84 | writeJSON(w, http.StatusForbidden, map[string]string{"state": "forbidden"}) |
| 85 | return |
| 86 | } |
| 87 | in, ok := readAskOficina(w, r) |
| 88 | if !ok { |
| 89 | writeJSON(w, http.StatusBadRequest, map[string]string{"state": "invalid"}) |
| 90 | return |
| 91 | } |
| 92 | defer a.askOficinaLock(me.ID)() |
| 93 | ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), askOficinaTimeout) |
| 94 | defer cancel() |
| 95 | |
| 96 | // The connection as the set-up begins, and whether the member has |
| 97 | // disconnected Ask, read together. Anything that changes it while |
| 98 | // Equipo answers (Disconnect, the web's Connect or its approval) wins: |
| 99 | // the set-up then saves nothing. |
| 100 | gen, disconnected, err := a.linkGenDisconnected(ctx, me.ID) |
| 101 | if err != nil { |
| 102 | a.logger.Error("ask oficina: disconnected", "err", err) |
| 103 | writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable}) |
| 104 | return |
| 105 | } |
| 106 | if in.Auto && disconnected { |
| 107 | writeJSON(w, http.StatusConflict, map[string]string{"state": askDisconnected}) |
| 108 | return |
| 109 | } |
| 110 | sess, err := a.ask.client.NativeExchange(ctx, in.Assertion, in.Verifier) |
| 111 | if err != nil { |
| 112 | a.askOficinaRefused(w, "exchange", err) |
| 113 | return |
| 114 | } |
| 115 | pub, key, err := ed25519.GenerateKey(rand.Reader) |
| 116 | if err != nil { |
| 117 | a.fail(w, err) |
| 118 | return |
| 119 | } |
| 120 | cred, err := a.ask.client.RegisterNative(ctx, sess, pub, a.ask.label) |
| 121 | if err != nil { |
| 122 | a.askOficinaRefused(w, "device", err) |
| 123 | return |
| 124 | } |
| 125 | exp := cred.ExpiresAt |
| 126 | if exp.IsZero() || exp.After(sess.ExpiresAt) { |
| 127 | exp = sess.ExpiresAt |
| 128 | } |
| 129 | sealed, err := a.sealSecrets(me.ID, deviceSecrets{Seed: key.Seed(), Token: cred.Token, Via: viaOficina, |
| 130 | SessionName: sess.Name, SessionValue: sess.Value}) |
| 131 | l := store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(), State: store.EquipoConnected, |
| 132 | DeviceID: cred.ID, Sealed: sealed, ExpiresAt: exp, Revision: cred.Revision} |
| 133 | var superseded bool |
| 134 | var old store.EquipoLink |
| 135 | var oldSec deviceSecrets |
| 136 | if err == nil { |
| 137 | superseded, old, oldSec, err = a.saveOficinaLink(ctx, me, gen, l, !in.Auto) |
| 138 | } |
| 139 | if err != nil || superseded { |
| 140 | // Nothing was saved: the device made for it goes. |
| 141 | a.revoke(ctx, l, deviceSecrets{Token: cred.Token}) |
| 142 | switch { |
| 143 | case superseded: |
| 144 | writeJSON(w, http.StatusConflict, map[string]string{"state": askSuperseded}) |
| 145 | return |
| 146 | case errors.Is(err, store.ErrAskDisconnected): |
| 147 | writeJSON(w, http.StatusConflict, map[string]string{"state": askDisconnected}) |
| 148 | return |
| 149 | } |
| 150 | a.logger.Error("ask oficina: store", "device", cred.ID, "err", err) |
| 151 | writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable}) |
| 152 | return |
| 153 | } |
| 154 | // The key it replaced is over, ready or not: revoke it in Equipo, as |
| 155 | // Connect does. A key Equipo already refused refuses this too. |
| 156 | a.revokeDisplaced(ctx, old, oldSec, cred.ID) |
| 157 | a.hostFor(ctx, me, cred.ID, cred.Token, true) |
| 158 | writeJSON(w, http.StatusOK, map[string]string{"state": askReady, "renew_after": renewAfter(l, deviceSecrets{Via: viaOficina}).Format(time.RFC3339)}) |
| 159 | } |
| 160 | |
| 161 | // saveOficinaLink stores l as the member's link, unless their connection |
| 162 | // has changed since generation gen (superseded, and nothing is stored). It |
| 163 | // answers the link it replaced, read under the member's lock as it saves. |
| 164 | // Saving forgets the old host token with it. An explicit save clears the |
| 165 | // member's Disconnect; an automatic one is refused while it stands |
| 166 | // (store.ErrAskDisconnected), checked again in the save's own transaction. |
| 167 | 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) { |
| 168 | c := a.memberConn(me.ID) |
| 169 | c.mu.Lock() |
| 170 | defer c.mu.Unlock() |
| 171 | if c.gen != gen { |
| 172 | return true, old, oldSec, nil |
| 173 | } |
| 174 | if old, oldSec, _, err = a.askLink(ctx, me); err != nil { |
| 175 | return false, store.EquipoLink{}, deviceSecrets{}, err |
| 176 | } |
| 177 | if err = store.SaveConnectedEquipoLink(ctx, a.db, l, explicit); err != nil { |
| 178 | return false, store.EquipoLink{}, deviceSecrets{}, err |
| 179 | } |
| 180 | c.gen++ |
| 181 | return false, old, oldSec, nil |
| 182 | } |
| 183 | |
| 184 | // askOficinaRefused answers for a step of Equipo's sign-in that failed, |
| 185 | // having stored nothing. The app never hears a 401 here: that would read |
| 186 | // as Base's own session ending. |
| 187 | func (a *app) askOficinaRefused(w http.ResponseWriter, step string, err error) { |
| 188 | var e *equipo.Error |
| 189 | switch { |
| 190 | case step == "exchange" && errors.Is(err, equipo.ErrNotLinked): |
| 191 | writeJSON(w, http.StatusConflict, map[string]string{"state": askNotLinked}) |
| 192 | case step == "exchange" && errors.Is(err, equipo.ErrAssertionFailed): |
| 193 | writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": "failed"}) |
| 194 | case step == "exchange" && errors.Is(err, equipo.ErrAssertionInvalid): |
| 195 | writeJSON(w, http.StatusBadRequest, map[string]string{"state": "invalid"}) |
| 196 | default: |
| 197 | if errors.As(err, &e) { |
| 198 | a.logger.Warn("ask oficina: equipo refused", "step", step, "status", e.Status, "code", e.Code) |
| 199 | } else { |
| 200 | a.logger.Warn("ask oficina: equipo", "step", step, "err", err) |
| 201 | } |
| 202 | writeJSON(w, http.StatusBadGateway, map[string]string{"state": askUnavailable}) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // askOficinaIn is POST /api/v1/ask/oficina's body. |
| 207 | type askOficinaIn struct { |
| 208 | Assertion, Verifier string |
| 209 | // Auto is a set-up the app starts by itself (after sign-in, or to |
| 210 | // renew), which yields to the member's Disconnect; without it the |
| 211 | // person asked, and it connects Ask again. |
| 212 | Auto bool |
| 213 | } |
| 214 | |
| 215 | // readAskOficina reads the body strictly: one JSON object with exactly the |
| 216 | // names assertion, verifier and, optionally, auto, each once and spelt so; |
| 217 | // auto only true or false (never null, which a client might send for "not |
| 218 | // set", and which must not read as the person asking). |
| 219 | func readAskOficina(w http.ResponseWriter, r *http.Request) (askOficinaIn, bool) { |
| 220 | if !isJSONBody(r) { |
| 221 | return askOficinaIn{}, false |
| 222 | } |
| 223 | raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 16<<10)) |
| 224 | if err != nil { |
| 225 | return askOficinaIn{}, false |
| 226 | } |
| 227 | var in struct { |
| 228 | Assertion string `json:"assertion"` |
| 229 | Verifier string `json:"verifier"` |
| 230 | Auto jsontext.Value `json:"auto"` |
| 231 | } |
| 232 | if jsonv2.Unmarshal(raw, &in, jsonv2.RejectUnknownMembers(true)) != nil || |
| 233 | in.Assertion == "" || len(in.Assertion) > 8192 || in.Verifier == "" || len(in.Verifier) > 256 { |
| 234 | return askOficinaIn{}, false |
| 235 | } |
| 236 | out := askOficinaIn{Assertion: in.Assertion, Verifier: in.Verifier} |
| 237 | switch string(in.Auto) { |
| 238 | case "": |
| 239 | case "true": |
| 240 | out.Auto = true |
| 241 | case "false": |
| 242 | default: |
| 243 | return askOficinaIn{}, false |
| 244 | } |
| 245 | return out, true |
| 246 | } |
| 247 | |