| 1 | package door |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/equipo/identity" |
| 12 | "amadan.net/oficina/equipo/internal/equipo/oficinaid" |
| 13 | "amadan.net/rastrillo/rastrillo/auth" |
| 14 | "amadan.net/rastrillo/rastrillo/lastsignin" |
| 15 | "amadan.net/rastrillo/rastrillo/sessions" |
| 16 | "github.com/go-chi/chi/v5" |
| 17 | ) |
| 18 | |
| 19 | // Routes is the door's routes, around the app's own sign-in and its guard. |
| 20 | type Routes struct { |
| 21 | Look |
| 22 | Auth *auth.Auth |
| 23 | // DB holds the sessions table: the door ends a refused session there. |
| 24 | DB *sql.DB |
| 25 | Origin string |
| 26 | // Issuer is Oficina ID's origin; "" when Home is not configured, and |
| 27 | // the door is email only. |
| 28 | Issuer string |
| 29 | // Guard is the gate every signed-in page runs (requireMember). |
| 30 | Guard func(http.Handler) http.Handler |
| 31 | // Invited reports whether an address that is no member yet holds an |
| 32 | // invitation it may verify (the invitation's sign-in). |
| 33 | Invited func(context.Context, string) (bool, error) |
| 34 | // Active reports whether address is an active member: false, with no |
| 35 | // error, for one not on the team. |
| 36 | Active func(context.Context, string) (bool, error) |
| 37 | // Address is the Equipo address an Oficina ID session's subject is |
| 38 | // linked to, "" for none. Nil without Home. |
| 39 | Address func(context.Context, string) (string, error) |
| 40 | // Signout is the app's sign-out: rastrillo's standalone, oficinaid's |
| 41 | // with Home. |
| 42 | Signout http.HandlerFunc |
| 43 | } |
| 44 | |
| 45 | // Mount mounts the door's routes on r. With Home, oficinaid mounts |
| 46 | // /signed-out (it knows whether to offer Oficina ID's sign-out); without, |
| 47 | // the door does. /signin/local and /signin/oficina exist only with Home. |
| 48 | func (rt *Routes) Mount(r chi.Router) { |
| 49 | r.Get(SigninPath, rt.signin) |
| 50 | r.Post(rt.Forget, rt.forget) |
| 51 | if rt.Issuer == "" { |
| 52 | r.Post("/signout", rt.standaloneSignout) |
| 53 | r.Get(SignedOutPath, func(w http.ResponseWriter, r *http.Request) { rt.SignedOut(w, r, false, "") }) |
| 54 | return |
| 55 | } |
| 56 | r.Get(SigninLocalPath, rt.signinLocal) |
| 57 | r.Get(SigninOficinaPath, rt.signinOficina) |
| 58 | r.Post("/signout", rt.homeSignout) |
| 59 | } |
| 60 | |
| 61 | // doorStates are the query keys that name a state of the door itself, drawn |
| 62 | // even for a browser with a live session (connect's doorStates). |
| 63 | var doorStates = []string{"sent", "err", "force", "reauth", "continue"} |
| 64 | |
| 65 | func doorState(q url.Values) bool { |
| 66 | for _, key := range doorStates { |
| 67 | if q.Has(key) { |
| 68 | return true |
| 69 | } |
| 70 | } |
| 71 | return false |
| 72 | } |
| 73 | |
| 74 | // signin is GET /signin: the door, always, offering Oficina ID with Home. |
| 75 | // A browser already signed in and admitted goes straight to a safe |
| 76 | // return_to, or "/", unless the query names a state of the door. A plain |
| 77 | // /signin (no state, no return_to) forgets the page an earlier, abandoned |
| 78 | // sign-in kept, so it never wins over the one being made now. |
| 79 | func (rt *Routes) signin(w http.ResponseWriter, r *http.Request) { |
| 80 | q, err := url.ParseQuery(r.URL.RawQuery) |
| 81 | if err != nil { |
| 82 | http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) |
| 83 | return |
| 84 | } |
| 85 | if rt.Issuer != "" { |
| 86 | r = withOffer(r) |
| 87 | } |
| 88 | r, admitted := rt.admitted(w, r) |
| 89 | if admitted && !doorState(q) { |
| 90 | alreadySignedIn(w, r, q) |
| 91 | return |
| 92 | } |
| 93 | if !doorState(q) && !q.Has("return_to") && !choosing(r) { |
| 94 | rt.spendKept(w, r) |
| 95 | } |
| 96 | rt.Draw(rt.Auth, w, r, http.StatusOK, false) |
| 97 | } |
| 98 | |
| 99 | // signinLocal is GET /signin/local: the door with email as the one way in, |
| 100 | // where Equipo sends people Oficina ID cannot help (unlinked, failed) and a |
| 101 | // step-up. No signed-in shortcut: a step-up asks somebody signed in. |
| 102 | func (rt *Routes) signinLocal(w http.ResponseWriter, r *http.Request) { |
| 103 | r, _ = rt.admitted(w, r) |
| 104 | rt.Draw(rt.Auth, w, r, http.StatusOK, false) |
| 105 | } |
| 106 | |
| 107 | // signinOficina is GET /signin/oficina?return_to=…: "Continue with Oficina |
| 108 | // ID". It starts Equipo's exchange (oficinaid.Start, which carries the |
| 109 | // page in the exchange itself) for the validated return_to, or "/". A |
| 110 | // browser already signed in and admitted goes straight there instead; a |
| 111 | // refused session is ended first, so the exchange starts signed out; a |
| 112 | // step-up never reaches Home. |
| 113 | func (rt *Routes) signinOficina(w http.ResponseWriter, r *http.Request) { |
| 114 | q, err := url.ParseQuery(r.URL.RawQuery) |
| 115 | if err != nil { |
| 116 | http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) |
| 117 | return |
| 118 | } |
| 119 | path, ok := requestedReturn(q) |
| 120 | if !ok { |
| 121 | path = "/" |
| 122 | } |
| 123 | w.Header().Set("Cache-Control", "no-store") |
| 124 | if q.Has("reauth") { |
| 125 | local := url.Values{"reauth": {"1"}} |
| 126 | if ok { |
| 127 | local.Set("return_to", path) |
| 128 | } |
| 129 | http.Redirect(w, r, SigninLocalPath+"?"+local.Encode(), http.StatusSeeOther) |
| 130 | return |
| 131 | } |
| 132 | if _, admitted := rt.admitted(w, r); admitted { |
| 133 | http.Redirect(w, r, path, http.StatusSeeOther) |
| 134 | return |
| 135 | } |
| 136 | http.Redirect(w, r, StartPath+"?"+url.Values{"return_to": {path}}.Encode(), http.StatusSeeOther) |
| 137 | } |
| 138 | |
| 139 | func alreadySignedIn(w http.ResponseWriter, r *http.Request, q url.Values) { |
| 140 | path, ok := requestedReturn(q) |
| 141 | if !ok { |
| 142 | path = "/" |
| 143 | } |
| 144 | w.Header().Set("Cache-Control", "no-store") |
| 145 | http.Redirect(w, r, path, http.StatusSeeOther) |
| 146 | } |
| 147 | |
| 148 | // forget is POST to Forget, rastrillo auth's Forget: "Use a different |
| 149 | // email" on the door, and "Forget me on this device" on the signed-out |
| 150 | // page. It also forgets the page a sign-in in progress kept. Each host |
| 151 | // remembers for itself, so with Home the signed-out page's form |
| 152 | // (chain=oficina) goes on to Oficina ID's own Forget once this one has |
| 153 | // answered, with Equipo's signed-out page as the way back. Anything but |
| 154 | // Forget's own redirect (a cross-origin refusal) is passed on as it is. |
| 155 | func (rt *Routes) forget(w http.ResponseWriter, r *http.Request) { |
| 156 | if r.Method == http.MethodPost { |
| 157 | rt.spendKept(w, r) |
| 158 | } |
| 159 | if rt.Issuer == "" { |
| 160 | rt.Auth.Forget(w, r) |
| 161 | return |
| 162 | } |
| 163 | out := &buffered{header: make(http.Header)} |
| 164 | rt.Auth.Forget(out, r) |
| 165 | if out.status == http.StatusSeeOther && r.PostFormValue("chain") == chainOficina { |
| 166 | out.header.Set("Location", OficinaForget(rt.Issuer, rt.Origin)) |
| 167 | } |
| 168 | out.replay(w) |
| 169 | } |
| 170 | |
| 171 | // OficinaForget is Oficina ID's Forget, returning to this origin's |
| 172 | // signed-out page (Home's forgetChainReturn takes only a registered |
| 173 | // consumer's exact /signed-out). |
| 174 | func OficinaForget(issuer, origin string) string { |
| 175 | back := strings.TrimSuffix(origin, "/") + SignedOutPath |
| 176 | return strings.TrimSuffix(issuer, "/") + "/forget?" + url.Values{"return": {back}}.Encode() |
| 177 | } |
| 178 | |
| 179 | // standaloneSignout is rastrillo's Sign out, which ends the session, clears |
| 180 | // the kept page and redirects to the door; it lands on /signed-out |
| 181 | // instead, which says what just happened. |
| 182 | func (rt *Routes) standaloneSignout(w http.ResponseWriter, r *http.Request) { |
| 183 | out := &buffered{header: make(http.Header)} |
| 184 | rt.Signout(out, r) |
| 185 | if out.status == http.StatusSeeOther && out.header.Get("Location") == SigninPath { |
| 186 | out.header.Set("Location", SignedOutPath) |
| 187 | } |
| 188 | out.replay(w) |
| 189 | } |
| 190 | |
| 191 | // homeSignout is oficinaid's Sign out, which also forgets the page a |
| 192 | // sign-in in progress kept: it was this person's, not the next one's. |
| 193 | func (rt *Routes) homeSignout(w http.ResponseWriter, r *http.Request) { |
| 194 | rt.spendKept(w, r) |
| 195 | rt.Signout(w, r) |
| 196 | } |
| 197 | |
| 198 | // keptCookie is rastrillo auth's own memory of the page a sign-in began |
| 199 | // from (auth.keepReturnTo): its cookie name, __Host- on https. |
| 200 | func (rt *Routes) keptCookie() string { |
| 201 | if strings.HasPrefix(rt.Origin, "https://") { |
| 202 | return "__Host-rastrillo_return_to" |
| 203 | } |
| 204 | return "rastrillo_return_to" |
| 205 | } |
| 206 | |
| 207 | // spendKept clears the kept page, when the browser holds one. |
| 208 | func (rt *Routes) spendKept(w http.ResponseWriter, r *http.Request) { |
| 209 | if _, err := r.Cookie(rt.keptCookie()); err != nil { |
| 210 | return |
| 211 | } |
| 212 | http.SetCookie(w, &http.Cookie{Name: rt.keptCookie(), Value: "", Path: "/", MaxAge: -1, HttpOnly: true, |
| 213 | Secure: strings.HasPrefix(rt.Origin, "https://"), SameSite: http.SameSiteLaxMode}) |
| 214 | } |
| 215 | |
| 216 | // SignedIn is oficinaid's hook on a finished Oficina ID sign-in, once the |
| 217 | // session is minted on w (the app's MintHomeSession). The page an email |
| 218 | // sign-in kept is spent, as every landing that mints a session spends it. |
| 219 | // Oficina ID is remembered only for a session the signed-in routes admit, |
| 220 | // asked of the session just minted and strictly, with the address of the |
| 221 | // Equipo account it signed in as: never one carried over from the record |
| 222 | // it replaces. Remembering is a convenience and fails silently. |
| 223 | func (rt *Routes) SignedIn(w http.ResponseWriter, r *http.Request, minted *http.Cookie) { |
| 224 | rt.spendKept(w, r) |
| 225 | probe := withoutCookie(r, rt.Auth.SessionCookie()) |
| 226 | probe.AddCookie(&http.Cookie{Name: minted.Name, Value: minted.Value}) |
| 227 | ad := rt.admission(probe) |
| 228 | if !ad.admitted || ad.undecided { |
| 229 | return |
| 230 | } |
| 231 | rt.Auth.RememberJar().Remember(w, lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: ad.address}) |
| 232 | } |
| 233 | |
| 234 | // admitted runs the admission probe for the door: whether r's session is |
| 235 | // a web sign-in the signed-in routes admit. One they refuse is ended here, |
| 236 | // at the door (refusedSession), and r comes back marked to say why and |
| 237 | // without that cookie. One they cannot decide on is left alone and counts |
| 238 | // as signed in, as connect counts any live session. |
| 239 | func (rt *Routes) admitted(w http.ResponseWriter, r *http.Request) (*http.Request, bool) { |
| 240 | ad := rt.admission(r) |
| 241 | if ad.refused || ad.stale { |
| 242 | return rt.refusedSession(w, r, ad.refused), false |
| 243 | } |
| 244 | return r, ad.admitted || ad.undecided |
| 245 | } |
| 246 | |
| 247 | // refusedSession ends a session the probe refused: its row is deleted and |
| 248 | // its cookie cleared on this response, so a reload is plainly signed out |
| 249 | // and the refused person cannot loop between the door and the page that |
| 250 | // refuses them. A remembered Oficina ID is forgotten, because offered again |
| 251 | // it would sign the same refused person in; a remembered email way is |
| 252 | // kept. If the session cannot be ended, the door says nothing of it. |
| 253 | // |
| 254 | // With refused false the session is only stale (an active member's from |
| 255 | // before their session epoch: removed, then added back): it is ended the |
| 256 | // same way, and the door is plain, with nothing forgotten and no refusal, |
| 257 | // because this person can sign in. |
| 258 | func (rt *Routes) refusedSession(w http.ResponseWriter, r *http.Request, refused bool) *http.Request { |
| 259 | c, err := r.Cookie(rt.Auth.SessionCookie()) |
| 260 | if err != nil { |
| 261 | return r |
| 262 | } |
| 263 | if _, err := rt.DB.ExecContext(r.Context(), "DELETE FROM sessions WHERE token_hash=?", sessions.HashToken(c.Value)); err != nil { |
| 264 | return r |
| 265 | } |
| 266 | http.SetCookie(w, &http.Cookie{Name: c.Name, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, |
| 267 | Secure: strings.HasPrefix(rt.Origin, "https://"), SameSite: http.SameSiteLaxMode}) |
| 268 | w.Header().Set("Cache-Control", "no-store") |
| 269 | if !refused { |
| 270 | return withoutCookie(r, c.Name) |
| 271 | } |
| 272 | jar := rt.Auth.RememberJar() |
| 273 | if rec, res := jar.Read(r); res == lastsignin.Valid && rec.Method == lastsignin.MethodFederated { |
| 274 | jar.Clear(w) |
| 275 | } |
| 276 | return withRefusal(withoutCookie(r, c.Name)) |
| 277 | } |
| 278 | |
| 279 | // admission is what the probe found. |
| 280 | type admission struct { |
| 281 | admitted, refused, undecided bool |
| 282 | // stale: the guard refused a session of an active member, one from |
| 283 | // before their session epoch. Signed out, not refused. |
| 284 | stale bool |
| 285 | address string |
| 286 | } |
| 287 | |
| 288 | // admission runs the gate every signed-in page runs (requireMember: |
| 289 | // rastrillo's session, or Oficina ID's resolved through its link, then the |
| 290 | // roster) around a probe GET / whose answer is thrown away. |
| 291 | // |
| 292 | // - Only web sign-ins are judged: an emailed link, Keymail, and an |
| 293 | // Oficina ID sign-in on the web. A native session |
| 294 | // (home-assertion-native) is the Mac and iPhone app's, which never |
| 295 | // reaches a door, and is never judged, refused, remembered or ended. |
| 296 | // - Any 5xx is undecided: the door must not tell somebody they cannot |
| 297 | // sign in, nor sign them out, because a read failed. |
| 298 | // - A 4xx is a refusal, except for somebody no member yet whose |
| 299 | // invitation lets them verify the address: they are between steps, |
| 300 | // and the door leaves them alone. |
| 301 | // - Anything else (the guard sent them to sign in) is signed out. |
| 302 | func (rt *Routes) admission(r *http.Request) admission { |
| 303 | if rt.Auth == nil || rt.Guard == nil { |
| 304 | return admission{} |
| 305 | } |
| 306 | probe := r.Clone(r.Context()) |
| 307 | probe.Method = http.MethodGet |
| 308 | probe.URL = &url.URL{Path: "/"} |
| 309 | probe.RequestURI = "/" |
| 310 | probe.Body = http.NoBody |
| 311 | probe.Header.Del("Authorization") |
| 312 | raw, ok := rt.Auth.SessionFrom(probe) |
| 313 | if !ok || !judged(string(raw.Method)) { |
| 314 | return admission{} |
| 315 | } |
| 316 | var ad admission |
| 317 | reached := false |
| 318 | gate := rt.Guard(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { |
| 319 | reached = true |
| 320 | if id, ok := identity.From(r); ok { |
| 321 | ad.address = id.Address |
| 322 | } |
| 323 | })) |
| 324 | out := &buffered{header: make(http.Header)} |
| 325 | gate.ServeHTTP(out, probe) |
| 326 | switch { |
| 327 | case reached: |
| 328 | ad.admitted = true |
| 329 | case out.status >= http.StatusInternalServerError: |
| 330 | ad.undecided = true |
| 331 | case out.status >= http.StatusBadRequest: |
| 332 | return rt.standing(r.Context(), raw) |
| 333 | } |
| 334 | return ad |
| 335 | } |
| 336 | |
| 337 | // standing is what a 4xx from the guard means for raw: a refusal, a stale |
| 338 | // session of somebody still on the team (removed and added back since it |
| 339 | // began), or somebody invited who has not joined yet (left alone). Any |
| 340 | // lookup that fails is undecided. |
| 341 | func (rt *Routes) standing(ctx context.Context, raw auth.Identity) admission { |
| 342 | address := raw.Address |
| 343 | if string(raw.Method) == oficinaid.Method { |
| 344 | if rt.Address == nil { |
| 345 | return admission{refused: true} |
| 346 | } |
| 347 | var err error |
| 348 | if address, err = rt.Address(ctx, raw.Address); err != nil { |
| 349 | return admission{undecided: true} |
| 350 | } |
| 351 | if address == "" { |
| 352 | return admission{refused: true} |
| 353 | } |
| 354 | } |
| 355 | if rt.Active != nil { |
| 356 | active, err := rt.Active(ctx, address) |
| 357 | if err != nil { |
| 358 | return admission{undecided: true} |
| 359 | } |
| 360 | if active { |
| 361 | return admission{stale: true} |
| 362 | } |
| 363 | } |
| 364 | if string(raw.Method) != oficinaid.Method && rt.Invited != nil { |
| 365 | invited, err := rt.Invited(ctx, address) |
| 366 | if err != nil { |
| 367 | return admission{undecided: true} |
| 368 | } |
| 369 | if invited { |
| 370 | return admission{} |
| 371 | } |
| 372 | } |
| 373 | return admission{refused: true} |
| 374 | } |
| 375 | |
| 376 | // judged reports whether the door judges a session by its method. |
| 377 | func judged(method string) bool { |
| 378 | return method == "magiclink" || method == "keymail" || method == oficinaid.Method |
| 379 | } |
| 380 | |
| 381 | // withoutCookie is r as a handler that must not see the named cookie. |
| 382 | func withoutCookie(r *http.Request, name string) *http.Request { |
| 383 | c := r.Clone(r.Context()) |
| 384 | c.Header = r.Header.Clone() |
| 385 | c.Header.Del("Cookie") |
| 386 | for _, cookie := range r.Cookies() { |
| 387 | if cookie.Name != name { |
| 388 | c.AddCookie(cookie) |
| 389 | } |
| 390 | } |
| 391 | return c |
| 392 | } |
| 393 | |
| 394 | // buffered holds a handler's answer so it can be read or changed before |
| 395 | // it is sent. |
| 396 | type buffered struct { |
| 397 | header http.Header |
| 398 | status int |
| 399 | body bytes.Buffer |
| 400 | } |
| 401 | |
| 402 | func (b *buffered) Header() http.Header { return b.header } |
| 403 | func (b *buffered) WriteHeader(status int) { |
| 404 | if b.status == 0 { |
| 405 | b.status = status |
| 406 | } |
| 407 | } |
| 408 | func (b *buffered) Write(p []byte) (int, error) { |
| 409 | if b.status == 0 { |
| 410 | b.status = http.StatusOK |
| 411 | } |
| 412 | return b.body.Write(p) |
| 413 | } |
| 414 | |
| 415 | func (b *buffered) replay(w http.ResponseWriter) { |
| 416 | for name, values := range b.header { |
| 417 | for _, v := range values { |
| 418 | w.Header().Add(name, v) |
| 419 | } |
| 420 | } |
| 421 | if b.status == 0 { |
| 422 | b.status = http.StatusOK |
| 423 | } |
| 424 | w.WriteHeader(b.status) |
| 425 | _, _ = w.Write(b.body.Bytes()) |
| 426 | } |
| 427 | |