| 1 | package calendar |
| 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 is asked about it, on a |
| 6 | // probe. A session it refuses gets the door with the refusal (or, in team |
| 7 | // mode, the removal) and is ended; one it cannot decide on is left alone. |
| 8 | // And the smart door's memory of an Oficina ID sign-in, written only for a |
| 9 | // session that gate admits. |
| 10 | |
| 11 | import ( |
| 12 | "context" |
| 13 | "database/sql" |
| 14 | "fmt" |
| 15 | "net/http" |
| 16 | "net/url" |
| 17 | |
| 18 | "amadan.net/oficina/home/connect" |
| 19 | "amadan.net/rastrillo/rastrillo/lastsignin" |
| 20 | "amadan.net/rastrillo/rastrillo/sessions" |
| 21 | ) |
| 22 | |
| 23 | // standaloneSignin is GET /signin without Home: somebody already signed in |
| 24 | // and admitted never sees the door (spec shared-chrome §9.4) unless the |
| 25 | // query names one of its states, and goes to a safe return_to or "/". A |
| 26 | // session the signed-in routes refuse gets the door with the refusal, as |
| 27 | // with Home (admittedOnly). Standalone Calendar has only email, so the door |
| 28 | // is the email way. |
| 29 | func (a *App) standaloneSignin(w http.ResponseWriter, r *http.Request) { |
| 30 | if ad := a.admission(r, false); ad.signedIn { |
| 31 | if !ad.admitted { |
| 32 | r = a.refusedSession(w, r, ad.removed) |
| 33 | } else if !signinOutcome(r) { |
| 34 | alreadySignedIn(w, r) |
| 35 | return |
| 36 | } |
| 37 | } |
| 38 | a.signinDoor(w, r) |
| 39 | } |
| 40 | |
| 41 | // admittedOnly runs connect's SigninDoor, SigninLocal or SigninOficina for |
| 42 | // a browser whose session the signed-in routes would admit, and as signed |
| 43 | // out for any other. SigninDoor and SigninOficina take any live session |
| 44 | // cookie as signed in and send it straight to the page; a session the |
| 45 | // signed-in routes refuse (an address taken off the allowlist, a Home link |
| 46 | // to a deleted person, somebody the roster says is off the team) would |
| 47 | // then go round /signin, the page, the refusal and back (Astra on Docs #65, |
| 48 | // Sheets #39), so they are not shown that cookie. SigninLocal is wrapped |
| 49 | // too, for the refusals that land there. |
| 50 | func (a *App) admittedOnly(next http.HandlerFunc) http.HandlerFunc { |
| 51 | return func(w http.ResponseWriter, r *http.Request) { |
| 52 | if ad := a.admission(r, false); ad.signedIn && !ad.admitted { |
| 53 | r = withoutCookie(a.refusedSession(w, r, ad.removed), a.sessionCookie()) |
| 54 | } |
| 55 | next(w, r) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // refusedSession answers for a session the probe refused: its cookie is |
| 60 | // cleared on this response (the probe's own answer, which may have cleared |
| 61 | // it, was thrown away), so a reload is plainly signed out rather than a |
| 62 | // dead cookie over the plain door; a remembered Oficina ID is forgotten, |
| 63 | // because offered again it would sign the same refused person in and send |
| 64 | // them back here; and the door is marked to say why: the refusal, or for |
| 65 | // somebody the roster says is off the team the removal, in the screen's |
| 66 | // app-problem slot with the email field. A remembered email way is kept: |
| 67 | // it is no loop. |
| 68 | func (a *App) refusedSession(w http.ResponseWriter, r *http.Request, removed bool) *http.Request { |
| 69 | a.sessionStore().SignOut(w, r) |
| 70 | w.Header().Set("Cache-Control", "no-store") |
| 71 | jar := a.auth.RememberJar() |
| 72 | if rec, res := jar.Read(r); res == lastsignin.Valid && rec.Method == lastsignin.MethodFederated { |
| 73 | jar.Clear(w) |
| 74 | } |
| 75 | if removed { |
| 76 | return withRemoval(r) |
| 77 | } |
| 78 | return withRefusal(r) |
| 79 | } |
| 80 | |
| 81 | // admissionResult is what the probe found: whether r holds a session at |
| 82 | // all, whether the signed-in routes let it in, and whether they turned it |
| 83 | // away as off the team (offboard). |
| 84 | type admissionResult struct { |
| 85 | signedIn, admitted, removed bool |
| 86 | } |
| 87 | |
| 88 | // admission runs the gate every signed-in page runs (the session, then |
| 89 | // requirePerson: identity, the allowlist recheck, a Home link, the roster) |
| 90 | // around a probe GET / whose answer is thrown away. A session is not |
| 91 | // enough: an address taken off the allowlist still holds a valid one. |
| 92 | // The probe ends nothing itself (offboard skips its sign-out under it): |
| 93 | // the door's caller does, for a session it decides to refuse. |
| 94 | // |
| 95 | // The per-route standing gate is not part of it: it sends an unlinked local |
| 96 | // account in team mode to /account/home, which is a way on, not a refusal, |
| 97 | // and the old /signin checks (homeSignin, teamSignin) never asked it either. |
| 98 | // |
| 99 | // A gate that cannot decide (a 5xx: storage or the roster unavailable) |
| 100 | // counts as admitted unless strict: the door must not tell somebody they |
| 101 | // cannot sign in, nor sign them out, because a read failed, and nothing is |
| 102 | // remembered on one. |
| 103 | func (a *App) admission(r *http.Request, strict bool) admissionResult { |
| 104 | probe := r.Clone(context.WithValue(r.Context(), probingKey{}, true)) |
| 105 | probe.Method = http.MethodGet |
| 106 | probe.URL = &url.URL{Path: "/"} |
| 107 | probe.RequestURI = "/" |
| 108 | probe.Body = http.NoBody |
| 109 | // The session is read from the probe's own cookie, never from the |
| 110 | // context the app-wide middleware filled: admittedAs asks about a |
| 111 | // session minted on this very response. |
| 112 | s, ok := a.sessions.From(probe) |
| 113 | if !ok { |
| 114 | return admissionResult{} |
| 115 | } |
| 116 | if !doorJudges(s.Method) { |
| 117 | // Not the web door's to judge (a native app's session, a guest): |
| 118 | // signed in, as the old /signin checks left it, and never refused. |
| 119 | return admissionResult{signedIn: true, admitted: true} |
| 120 | } |
| 121 | reached := false |
| 122 | gate := a.requirePerson(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true })) |
| 123 | rec := &bufferedResponse{header: make(http.Header)} |
| 124 | if a.home != nil { |
| 125 | gate.ServeHTTP(rec, withSession(probe, s)) |
| 126 | } else { |
| 127 | a.auth.RequireSession(gate).ServeHTTP(rec, probe) |
| 128 | } |
| 129 | undecided := rec.status >= http.StatusInternalServerError |
| 130 | return admissionResult{ |
| 131 | signedIn: true, |
| 132 | admitted: reached || (!strict && undecided), |
| 133 | removed: !reached && rec.status == http.StatusSeeOther && rec.header.Get("Location") == offboardPath, |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // doorJudges reports whether the door's probe judges a session signed in |
| 138 | // by method: the three requirePerson speaks for (a Home sign-in on the web, |
| 139 | // an emailed link, Keymail), as homeSignin and teamSignin did. Any other |
| 140 | // (connect's native methods, a guest) is never refused by the web door. |
| 141 | func doorJudges(method string) bool { |
| 142 | return method == connect.HomeMethod || method == "magiclink" || method == "keymail" |
| 143 | } |
| 144 | |
| 145 | // probingKey marks the admission probe's request, so the gate it runs |
| 146 | // answers without ending anything (offboard). |
| 147 | type probingKey struct{} |
| 148 | |
| 149 | // probing reports whether ctx is the admission probe's. |
| 150 | func probing(ctx context.Context) bool { |
| 151 | v, _ := ctx.Value(probingKey{}).(bool) |
| 152 | return v |
| 153 | } |
| 154 | |
| 155 | // withoutCookie is r, as seen by a handler that must not see the named |
| 156 | // cookie. Only admittedOnly and admittedAs use it. |
| 157 | func withoutCookie(r *http.Request, name string) *http.Request { |
| 158 | c := r.Clone(r.Context()) |
| 159 | c.Header.Del("Cookie") |
| 160 | for _, cookie := range r.Cookies() { |
| 161 | if cookie.Name != name { |
| 162 | c.AddCookie(cookie) |
| 163 | } |
| 164 | } |
| 165 | return c |
| 166 | } |
| 167 | |
| 168 | // rememberOficina is the smart door's memory of a Home sign-in, written in |
| 169 | // MintHomeSession once the session is stored, so it is written only where |
| 170 | // connect turns a Home sign-in into a session here (a finished exchange, |
| 171 | // "I'm new here"), never on link, choose, unknown or failed. The record is |
| 172 | // Oficina ID, with the address of the person connect resolved for this |
| 173 | // very sign-in (connect.MintedPerson), or none for a Home-only member. |
| 174 | // Nothing is carried over from the record it replaces: that address could |
| 175 | // be somebody else's. Remembering is a convenience, and Remember fails |
| 176 | // silently, so it can never fail the sign-in. |
| 177 | // |
| 178 | // Only for a session the signed-in routes admit, asked of the session just |
| 179 | // minted (admittedAs) and strictly: connect mints for any linked person, |
| 180 | // and a record for a refused one would offer Oficina ID again, round a |
| 181 | // loop of sign-in, refusal and door (Fable on Docs #139, A2). |
| 182 | func (a *App) rememberOficina(w http.ResponseWriter, r *http.Request) { |
| 183 | if a.auth == nil || a.home == nil { |
| 184 | return |
| 185 | } |
| 186 | if !a.admission(a.admittedAs(w, r), true).admitted { |
| 187 | return |
| 188 | } |
| 189 | address := "" |
| 190 | if p, ok := connect.MintedPerson(r); ok { |
| 191 | address = p.Label |
| 192 | } |
| 193 | a.auth.RememberJar().Remember(w, lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: address}) |
| 194 | } |
| 195 | |
| 196 | // admittedAs is r as the session MintHomeSession just set on w would send |
| 197 | // it: the request's own cookies, with that session's in place of any other. |
| 198 | func (a *App) admittedAs(w http.ResponseWriter, r *http.Request) *http.Request { |
| 199 | name := a.sessionCookie() |
| 200 | var minted *http.Cookie |
| 201 | for _, c := range (&http.Response{Header: w.Header()}).Cookies() { |
| 202 | if c.Name == name && c.MaxAge >= 0 && c.Value != "" { |
| 203 | minted = c |
| 204 | } |
| 205 | } |
| 206 | probe := withoutCookie(r, name) |
| 207 | if minted != nil { |
| 208 | probe.AddCookie(&http.Cookie{Name: minted.Name, Value: minted.Value}) |
| 209 | } |
| 210 | return probe |
| 211 | } |
| 212 | |
| 213 | // signinOutcome reports whether GET /signin names a state of the door |
| 214 | // rather than opening it afresh: an outcome of the email flow (?sent, |
| 215 | // ?err, ?force), the Keymail continuation (?continue) or a step-up |
| 216 | // (?reauth). connect's SigninDoor draws the same five for a signed-in |
| 217 | // browser too (its doorStates). |
| 218 | func signinOutcome(r *http.Request) bool { |
| 219 | q := r.URL.Query() |
| 220 | return q.Has("sent") || q.Has("err") || q.Has("force") || q.Has("continue") || q.Has("reauth") |
| 221 | } |
| 222 | |
| 223 | // alreadySignedIn sends a signed-in GET /signin back where it came from, |
| 224 | // with no door: 303 to a safe return_to, or "/". |
| 225 | func alreadySignedIn(w http.ResponseWriter, r *http.Request) { |
| 226 | target := "/" |
| 227 | if path, ok := requestedReturn(r); ok && !signedOutPage(path) { |
| 228 | target = path |
| 229 | } |
| 230 | w.Header().Set("Cache-Control", "no-store") |
| 231 | http.Redirect(w, r, target, http.StatusSeeOther) |
| 232 | } |
| 233 | |
| 234 | // wireSessions sets App.sessions: Home's with Home configured, otherwise a |
| 235 | // store over the same table and cookie as auth's own. |
| 236 | func (a *App) wireSessions(writer *sql.DB, origin string) error { |
| 237 | if a.home != nil { |
| 238 | a.sessions = a.home.sessions |
| 239 | return nil |
| 240 | } |
| 241 | s, err := sessions.New(sessions.Config{DB: writer, Origin: origin, Logger: a.logger}) |
| 242 | if err != nil { |
| 243 | return fmt.Errorf("calendar: sessions: %w", err) |
| 244 | } |
| 245 | a.sessions = s |
| 246 | return nil |
| 247 | } |
| 248 | |
| 249 | // sessionStore is the session store the door signs a refused session out |
| 250 | // of (App.sessions). |
| 251 | func (a *App) sessionStore() *sessions.Sessions { return a.sessions } |
| 252 | |
| 253 | // sessionCookie is the session cookie's name: auth's and Home's are the |
| 254 | // same table and the same cookie. |
| 255 | func (a *App) sessionCookie() string { return a.sessions.CookieName() } |
| 256 | |
| 257 | // withSession is r carrying s as the current session, in place of any the |
| 258 | // app-wide middleware put there (admission, above). |
| 259 | func withSession(r *http.Request, s sessions.Session) *http.Request { |
| 260 | return sessions.WithSession(r, s) |
| 261 | } |
| 262 | |