| 1 | package memoria |
| 2 | |
| 3 | // The door's admission check (home/connect MIGRATING.md, step 6, item 2): |
| 4 | // before /signin, /signin/local or /signin/oficina may treat a live session |
| 5 | // as signed in, the gate every signed-in page runs (requireSession) is |
| 6 | // asked about it, on a probe. A session it refuses gets the door with the |
| 7 | // refusal (or the removal) and is ended; one it cannot decide on is left |
| 8 | // alone. And the smart door's memory of an Oficina ID sign-in, written only |
| 9 | // for a session that gate admits. |
| 10 | // |
| 11 | // What the door judges, and what it never touches: |
| 12 | // |
| 13 | // - A web sign-in (an emailed link, Keymail, a Home sign-in) is judged, |
| 14 | // as the old /signin's admission check (signin, offboard) judged it. |
| 15 | // - Any other session is never judged, refused, remembered or ended here: |
| 16 | // the door is drawn for it as for anybody signed out. requireSession |
| 17 | // recognises no other method as a person (identity, teamIdentify), and |
| 18 | // connect's native sessions (home-assertion-native, its native web |
| 19 | // session) are not Memoria's. |
| 20 | // - The native apps hold sessions of their own: rastrillo/native's |
| 21 | // exchange (native.go) mints the app its own session row, a copy of the |
| 22 | // browser's, and the app calls only /api/native/* with it, never a |
| 23 | // door. The door only ever ends the one session the browser presented |
| 24 | // (refusedSession), so no native session is refused or ended by it. |
| 25 | |
| 26 | import ( |
| 27 | "context" |
| 28 | "net/http" |
| 29 | "net/url" |
| 30 | |
| 31 | "amadan.net/oficina/home/connect" |
| 32 | "amadan.net/rastrillo/rastrillo/lastsignin" |
| 33 | ) |
| 34 | |
| 35 | // signinRoute is GET /signin: the door. With Home, connect's SigninDoor |
| 36 | // behind the admission check; standalone, standaloneSignin. |
| 37 | func (a *app) signinRoute(w http.ResponseWriter, r *http.Request) { |
| 38 | if a.home == nil { |
| 39 | a.standaloneSignin(w, r) |
| 40 | return |
| 41 | } |
| 42 | a.homeDoor(a.home.routes.SigninDoor)(w, r) |
| 43 | } |
| 44 | |
| 45 | // signinLocalRoute is GET /signin/local: with Home, the door with email as |
| 46 | // the one way in (connect's SigninLocal, under LocalGuard), where connect |
| 47 | // sends people Oficina ID cannot help. Standalone it does not exist. |
| 48 | func (a *app) signinLocalRoute(w http.ResponseWriter, r *http.Request) { |
| 49 | if a.home == nil { |
| 50 | a.routeNotFound(w, r) |
| 51 | return |
| 52 | } |
| 53 | a.home.routes.LocalGuard(a.homeDoor(a.home.routes.SigninLocal))(w, r) |
| 54 | } |
| 55 | |
| 56 | // signinOficinaRoute is GET /signin/oficina: with Home, Continue with |
| 57 | // Oficina ID, which remembers return_to and starts the Home exchange. |
| 58 | // Standalone it does not exist. |
| 59 | func (a *app) signinOficinaRoute(w http.ResponseWriter, r *http.Request) { |
| 60 | if a.home == nil { |
| 61 | a.routeNotFound(w, r) |
| 62 | return |
| 63 | } |
| 64 | a.homeDoor(a.home.routes.SigninOficina)(w, r) |
| 65 | } |
| 66 | |
| 67 | // homeDoor is one of connect's three door routes as Memoria mounts it: |
| 68 | // under Home's session middleware, which clears a cookie whose session is |
| 69 | // definitively gone (and leaves it on a storage failure), so a stale cookie |
| 70 | // cannot stand in the way of the exchange (connect's Start refuses a |
| 71 | // session cookie that does not resolve); then the admission check. |
| 72 | func (a *app) homeDoor(next http.HandlerFunc) http.HandlerFunc { |
| 73 | return a.home.sessions.Middleware(a.admittedOnly(next)).ServeHTTP |
| 74 | } |
| 75 | |
| 76 | // standaloneSignin is GET /signin without Home: somebody already signed in |
| 77 | // and admitted never sees the door (spec shared-chrome §9.2) unless the |
| 78 | // query names one of its states, and goes to a safe return_to or "/". A |
| 79 | // session the signed-in routes refuse gets the door with the refusal, as |
| 80 | // with Home (admittedOnly). Standalone Memoria has only email, so the door |
| 81 | // is the email way. |
| 82 | func (a *app) standaloneSignin(w http.ResponseWriter, r *http.Request) { |
| 83 | if ad := a.admission(r, false); ad.signedIn { |
| 84 | if !ad.admitted { |
| 85 | r = a.refusedSession(w, r, ad.removed) |
| 86 | } else if !signinOutcome(r) { |
| 87 | alreadySignedIn(w, r) |
| 88 | return |
| 89 | } |
| 90 | } |
| 91 | a.signinDoor(w, r) |
| 92 | } |
| 93 | |
| 94 | // admittedOnly runs connect's SigninDoor, SigninLocal or SigninOficina for |
| 95 | // a browser whose session the signed-in routes would admit, and as signed |
| 96 | // out for any other. SigninDoor and SigninOficina take any live session |
| 97 | // cookie as signed in and send it straight to the page; a session the |
| 98 | // signed-in routes refuse (a Home link to an address taken off the owners |
| 99 | // list, somebody the roster says is off the team) would then go round |
| 100 | // /signin, the page, the refusal and back (Astra on Docs #65, Sheets #39), |
| 101 | // so they are not shown that cookie. SigninLocal is wrapped too, for the |
| 102 | // refusals that land there. |
| 103 | func (a *app) admittedOnly(next http.HandlerFunc) http.HandlerFunc { |
| 104 | return func(w http.ResponseWriter, r *http.Request) { |
| 105 | if ad := a.admission(r, false); ad.signedIn && !ad.admitted { |
| 106 | r = withoutCookie(a.refusedSession(w, r, ad.removed), a.sessionCookie()) |
| 107 | } |
| 108 | next(w, r) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | // refusedSession answers for a session the probe refused: it is ended and |
| 113 | // its cookie cleared on this response, so a reload is plainly signed out |
| 114 | // rather than a dead cookie over the plain door; a remembered Oficina ID is |
| 115 | // forgotten, because offered again it would sign the same refused person |
| 116 | // in and send them back here; and the door is marked to say why: the |
| 117 | // refusal, or for a session the signed-in routes end as removed the |
| 118 | // removal, in the screen's app-problem slot with the email field. A |
| 119 | // remembered email way is kept: it is no loop. |
| 120 | // |
| 121 | // Removal ends the session HERE, at the door, and never inside the probe |
| 122 | // (offboard skips its sign-out while probing). |
| 123 | func (a *app) refusedSession(w http.ResponseWriter, r *http.Request, removed bool) *http.Request { |
| 124 | if a.sess != nil { |
| 125 | a.sess.SignOut(w, r) |
| 126 | } |
| 127 | w.Header().Set("Cache-Control", "no-store") |
| 128 | jar := a.auth.RememberJar() |
| 129 | if rec, res := jar.Read(r); res == lastsignin.Valid && rec.Method == lastsignin.MethodFederated { |
| 130 | jar.Clear(w) |
| 131 | } |
| 132 | if removed { |
| 133 | return withRemoval(r) |
| 134 | } |
| 135 | return withRefusal(r) |
| 136 | } |
| 137 | |
| 138 | // admissionResult is what the probe found: whether r holds a web sign-in |
| 139 | // at all, whether the signed-in routes let it in, and whether they ended it |
| 140 | // as removed (offboard). |
| 141 | type admissionResult struct { |
| 142 | signedIn, admitted, removed bool |
| 143 | } |
| 144 | |
| 145 | // admission runs the gate every signed-in page runs (requireSession: |
| 146 | // rastrillo auth's RequireSession, then the owners list through identity, |
| 147 | // a Home link and whether it still resolves to an owner, or in team mode |
| 148 | // the roster) around a probe GET / whose answer is thrown away. A session |
| 149 | // is not enough: a Home link to an address taken off the owners list still |
| 150 | // holds a valid one. The probe ends nothing itself (offboard skips its |
| 151 | // sign-out under it): the door's caller does, for a session it decides to |
| 152 | // refuse. |
| 153 | // |
| 154 | // The routes' standing gate (team_access.go's standing) is not part of |
| 155 | // it: it sends an unlinked local account to /account/home, a way on, not |
| 156 | // a refusal, and the old /signin check never asked it either. |
| 157 | // |
| 158 | // A gate that cannot decide (a 5xx: storage or the roster unavailable) |
| 159 | // counts as admitted unless strict: the door must not tell somebody they |
| 160 | // cannot sign in, nor sign them out, because a read failed, and nothing is |
| 161 | // remembered on one. |
| 162 | func (a *app) admission(r *http.Request, strict bool) admissionResult { |
| 163 | if a.allowUnauthenticated { |
| 164 | // AppForTest: the stub identity is signed in and admitted, as |
| 165 | // admissionOf and requireSession say. |
| 166 | return admissionResult{signedIn: a.testIdentity != "", admitted: a.testIdentity != ""} |
| 167 | } |
| 168 | if a.auth == nil || a.sess == nil { |
| 169 | return admissionResult{} |
| 170 | } |
| 171 | probe := r.Clone(context.WithValue(r.Context(), probingKey{}, true)) |
| 172 | probe.Method = http.MethodGet |
| 173 | probe.URL = &url.URL{Path: "/"} |
| 174 | probe.RequestURI = "/" |
| 175 | probe.Body = http.NoBody |
| 176 | // The session is read from the probe's own cookie, never from the |
| 177 | // context a middleware filled: admittedAs asks about a session minted |
| 178 | // on this very response. |
| 179 | s, ok := a.sess.From(probe) |
| 180 | if !ok || !doorJudges(s.Method) { |
| 181 | // Signed out, or a session that is not a web sign-in: the door is |
| 182 | // drawn, and nothing is refused or ended. |
| 183 | return admissionResult{} |
| 184 | } |
| 185 | reached := false |
| 186 | gate := a.requireSession(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true })) |
| 187 | rec := &bufferedResponse{header: make(http.Header)} |
| 188 | gate.ServeHTTP(rec, probe) |
| 189 | undecided := rec.status >= http.StatusInternalServerError |
| 190 | return admissionResult{ |
| 191 | signedIn: true, |
| 192 | admitted: reached || (!strict && undecided), |
| 193 | removed: !reached && rec.status == http.StatusSeeOther && removedRedirect(rec.header.Get("Location")), |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | // doorJudges reports whether the door's probe judges a session by method: |
| 198 | // the three requireSession speaks for as a sign-in (an emailed link, |
| 199 | // Keymail, a Home sign-in on the web), as the old /signin check did. |
| 200 | func doorJudges(method string) bool { |
| 201 | return method == connect.HomeMethod || method == "magiclink" || method == "keymail" |
| 202 | } |
| 203 | |
| 204 | // removedRedirect reports whether location is offboard's: the door with |
| 205 | // err=removed. |
| 206 | func removedRedirect(location string) bool { |
| 207 | u, err := url.Parse(location) |
| 208 | return err == nil && u.Path == signinPath && u.Query().Get("err") == "removed" |
| 209 | } |
| 210 | |
| 211 | // probingKey marks the admission probe's request, so the gate it runs |
| 212 | // answers without ending anything (offboard). |
| 213 | type probingKey struct{} |
| 214 | |
| 215 | // probing reports whether ctx is the admission probe's. |
| 216 | func probing(ctx context.Context) bool { |
| 217 | v, _ := ctx.Value(probingKey{}).(bool) |
| 218 | return v |
| 219 | } |
| 220 | |
| 221 | // withoutCookie is r, as seen by a handler that must not see the named |
| 222 | // cookie. Only admittedOnly and admittedAs use it. |
| 223 | func withoutCookie(r *http.Request, name string) *http.Request { |
| 224 | c := r.Clone(r.Context()) |
| 225 | c.Header.Del("Cookie") |
| 226 | for _, cookie := range r.Cookies() { |
| 227 | if cookie.Name != name { |
| 228 | c.AddCookie(cookie) |
| 229 | } |
| 230 | } |
| 231 | return c |
| 232 | } |
| 233 | |
| 234 | // sessionCookie is the session cookie's name: auth's, Home's and the |
| 235 | // native hand-off's are the same table and the same cookie. |
| 236 | func (a *app) sessionCookie() string { return a.auth.SessionCookie() } |
| 237 | |
| 238 | // rememberOficina is the smart door's memory of a Home sign-in, written in |
| 239 | // MintHomeSession once the session is stored, so it is written only where |
| 240 | // connect turns a Home sign-in into a session here (a finished exchange, |
| 241 | // "I'm new here"), never on link, choose, unknown or failed. The record is |
| 242 | // Oficina ID, with the address of the person connect resolved for this |
| 243 | // very sign-in (connect.MintedPerson), or none for a Home-only member. |
| 244 | // Nothing is carried over from the record it replaces: that address could |
| 245 | // be somebody else's. Remembering is a convenience, and Remember fails |
| 246 | // silently, so it can never fail the sign-in. |
| 247 | // |
| 248 | // Only for a session the signed-in routes admit, asked of the session just |
| 249 | // minted (admittedAs) and strictly: connect mints for any linked person, |
| 250 | // and a record for a refused one would offer Oficina ID again, round a |
| 251 | // loop of sign-in, refusal and door (Fable on Docs #139, A2). |
| 252 | func (a *app) rememberOficina(w http.ResponseWriter, r *http.Request) { |
| 253 | if a.auth == nil || a.home == nil { |
| 254 | return |
| 255 | } |
| 256 | if !a.admission(a.admittedAs(w, r), true).admitted { |
| 257 | return |
| 258 | } |
| 259 | address := "" |
| 260 | if p, ok := connect.MintedPerson(r); ok { |
| 261 | address = p.Label |
| 262 | } |
| 263 | a.auth.RememberJar().Remember(w, lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: address}) |
| 264 | } |
| 265 | |
| 266 | // admittedAs is r as the session MintHomeSession just set on w would send |
| 267 | // it: the request's own cookies, with that session's in place of any other. |
| 268 | func (a *app) admittedAs(w http.ResponseWriter, r *http.Request) *http.Request { |
| 269 | name := a.sessionCookie() |
| 270 | var minted *http.Cookie |
| 271 | for _, c := range (&http.Response{Header: w.Header()}).Cookies() { |
| 272 | if c.Name == name && c.MaxAge >= 0 && c.Value != "" { |
| 273 | minted = c |
| 274 | } |
| 275 | } |
| 276 | probe := withoutCookie(r, name) |
| 277 | if minted != nil { |
| 278 | probe.AddCookie(&http.Cookie{Name: minted.Name, Value: minted.Value}) |
| 279 | } |
| 280 | return probe |
| 281 | } |
| 282 | |
| 283 | // signinOutcome reports whether GET /signin names a state of the door |
| 284 | // rather than opening it afresh: an outcome of the email flow (?sent, |
| 285 | // ?err, ?force), the Keymail continuation (?continue) or a step-up |
| 286 | // (?reauth). connect's SigninDoor draws the same five for a signed-in |
| 287 | // browser too (its doorStates). |
| 288 | func signinOutcome(r *http.Request) bool { |
| 289 | q := r.URL.Query() |
| 290 | return q.Has("sent") || q.Has("err") || q.Has("force") || q.Has("continue") || q.Has("reauth") |
| 291 | } |
| 292 | |
| 293 | // alreadySignedIn sends a signed-in GET /signin back where it came from, |
| 294 | // with no door: 303 to a safe return_to, or "/". |
| 295 | func alreadySignedIn(w http.ResponseWriter, r *http.Request) { |
| 296 | target := "/" |
| 297 | if path, ok := requestedReturn(r); ok { |
| 298 | target = path |
| 299 | } |
| 300 | w.Header().Set("Cache-Control", "no-store") |
| 301 | http.Redirect(w, r, target, http.StatusSeeOther) |
| 302 | } |
| 303 | |