| 1 | package calls |
| 2 | |
| 3 | // Back to where you were (shared chrome spec §9.4). Before this a |
| 4 | // signed-out visit to /settings, a meeting's holding screen or any other |
| 5 | // guarded page went to a bare /signin, and after the emailed link the |
| 6 | // person landed on the meeting list: rastrillo/auth's RequireSession |
| 7 | // drops the path, and its Verify always lands on a fixed SignedInPath. |
| 8 | // |
| 9 | // So the path rides a cookie instead of the link. GET /signin?return_to= |
| 10 | // remembers it, sealed and short-lived, and /continue (SignedInPath |
| 11 | // standalone, connect's LocalLandingPath with Home) goes there once a |
| 12 | // pending meeting join — which takes precedence, being the reason the |
| 13 | // person signed in at all — has had its turn. With Home configured, |
| 14 | // connect's SigninOficina remembers return_to for the Home exchange; this |
| 15 | // cookie serves every local sign-in (an emailed link, Keymail). |
| 16 | // |
| 17 | // The smart door (rastrillo's screen) posts return_to on its forms, and |
| 18 | // rastrillo would carry it across the round trip and land the new session |
| 19 | // there itself, skipping /continue and the pending join. So POST /signin |
| 20 | // takes it off the form and keeps it here instead (beginSignin), with the |
| 21 | // protections Docs', Sheets' and Slides' reviews asked for: a post without |
| 22 | // one forgets the page an earlier attempt kept, it comes off even when the |
| 23 | // body fails to parse, a plain /signin/local carries the kept page rather |
| 24 | // than overwriting it, /signed-out reads as no page, and Forget and Sign |
| 25 | // out clear it (signin.go). |
| 26 | // |
| 27 | // This is a port of Slides' cookie (b19fbda), which Astra reviewed on |
| 28 | // oficina/slides #14: sealed with a key of its own, bound to this origin |
| 29 | // by the purpose, with an issued and an expiry time checked on read, one |
| 30 | // cookie only, strict base64, and handoff.SafePath on the way in and the |
| 31 | // way out, so it can never name another site or loop into /signin. |
| 32 | |
| 33 | import ( |
| 34 | "bytes" |
| 35 | "crypto/sha256" |
| 36 | "encoding/base64" |
| 37 | "encoding/json" |
| 38 | "math" |
| 39 | "net/http" |
| 40 | "net/url" |
| 41 | "strings" |
| 42 | |
| 43 | "amadan.net/oficina/home/connect" |
| 44 | "amadan.net/oficina/home/handoff" |
| 45 | "amadan.net/oficina/home/handoff/seal" |
| 46 | rauth "amadan.net/rastrillo/rastrillo/auth" |
| 47 | ) |
| 48 | |
| 49 | // returnCookieAge is how long a remembered page lasts: a link opened |
| 50 | // after ten minutes, or in another browser, lands on the meeting list. |
| 51 | const returnCookieAge int64 = 600 |
| 52 | const returnCookieLimit = 4096 |
| 53 | |
| 54 | type returnIntent struct { |
| 55 | Path string `json:"path"` |
| 56 | Issued int64 `json:"issued"` |
| 57 | Expires int64 `json:"expires"` |
| 58 | } |
| 59 | |
| 60 | // returnCookieName is host-only, and __Host- prefixed wherever the origin |
| 61 | // is https. |
| 62 | func (a *app) returnCookieName() string { |
| 63 | if a.secure() { |
| 64 | return "__Host-calls_return" |
| 65 | } |
| 66 | return "calls_return" |
| 67 | } |
| 68 | |
| 69 | func (a *app) secure() bool { return strings.HasPrefix(a.cfg.Origin, "https://") } |
| 70 | |
| 71 | // returnSealer keeps the cookie independent of every other sealed value: |
| 72 | // its key is a domain-bound hash of the instance key. A changed key |
| 73 | // invalidates old return cookies, which is safe. |
| 74 | func (a *app) returnSealer() *seal.Sealer { |
| 75 | key := sha256.Sum256([]byte("oficina/calls return v1\x00" + a.cfg.instanceKey)) |
| 76 | s, err := seal.New(key[:], "oficina/calls") |
| 77 | if err != nil { |
| 78 | return nil |
| 79 | } |
| 80 | return s |
| 81 | } |
| 82 | |
| 83 | func (a *app) returnPurpose() string { return "calls.return.v1:" + a.cfg.Origin } |
| 84 | |
| 85 | // safeReturn is the request's return_to, when there is exactly one and |
| 86 | // it is a same-origin path (handoff.SafePath: no scheme, no host, no |
| 87 | // "//", no control characters, not /signin or /auth/*) and not an |
| 88 | // invitation, whose path is the capability itself. |
| 89 | func safeReturn(q url.Values) (string, bool) { |
| 90 | values, ok := q["return_to"] |
| 91 | if !ok || len(values) != 1 || !safeReturnPath(values[0]) { |
| 92 | return "", false |
| 93 | } |
| 94 | return values[0], true |
| 95 | } |
| 96 | |
| 97 | func safeReturnPath(p string) bool { |
| 98 | return handoff.SafePath(p) && !strings.HasPrefix(p, "/j/") && !signedOutPage(p) |
| 99 | } |
| 100 | |
| 101 | // signedOutPage reports whether path is /signed-out, with or without a |
| 102 | // query or fragment: a fresh sign-in must not land on "You're signed |
| 103 | // out", so it is no page to return to. |
| 104 | func signedOutPage(path string) bool { |
| 105 | u, err := url.Parse(path) |
| 106 | return err != nil || u.Path == "/signed-out" |
| 107 | } |
| 108 | |
| 109 | // requestedReturn is the return_to a sign-in GET carries, when it is |
| 110 | // exactly one same-origin path. |
| 111 | func requestedReturn(r *http.Request) (string, bool) { |
| 112 | q, err := url.ParseQuery(r.URL.RawQuery) |
| 113 | if err != nil { |
| 114 | return "", false |
| 115 | } |
| 116 | return safeReturn(q) |
| 117 | } |
| 118 | |
| 119 | // rememberSigninReturn keeps the page a sign-in began from in the return |
| 120 | // memory, when the door is opened afresh: a plain GET of /signin or |
| 121 | // /signin/local that is not one of the door's states. A plain /signin |
| 122 | // forgets one, so a page remembered by an earlier, abandoned attempt never |
| 123 | // wins over the one being made now (the landing is then /continue's own: |
| 124 | // the list, or /welcome). A plain /signin/local does not: connect sends |
| 125 | // people there (failed, unknown, "Connect my existing account") without |
| 126 | // return_to, mid-way through a sign-in that already remembered its page, |
| 127 | // so the door carries that page on its forms instead (st.ReturnTo), and |
| 128 | // the post remembers it again (beginSignin). The chooser's links carry |
| 129 | // return_to, so moving between ways keeps it. The confirm step and a |
| 130 | // refusal are drawn on /auth/*, and remember nothing. |
| 131 | func (a *app) rememberSigninReturn(w http.ResponseWriter, r *http.Request, st *rauth.SigninState) { |
| 132 | if r.Method != http.MethodGet || signinOutcome(r) || |
| 133 | (r.URL.Path != connect.SigninPath && r.URL.Path != connect.SigninLocalPath) { |
| 134 | return |
| 135 | } |
| 136 | path, ok := requestedReturn(r) |
| 137 | switch { |
| 138 | case ok: |
| 139 | a.rememberReturn(w, path) |
| 140 | case r.URL.Path == connect.SigninPath: |
| 141 | a.forgetReturn(w) |
| 142 | case st.ReturnTo == "": |
| 143 | if kept, ok := a.rememberedReturn(r); ok { |
| 144 | st.ReturnTo = kept |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // beginSignin is POST /signin, in both modes: rastrillo's Begin (behind |
| 150 | // gateBegin), with the destination kept Calls' way. |
| 151 | // |
| 152 | // The door's forms post return_to, and rastrillo would carry it across |
| 153 | // the round trip and land the new session there itself, skipping |
| 154 | // /continue, where a pending meeting join is taken and, with Home, |
| 155 | // connect's /auth/local/complete, where a pending account link resumes. |
| 156 | // So the posted return_to is remembered in the return memory and taken off |
| 157 | // the form before Begin reads it, and put back on Begin's redirect to the |
| 158 | // door (a problem, Sent, the Keymail continuation), so the next form there |
| 159 | // posts it again and the chooser's links keep it. |
| 160 | // |
| 161 | // With SigninScreen on, Begin never answers with a redirect off this |
| 162 | // origin: a Keymail address continues on the door (?continue=), whose |
| 163 | // meta refresh leaves for Keymail, so form-action stays 'self' (Safari |
| 164 | // applies it to a form submission's whole redirect chain). |
| 165 | func (a *app) beginSignin(next http.HandlerFunc) http.HandlerFunc { |
| 166 | return func(w http.ResponseWriter, r *http.Request) { |
| 167 | // Off the form whether or not the body parsed: Begin must never |
| 168 | // read a destination of its own. |
| 169 | to := "" |
| 170 | if r.ParseForm() == nil { |
| 171 | if v := r.PostForm["return_to"]; len(v) == 1 && safeReturnPath(v[0]) { |
| 172 | to = v[0] |
| 173 | } |
| 174 | } |
| 175 | if r.PostForm != nil { |
| 176 | r.PostForm.Del("return_to") |
| 177 | } |
| 178 | if r.Form != nil { |
| 179 | r.Form.Del("return_to") |
| 180 | } |
| 181 | // A post without one is a sign-in for /continue's own landing, so |
| 182 | // a page another tab remembered does not win. |
| 183 | if to != "" { |
| 184 | a.rememberReturn(w, to) |
| 185 | } else { |
| 186 | a.forgetReturn(w) |
| 187 | } |
| 188 | result := &bufferedResponse{header: make(http.Header)} |
| 189 | next(result, r) |
| 190 | if to != "" && result.status == http.StatusSeeOther { |
| 191 | result.header.Set("Location", withReturnTo(result.header.Get("Location"), to)) |
| 192 | } |
| 193 | result.replay(w) |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | // withReturnTo puts return_to on a redirect to the door, and leaves any |
| 198 | // other Location as it is. |
| 199 | func withReturnTo(location, to string) string { |
| 200 | u, err := url.Parse(location) |
| 201 | if err != nil || u.Scheme != "" || u.Host != "" || u.Path != connect.SigninPath { |
| 202 | return location |
| 203 | } |
| 204 | q := u.Query() |
| 205 | if q.Has("return_to") { |
| 206 | return location |
| 207 | } |
| 208 | q.Set("return_to", to) |
| 209 | u.RawQuery = q.Encode() |
| 210 | return u.String() |
| 211 | } |
| 212 | |
| 213 | // bufferedResponse holds a handler's answer so the caller can read it or |
| 214 | // change its Location before it is sent. |
| 215 | type bufferedResponse struct { |
| 216 | header http.Header |
| 217 | status int |
| 218 | body bytes.Buffer |
| 219 | } |
| 220 | |
| 221 | func (w *bufferedResponse) Header() http.Header { return w.header } |
| 222 | func (w *bufferedResponse) WriteHeader(status int) { |
| 223 | if w.status == 0 { |
| 224 | w.status = status |
| 225 | } |
| 226 | } |
| 227 | func (w *bufferedResponse) Write(p []byte) (int, error) { |
| 228 | if w.status == 0 { |
| 229 | w.WriteHeader(http.StatusOK) |
| 230 | } |
| 231 | return w.body.Write(p) |
| 232 | } |
| 233 | |
| 234 | // replay writes the held answer to w. |
| 235 | func (w *bufferedResponse) replay(to http.ResponseWriter) { |
| 236 | for name, values := range w.header { |
| 237 | for _, value := range values { |
| 238 | to.Header().Add(name, value) |
| 239 | } |
| 240 | } |
| 241 | if w.status == 0 { |
| 242 | w.status = http.StatusOK |
| 243 | } |
| 244 | to.WriteHeader(w.status) |
| 245 | _, _ = to.Write(w.body.Bytes()) |
| 246 | } |
| 247 | |
| 248 | func (a *app) rememberReturn(w http.ResponseWriter, path string) { |
| 249 | s := a.returnSealer() |
| 250 | if !safeReturnPath(path) || s == nil { |
| 251 | return |
| 252 | } |
| 253 | now := a.store.now().Unix() |
| 254 | if now <= 0 || now > math.MaxInt64-returnCookieAge { |
| 255 | return |
| 256 | } |
| 257 | raw, err := json.Marshal(returnIntent{Path: path, Issued: now, Expires: now + returnCookieAge}) |
| 258 | if err != nil { |
| 259 | return |
| 260 | } |
| 261 | sealed, err := s.Seal(a.returnPurpose(), raw) |
| 262 | if err != nil { |
| 263 | return |
| 264 | } |
| 265 | value := base64.RawURLEncoding.EncodeToString(sealed) |
| 266 | if len(value) > returnCookieLimit { |
| 267 | return |
| 268 | } |
| 269 | http.SetCookie(w, &http.Cookie{ |
| 270 | Name: a.returnCookieName(), Value: value, Path: "/", |
| 271 | MaxAge: int(returnCookieAge), HttpOnly: true, Secure: a.secure(), |
| 272 | SameSite: http.SameSiteLaxMode, |
| 273 | }) |
| 274 | } |
| 275 | |
| 276 | func (a *app) forgetReturn(w http.ResponseWriter) { |
| 277 | http.SetCookie(w, &http.Cookie{ |
| 278 | Name: a.returnCookieName(), Value: "", Path: "/", |
| 279 | MaxAge: -1, HttpOnly: true, Secure: a.secure(), |
| 280 | SameSite: http.SameSiteLaxMode, |
| 281 | }) |
| 282 | } |
| 283 | |
| 284 | // rememberedReturn reads the remembered page back, validated again: the |
| 285 | // cookie is a request header like any other. |
| 286 | func (a *app) rememberedReturn(r *http.Request) (string, bool) { |
| 287 | s := a.returnSealer() |
| 288 | if s == nil { |
| 289 | return "", false |
| 290 | } |
| 291 | count := 0 |
| 292 | for _, c := range r.Cookies() { |
| 293 | if c.Name == a.returnCookieName() { |
| 294 | count++ |
| 295 | } |
| 296 | } |
| 297 | if count != 1 { |
| 298 | return "", false |
| 299 | } |
| 300 | c, err := r.Cookie(a.returnCookieName()) |
| 301 | if err != nil || c.Value == "" || len(c.Value) > returnCookieLimit { |
| 302 | return "", false |
| 303 | } |
| 304 | sealed, err := base64.RawURLEncoding.Strict().DecodeString(c.Value) |
| 305 | if err != nil || base64.RawURLEncoding.EncodeToString(sealed) != c.Value { |
| 306 | return "", false |
| 307 | } |
| 308 | raw, err := s.Open(a.returnPurpose(), sealed) |
| 309 | if err != nil || len(raw) > returnCookieLimit { |
| 310 | return "", false |
| 311 | } |
| 312 | var intent returnIntent |
| 313 | if json.Unmarshal(raw, &intent) != nil { |
| 314 | return "", false |
| 315 | } |
| 316 | canonical, _ := json.Marshal(intent) |
| 317 | now := a.store.now().Unix() |
| 318 | if !bytes.Equal(raw, canonical) || intent.Issued <= 0 || intent.Issued > now || intent.Expires <= now || |
| 319 | intent.Expires <= intent.Issued || intent.Expires-intent.Issued > returnCookieAge || !safeReturnPath(intent.Path) { |
| 320 | return "", false |
| 321 | } |
| 322 | return intent.Path, true |
| 323 | } |
| 324 | |
| 325 | // requireSignedInPage is rastrillo/auth's RequireSession with return_to |
| 326 | // for a page: a signed-out GET or HEAD that asked for HTML is answered |
| 327 | // 303 /signin?return_to=<the page>. Everything else — a POST, and the |
| 328 | // room's stream, signal, ICE and info fetches, which never ask for HTML — |
| 329 | // goes to the guard and gets exactly today's answer, which is what |
| 330 | // room.js's readRefusal reads a sign-out from (spec §9.4). |
| 331 | // |
| 332 | // With Home configured every signed-out GET carries return_to, as |
| 333 | // homeReturnTo on main (bf4e24d, #22) already did: a fetch redirected to |
| 334 | // /signin?return_to=… has still gone somewhere else, which is what |
| 335 | // readRefusal reads, so the room's answer is unchanged there too. |
| 336 | func (a *app) requireSignedInPage(next http.Handler) http.Handler { |
| 337 | guarded := a.auth.RequireSession(next) |
| 338 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 339 | if (r.Method == http.MethodGet || r.Method == http.MethodHead) && (wantsHTML(r) || a.home != nil) { |
| 340 | if _, ok := a.auth.SessionFrom(r); !ok { |
| 341 | w.Header().Set("Cache-Control", "no-store") |
| 342 | http.Redirect(w, r, signinPath+"?return_to="+url.QueryEscape(r.URL.RequestURI()), http.StatusSeeOther) |
| 343 | return |
| 344 | } |
| 345 | } |
| 346 | guarded.ServeHTTP(w, r) |
| 347 | }) |
| 348 | } |
| 349 | |
| 350 | // signedOutAfter wraps rastrillo/auth's Signout, which ends the session |
| 351 | // and redirects to the sign-in form: a page that, with no word about |
| 352 | // what had just happened, read like an error. It goes to /signed-out, |
| 353 | // which says so. |
| 354 | func signedOutAfter(signout http.HandlerFunc) http.HandlerFunc { |
| 355 | return func(w http.ResponseWriter, r *http.Request) { |
| 356 | signout(&toSignedOut{ResponseWriter: w}, r) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | // toSignedOut rewrites Signout's Location, at the last moment a header is |
| 361 | // still settable. |
| 362 | type toSignedOut struct{ http.ResponseWriter } |
| 363 | |
| 364 | func (t *toSignedOut) WriteHeader(status int) { |
| 365 | if t.Header().Get("Location") == signinPath { |
| 366 | t.Header().Set("Location", "/signed-out") |
| 367 | } |
| 368 | t.ResponseWriter.WriteHeader(status) |
| 369 | } |
| 370 | |