| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "crypto/subtle" |
| 7 | "database/sql" |
| 8 | "encoding/base64" |
| 9 | "encoding/hex" |
| 10 | "errors" |
| 11 | "net/http" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/rastrillo/rastrillo/assertion" |
| 15 | "amadan.net/rastrillo/rastrillo/sessions" |
| 16 | ) |
| 17 | |
| 18 | // signoutAllPath is "Sign out all devices" (§10): the slice-A stand-in for |
| 19 | // A2's Devices page. Paul, 2026-11-14: it ends every native grant AND every |
| 20 | // Home browser session the person has, on id.* and on the directory, |
| 21 | // including the browser pressing the button. id.* ends its half in one |
| 22 | // transaction; the directory ends its half in one transaction when this |
| 23 | // browser carries the signed receipt across (signedOutAllPath). Both record |
| 24 | // a per-person mark, and assertions issued at or before it are refused. The |
| 25 | // residual (the hop between the two stores, and team instances that do not |
| 26 | // read the mark yet) is in the branch description. |
| 27 | const signoutAllPath = "/devices/sign-out-all" |
| 28 | |
| 29 | // signedOutAllPath is the directory's receiver for that receipt. |
| 30 | const signedOutAllPath = "/auth/signed-out-all" |
| 31 | |
| 32 | // signoutAllNonceContext domain-separates the receipt's nonce. The receipt |
| 33 | // is an ordinary v1 assertion for the directory audience whose nonce Home |
| 34 | // derives from its own jti, so it can match no browser's pending sign-in |
| 35 | // and no native verifier, and the receiver accepts no other nonce. |
| 36 | const signoutAllNonceContext = "oficina-id/signout-all/v1" |
| 37 | |
| 38 | func signoutAllNonce(jti string) string { |
| 39 | h := sha256.New() |
| 40 | h.Write([]byte(signoutAllNonceContext)) |
| 41 | h.Write([]byte{0}) |
| 42 | h.Write([]byte(jti)) |
| 43 | return base64.RawURLEncoding.EncodeToString(h.Sum(nil)[:16]) |
| 44 | } |
| 45 | |
| 46 | func (a *App) handleSignoutAllPage(w http.ResponseWriter, r *http.Request) { |
| 47 | a.render(w, r, http.StatusOK, "id_signout_all.html", nil) |
| 48 | } |
| 49 | |
| 50 | // handleSignoutAll is behind RequireFresh and csrf.Protect, and re-reads the |
| 51 | // live session inside the writer transaction, as recovery-code generation |
| 52 | // does, so a session revoked a moment ago cannot end anybody's devices. |
| 53 | func (a *App) handleSignoutAll(w http.ResponseWriter, r *http.Request) { |
| 54 | w.Header().Set("Cache-Control", "no-store") |
| 55 | tx, now, err := a.idTransaction(r.Context()) |
| 56 | if err != nil { |
| 57 | a.serverError(w, r) |
| 58 | return |
| 59 | } |
| 60 | defer tx.Rollback() |
| 61 | live, _, err := a.idSession(tx, r, now) |
| 62 | if err != nil || !idFreshSession(live, enrolFreshness, time.Unix(now, 0)) { |
| 63 | a.signinFailed(w, r) |
| 64 | return |
| 65 | } |
| 66 | authTime := live.AuthTime |
| 67 | if authTime.IsZero() { |
| 68 | authTime = live.At |
| 69 | } |
| 70 | if err = endGrants(tx, live.Subject, "all_devices", now); err != nil { |
| 71 | a.serverError(w, r) |
| 72 | return |
| 73 | } |
| 74 | // Every id.* session of this person, this browser's included, in the |
| 75 | // same transaction as the grants, along with the half-finished sign-ins |
| 76 | // that would otherwise mint a new one. |
| 77 | for _, q := range []string{ |
| 78 | "DELETE FROM sessions WHERE subject=?", |
| 79 | "DELETE FROM passkey_pending WHERE subject=?", |
| 80 | "DELETE FROM home_id_native_pending WHERE person_ref=?", |
| 81 | } { |
| 82 | if _, err = tx.Exec(q, live.Subject); err != nil { |
| 83 | a.serverError(w, r) |
| 84 | return |
| 85 | } |
| 86 | } |
| 87 | if err = markSignedOutAll(tx, "home_id_signed_out_all", live.Subject, now); err != nil { |
| 88 | a.serverError(w, r) |
| 89 | return |
| 90 | } |
| 91 | id, err := assertion.RandomID() |
| 92 | if err != nil { |
| 93 | a.serverError(w, r) |
| 94 | return |
| 95 | } |
| 96 | receipt, err := assertion.Sign(a.runtime.signer, assertion.Claims{ |
| 97 | Version: 1, Issuer: a.origins.Credential, Audience: a.origins.Directory, Subject: live.Subject, |
| 98 | KeyID: a.runtime.keyID, ID: id, Nonce: signoutAllNonce(id), |
| 99 | IssuedAt: now, ExpiresAt: now + 120, AuthTime: min(authTime.Unix(), now), |
| 100 | }) |
| 101 | if err != nil { |
| 102 | a.serverError(w, r) |
| 103 | return |
| 104 | } |
| 105 | if tx.Commit() != nil { |
| 106 | a.serverError(w, r) |
| 107 | return |
| 108 | } |
| 109 | idCookie(w, a.sessions.CookieName(), "", -1) |
| 110 | // The hop to the directory: the same self-submitting form, transport and |
| 111 | // referrer policy as the assertion handoff. |
| 112 | w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") |
| 113 | a.render(w, r, http.StatusOK, "id_signout_all_hop.html", map[string]any{"Action": a.origins.Directory + signedOutAllPath, "Token": receipt}) |
| 114 | } |
| 115 | |
| 116 | // markSignedOutAll records the press, keeping the later of two, and prunes |
| 117 | // marks too old to matter: no assertion lives longer than 120 seconds. |
| 118 | func markSignedOutAll(tx *sql.Tx, table, person string, at int64) error { |
| 119 | if _, err := tx.Exec("DELETE FROM "+table+" WHERE at<?", at-signedOutAllKeep); err != nil { |
| 120 | return errIDProof |
| 121 | } |
| 122 | if _, err := tx.Exec("INSERT INTO "+table+"(person_ref,at) VALUES(?,?) ON CONFLICT(person_ref) DO UPDATE SET at=MAX(at,excluded.at)", person, at); err != nil { |
| 123 | return errIDProof |
| 124 | } |
| 125 | return nil |
| 126 | } |
| 127 | |
| 128 | const signedOutAllKeep = 300 |
| 129 | |
| 130 | type rowQueryer interface { |
| 131 | QueryRowContext(context.Context, string, ...any) *sql.Row |
| 132 | } |
| 133 | |
| 134 | // signedOutBefore reports whether something issued at iat predates the |
| 135 | // person's latest "Sign out all devices" (iat at or before the mark). |
| 136 | func signedOutBefore(ctx context.Context, q rowQueryer, table, person string, iat int64) (bool, error) { |
| 137 | var at int64 |
| 138 | err := q.QueryRowContext(ctx, "SELECT at FROM "+table+" WHERE person_ref=?", person).Scan(&at) |
| 139 | if errors.Is(err, sql.ErrNoRows) { |
| 140 | return false, nil |
| 141 | } |
| 142 | if err != nil { |
| 143 | return false, err |
| 144 | } |
| 145 | return iat <= at, nil |
| 146 | } |
| 147 | |
| 148 | // errSignedOutAll refuses a directory sign-in from an assertion issued |
| 149 | // before the person pressed "Sign out all devices". |
| 150 | var errSignedOutAll = errors.New("home: assertion predates sign out all devices") |
| 151 | |
| 152 | // directorySigninAllowed is the directory's browser-finish check. |
| 153 | func (a *App) directorySigninAllowed(ctx context.Context, c assertion.Claims) error { |
| 154 | before, err := signedOutBefore(ctx, a.db.Writer(), "home_directory_signed_out_all", c.Subject, c.IssuedAt) |
| 155 | if err != nil { |
| 156 | return err |
| 157 | } |
| 158 | if before { |
| 159 | return errSignedOutAll |
| 160 | } |
| 161 | return nil |
| 162 | } |
| 163 | |
| 164 | // handleSignedOutAll is the directory's half: POST /auth/signed-out-all |
| 165 | // {assertion}, from the credential origin only. It ends every directory |
| 166 | // session the person holds, browser and native, in one transaction with |
| 167 | // the receipt's jti, then lands this browser on the signed-out page. |
| 168 | func (a *App) handleSignedOutAll(w http.ResponseWriter, r *http.Request) { |
| 169 | w.Header().Set("Cache-Control", "no-store") |
| 170 | failed := func(status int) { |
| 171 | a.render(w, r, status, "directory_signout_all_failed.html", map[string]any{"Again": a.origins.Credential + signoutAllPath}) |
| 172 | } |
| 173 | if origins := r.Header.Values("Origin"); len(origins) != 1 || origins[0] != a.origins.Credential { |
| 174 | failed(http.StatusForbidden) |
| 175 | return |
| 176 | } |
| 177 | r.Body = http.MaxBytesReader(w, r.Body, 16<<10) |
| 178 | if r.ParseForm() != nil || len(r.PostForm["assertion"]) != 1 || len(r.PostForm) != 1 { |
| 179 | failed(http.StatusBadRequest) |
| 180 | return |
| 181 | } |
| 182 | claims, err := a.handoffStore.Verify(r.PostForm.Get("assertion"), time.Now()) |
| 183 | if err != nil || subtle.ConstantTimeCompare([]byte(claims.Nonce), []byte(signoutAllNonce(claims.ID))) != 1 || !ValidPersonRef(claims.Subject) { |
| 184 | failed(http.StatusForbidden) |
| 185 | return |
| 186 | } |
| 187 | tx, err := a.db.Writer().BeginTx(r.Context(), nil) |
| 188 | if err != nil { |
| 189 | failed(http.StatusServiceUnavailable) |
| 190 | return |
| 191 | } |
| 192 | defer tx.Rollback() |
| 193 | // Reserved here rather than through handoff.Store.Reserve, on purpose: |
| 194 | // the receipt is one-shot, so its jti, the sessions it ends and the mark |
| 195 | // commit together. The key is handoff's jtiHash, SHA-256(iss ‖ 0 ‖ jti), |
| 196 | // so the one ledger still refuses it at every other door. |
| 197 | jti := sha256.Sum256([]byte(claims.Issuer + "\x00" + claims.ID)) |
| 198 | res, err := tx.Exec("INSERT INTO oficina_handoff_replay(jti_hash,expires_at) VALUES(?,?) ON CONFLICT DO NOTHING", hex.EncodeToString(jti[:]), claims.ExpiresAt) |
| 199 | if err != nil { |
| 200 | failed(http.StatusServiceUnavailable) |
| 201 | return |
| 202 | } |
| 203 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 204 | failed(http.StatusForbidden) |
| 205 | return |
| 206 | } |
| 207 | // Whose session does this browser hold? Its cookie is cleared only if it |
| 208 | // is the receipt's person's, which the delete below ends anyway. |
| 209 | mine := false |
| 210 | if token := cookieValue(r, a.sessions.CookieName()); token != "" { |
| 211 | var subject string |
| 212 | if tx.QueryRow("SELECT subject FROM sessions WHERE token_hash=?", sessions.HashToken(token)).Scan(&subject) == nil { |
| 213 | mine = subject == claims.Subject |
| 214 | } |
| 215 | } |
| 216 | if _, err = tx.Exec("DELETE FROM sessions WHERE subject=?", claims.Subject); err != nil { |
| 217 | failed(http.StatusServiceUnavailable) |
| 218 | return |
| 219 | } |
| 220 | if markSignedOutAll(tx, "home_directory_signed_out_all", claims.Subject, claims.IssuedAt) != nil || tx.Commit() != nil { |
| 221 | failed(http.StatusServiceUnavailable) |
| 222 | return |
| 223 | } |
| 224 | if mine { |
| 225 | idCookie(w, a.sessions.CookieName(), "", -1) |
| 226 | } |
| 227 | idCookie(w, "__Host-oficina-signed-out-all", "1", 300) |
| 228 | http.Redirect(w, r, "/signed-out", http.StatusSeeOther) |
| 229 | } |
| 230 | |
| 231 | // afterMarkCheck is a test seam: it runs between a sign-in's first mark |
| 232 | // check and the write that follows, so a test can commit a receipt in that |
| 233 | // gap. It does nothing in production. |
| 234 | var afterMarkCheck = func() {} |
| 235 | |
| 236 | // finishWriter carries one fact from the directory's Complete to its Fail |
| 237 | // hook through handoff.Consumer.Finish: the sign-in was refused because the |
| 238 | // person pressed "Sign out all devices". |
| 239 | type finishWriter struct { |
| 240 | http.ResponseWriter |
| 241 | signedOutAll bool |
| 242 | } |
| 243 | |
| 244 | func markSignedOutAllFinish(w http.ResponseWriter) { |
| 245 | if fw, ok := w.(*finishWriter); ok { |
| 246 | fw.signedOutAll = true |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | func signedOutAllFinish(w http.ResponseWriter) bool { |
| 251 | fw, ok := w.(*finishWriter) |
| 252 | return ok && fw.signedOutAll |
| 253 | } |
| 254 | |
| 255 | // undoSignIn deletes the session sessions.SignIn just minted, found by the |
| 256 | // cookie it set on this response, and replaces that cookie with a clearing |
| 257 | // one. Nothing has been sent yet: handoff's Finish writes only after |
| 258 | // Complete returns. |
| 259 | func (a *App) undoSignIn(w http.ResponseWriter, r *http.Request) { |
| 260 | name := a.sessions.CookieName() |
| 261 | h := w.Header() |
| 262 | kept := h.Values("Set-Cookie")[:0:0] |
| 263 | for _, line := range h.Values("Set-Cookie") { |
| 264 | c, err := http.ParseSetCookie(line) |
| 265 | if err == nil && c.Name == name && c.Value != "" { |
| 266 | if _, err := a.db.Writer().ExecContext(r.Context(), "DELETE FROM sessions WHERE token_hash=?", sessions.HashToken(c.Value)); err != nil { |
| 267 | a.logger.Warn("undoing a refused directory sign-in failed") |
| 268 | } |
| 269 | continue |
| 270 | } |
| 271 | kept = append(kept, line) |
| 272 | } |
| 273 | h.Del("Set-Cookie") |
| 274 | for _, line := range kept { |
| 275 | h.Add("Set-Cookie", line) |
| 276 | } |
| 277 | idCookie(w, name, "", -1) |
| 278 | } |
| 279 | |