oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3// Return to the page you came from (shared chrome spec §9.4).
4//
5// requireSession used to answer a signed-out page request with rastrillo's
6// bare /signin, dropping the path: a link to a document, opened signed
7// out, landed on the index after sign-in. Now a signed-out GET is sent to
8// /signin?return_to=<the page>, and the page is carried to wherever the
9// magic link lands.
10//
11// It cannot ride the emailed link: rastrillo's auth lands a verified link
12// on one fixed SignedInPath and never reads return_to. So GET /signin
13// remembers it in a short-lived cookie, and the landing reads it back:
14//
15// - standalone, SignedInPath is /auth/landed (landed, below);
16// - with Home, a local link lands on connect's /auth/local/complete,
17// which goes to "/" (or /account/home mid-link); landedAfter swaps
18// that "/" for the remembered page. With Home and no local detour,
19// connect carries return_to itself through the Home exchange.
20//
21// The smart door (rastrillo's screen) posts return_to on its forms, and
22// rastrillo would carry it across the round trip and land the new session
23// there itself, skipping /auth/landed and, with Home, connect's
24// /auth/local/complete, where a pending account link resumes. So POST
25// /auth/begin takes it off the form and keeps it here instead
26// (beginSignin), with the protections Docs', Sheets', Slides', Calendar's
27// and Calls' reviews asked for: a post without one forgets the page an
28// earlier attempt kept, it comes off even when the body fails to parse, a
29// plain /signin/local carries the kept page rather than overwriting it,
30// /signed-out reads as no page, every landing spends it before it answers,
31// and Forget and Sign out clear it (signin.go).
32//
33// The cookie is SEALED (seal.PurposeReturn), bound to this origin, and
34// carries its own issue and expiry times, checked on read — a browser's
35// Max-Age alone is a suggestion (Astra on Slides #14, finding 3). Its
36// value is only ever a same-origin path that handoff.SafePath admits (no
37// scheme, no host, no "//", no control characters, not /signin or
38// /auth/*), checked when written and again when read, so it can never
39// send anyone off-site or into a sign-in loop.
40
41import (
42 "bytes"
43 "encoding/base64"
44 "encoding/json"
45 "math"
46 "net/http"
47 "net/url"
48 "strings"
49 "time"
50
51 "amadan.net/oficina/home/connect"
52 "amadan.net/oficina/home/handoff"
53 rauth "amadan.net/rastrillo/rastrillo/auth"
54
55 "amadan.net/oficina/memoria/internal/memoria/seal"
56)
57
58// landedPath is rastrillo's SignedInPath in standalone mode: where a
59// verified magic link lands, which then goes on to the remembered page.
60const landedPath = "/auth/landed"
61
62// returnCookieAge is how long a remembered page lasts: a link opened after
63// ten minutes, or in another browser, lands on the index. Intended.
64const returnCookieAge int64 = 600
65
66const returnCookieLimit = 4096
67
68type returnIntent struct {
69 Path string `json:"path"`
70 Origin string `json:"origin"`
71 Issued int64 `json:"issued"`
72 Expires int64 `json:"expires"`
73}
74
75func (a *app) secure() bool { return strings.HasPrefix(a.origin, "https://") }
76
77// returnCookieName is host-only, and __Host- prefixed wherever the origin
78// is https.
79func (a *app) returnCookieName() string {
80 if a.secure() {
81 return "__Host-memoria_return"
82 }
83 return "memoria_return"
84}
85
86func (a *app) now() time.Time {
87 if a.clock != nil {
88 return a.clock()
89 }
90 return time.Now()
91}
92
93// safeReturn is the request's return_to, when there is exactly one and it
94// is a same-origin path safeReturnPath admits.
95func safeReturn(q url.Values) (string, bool) {
96 values, ok := q["return_to"]
97 if !ok || len(values) != 1 || !safeReturnPath(values[0]) {
98 return "", false
99 }
100 return values[0], true
101}
102
103// safeReturnPath is handoff.SafePath (no scheme, no host, no "//", no
104// control characters, not /signin or /auth/*) and not /signed-out.
105func safeReturnPath(p string) bool {
106 return handoff.SafePath(p) && !signedOutPage(p)
107}
108
109// signedOutPage reports whether path is /signed-out, with or without a
110// query or fragment: a fresh sign-in must not land on "You’re signed
111// out", so it is no page to return to.
112func signedOutPage(path string) bool {
113 u, err := url.Parse(path)
114 return err != nil || u.Path == "/signed-out"
115}
116
117// requestedReturn is the return_to a sign-in GET carries, when it is
118// exactly one same-origin path.
119func requestedReturn(r *http.Request) (string, bool) {
120 q, err := url.ParseQuery(r.URL.RawQuery)
121 if err != nil {
122 return "", false
123 }
124 return safeReturn(q)
125}
126
127// rememberSigninReturn keeps the page a sign-in began from in the return
128// memory, when the door is opened afresh: a plain GET of /signin or
129// /signin/local that is not one of the door's states. A plain /signin
130// forgets one, so a page remembered by an earlier, abandoned attempt never
131// wins over the one being made now. A plain /signin/local does not:
132// connect sends people there (failed, unknown, "Connect my existing
133// account") without return_to, mid-way through a sign-in that already
134// remembered its page, so the door carries that page on its forms instead
135// (st.ReturnTo), and the post remembers it again (beginSignin). The
136// chooser's links carry return_to, so moving between ways keeps it. The
137// confirm step and a refusal are drawn on /auth/*, and remember nothing.
138func (a *app) rememberSigninReturn(w http.ResponseWriter, r *http.Request, st *rauth.SigninState) {
139 if r.Method != http.MethodGet || signinOutcome(r) ||
140 (r.URL.Path != connect.SigninPath && r.URL.Path != connect.SigninLocalPath) {
141 return
142 }
143 path, ok := requestedReturn(r)
144 switch {
145 case ok:
146 a.rememberReturn(w, path)
147 case r.URL.Path == connect.SigninPath:
148 a.forgetReturn(w)
149 case st.ReturnTo == "":
150 if kept, ok := a.rememberedReturn(r); ok {
151 st.ReturnTo = kept
152 }
153 }
154}
155
156// beginSignin is POST /auth/begin, in both modes, outermost: the
157// destination is kept Memoria's way, before beginGuard or Begin sees the
158// form.
159//
160// The door's forms post return_to, and rastrillo would carry it across
161// the round trip and land the new session there itself, skipping
162// /auth/landed and, with Home, connect's /auth/local/complete, where a
163// pending account link resumes. So the posted return_to is remembered in
164// the return memory and taken off the form before Begin reads it, and put
165// back on Begin's redirect to the door (a problem, Sent, the Keymail
166// continuation), so the next form there posts it again and the chooser's
167// links keep it. An owner and a stranger (beginGuard's AnswerAsSent) are
168// treated alike here.
169func (a *app) beginSignin(next http.HandlerFunc) http.HandlerFunc {
170 return func(w http.ResponseWriter, r *http.Request) {
171 // Off the form whether or not the body parsed: Begin must never
172 // read a destination of its own.
173 to := ""
174 if r.ParseForm() == nil {
175 if v := r.PostForm["return_to"]; len(v) == 1 && safeReturnPath(v[0]) {
176 to = v[0]
177 }
178 }
179 if r.PostForm != nil {
180 r.PostForm.Del("return_to")
181 }
182 if r.Form != nil {
183 r.Form.Del("return_to")
184 }
185 // A post without one is a sign-in for the landing's own "/", so a
186 // page another tab remembered does not win.
187 if to != "" {
188 a.rememberReturn(w, to)
189 } else {
190 a.forgetReturn(w)
191 }
192 result := &bufferedResponse{header: make(http.Header)}
193 next(result, r)
194 if to != "" && result.status == http.StatusSeeOther {
195 result.header.Set("Location", withReturnTo(result.header.Get("Location"), to))
196 }
197 result.replay(w)
198 }
199}
200
201// withReturnTo puts return_to on a redirect to the door, and leaves any
202// other Location as it is.
203func withReturnTo(location, to string) string {
204 u, err := url.Parse(location)
205 if err != nil || u.Scheme != "" || u.Host != "" || u.Path != connect.SigninPath {
206 return location
207 }
208 q := u.Query()
209 if q.Has("return_to") {
210 return location
211 }
212 q.Set("return_to", to)
213 u.RawQuery = q.Encode()
214 return u.String()
215}
216
217// bufferedResponse holds a handler's answer so the caller can read it or
218// change its Location before it is sent.
219type bufferedResponse struct {
220 header http.Header
221 status int
222 body bytes.Buffer
223}
224
225func (w *bufferedResponse) Header() http.Header { return w.header }
226func (w *bufferedResponse) WriteHeader(status int) {
227 if w.status == 0 {
228 w.status = status
229 }
230}
231func (w *bufferedResponse) Write(p []byte) (int, error) {
232 if w.status == 0 {
233 w.WriteHeader(http.StatusOK)
234 }
235 return w.body.Write(p)
236}
237
238// replay writes the held answer to w.
239func (w *bufferedResponse) replay(to http.ResponseWriter) {
240 for name, values := range w.header {
241 for _, value := range values {
242 to.Header().Add(name, value)
243 }
244 }
245 if w.status == 0 {
246 w.status = http.StatusOK
247 }
248 to.WriteHeader(w.status)
249 _, _ = to.Write(w.body.Bytes())
250}
251
252func (a *app) rememberReturn(w http.ResponseWriter, path string) {
253 if !safeReturnPath(path) || a.store == nil || a.store.sealer == nil {
254 return
255 }
256 now := a.now().Unix()
257 if now <= 0 || now > math.MaxInt64-returnCookieAge {
258 return
259 }
260 raw, err := json.Marshal(returnIntent{Path: path, Origin: a.origin, Issued: now, Expires: now + returnCookieAge})
261 if err != nil {
262 return
263 }
264 sealed, err := a.store.sealer.Seal(seal.PurposeReturn, raw)
265 if err != nil {
266 return
267 }
268 value := base64.RawURLEncoding.EncodeToString(sealed)
269 if len(value) > returnCookieLimit {
270 return
271 }
272 http.SetCookie(w, &http.Cookie{
273 Name: a.returnCookieName(), Value: value, Path: "/",
274 MaxAge: int(returnCookieAge), HttpOnly: true, Secure: a.secure(),
275 SameSite: http.SameSiteLaxMode,
276 })
277}
278
279func (a *app) forgetReturn(w http.ResponseWriter) {
280 http.SetCookie(w, &http.Cookie{
281 Name: a.returnCookieName(), Value: "", Path: "/",
282 MaxAge: -1, HttpOnly: true, Secure: a.secure(),
283 SameSite: http.SameSiteLaxMode,
284 })
285}
286
287// rememberedReturn reads the remembered page back, validated again: the
288// cookie is a request header like any other. Exactly one cookie, strict
289// base64, a seal that opens under this purpose, canonical JSON (nothing
290// added, nothing duplicated), this origin, and a live, bounded window.
291func (a *app) rememberedReturn(r *http.Request) (string, bool) {
292 if a.store == nil || a.store.sealer == nil {
293 return "", false
294 }
295 count := 0
296 value := ""
297 for _, c := range r.Cookies() {
298 if c.Name == a.returnCookieName() {
299 count++
300 value = c.Value
301 }
302 }
303 if count != 1 || value == "" || len(value) > returnCookieLimit {
304 return "", false
305 }
306 sealed, err := base64.RawURLEncoding.Strict().DecodeString(value)
307 if err != nil || base64.RawURLEncoding.EncodeToString(sealed) != value {
308 return "", false
309 }
310 raw, err := a.store.sealer.Open(seal.PurposeReturn, sealed)
311 if err != nil || len(raw) > returnCookieLimit {
312 return "", false
313 }
314 var intent returnIntent
315 if json.Unmarshal(raw, &intent) != nil {
316 return "", false
317 }
318 canonical, _ := json.Marshal(intent)
319 now := a.now().Unix()
320 if !bytes.Equal(raw, canonical) || intent.Origin != a.origin || intent.Issued <= 0 || intent.Issued > now ||
321 intent.Expires <= now || intent.Expires <= intent.Issued || intent.Expires-intent.Issued > returnCookieAge ||
322 !safeReturnPath(intent.Path) {
323 return "", false
324 }
325 return intent.Path, true
326}
327
328// landed serves GET /auth/landed: the remembered return_to, or the index.
329// The cookie is spent either way, and spent before the redirect is
330// written, or the clearing cookie would never be sent (Calls' /continue,
331// Fable on oficina/meet #46).
332func (a *app) landed(w http.ResponseWriter, r *http.Request) {
333 dest := "/"
334 if ret, ok := a.rememberedReturn(r); ok {
335 dest = ret
336 }
337 a.forgetReturn(w)
338 w.Header().Set("Cache-Control", "no-store")
339 http.Redirect(w, r, dest, http.StatusSeeOther)
340}
341
342// landedAfter wraps connect's local-link completion (Home mode): where it
343// would land on the root, it lands on the remembered page instead. Any
344// other destination — /account/home in the middle of linking an account —
345// is connect's decision and is left alone. The cookie is spent either way.
346func (a *app) landedAfter(complete http.HandlerFunc) http.HandlerFunc {
347 return func(w http.ResponseWriter, r *http.Request) {
348 ret, ok := a.rememberedReturn(r)
349 a.forgetReturn(w)
350 rw := &rewriteLocation{ResponseWriter: w, from: "/"}
351 if ok {
352 rw.to = ret
353 }
354 complete(rw, r)
355 }
356}
357
358// spentOnMint wraps a Home route that may finish a sign-in without a
359// local landing (connect's /auth/finish, and the member choice's POST):
360// when its answer mints a session, the page a local sign-in kept is
361// spent on that same response, as every landing spends it (Fable on
362// oficina/memoria #49). An answer that sends the browser on to the
363// choice, or "Connect my existing account" to the email-only door, mints
364// no session, so it keeps the page: that sign-in is not over, and still
365// needs it. (A Location check for those two was written and deleted: no
366// minting answer goes there, so it could not fail.)
367func (a *app) spentOnMint(next http.HandlerFunc) http.HandlerFunc {
368 return func(w http.ResponseWriter, r *http.Request) {
369 result := &bufferedResponse{header: make(http.Header)}
370 next(result, r)
371 if a.auth != nil && mintsSession(result.header, a.sessionCookie()) {
372 a.forgetReturn(result)
373 }
374 result.replay(w)
375 }
376}
377
378// mintsSession reports whether h sets the named session cookie to a value.
379func mintsSession(h http.Header, name string) bool {
380 for _, c := range (&http.Response{Header: h}).Cookies() {
381 if c.Name == name && c.MaxAge >= 0 && c.Value != "" {
382 return true
383 }
384 }
385 return false
386}
387
388// rewriteLocation swaps one Location for another at the last moment a
389// header is still settable. to == "" leaves it alone.
390type rewriteLocation struct {
391 http.ResponseWriter
392 from, to string
393}
394
395func (rw *rewriteLocation) WriteHeader(status int) {
396 if rw.to != "" && rw.Header().Get("Location") == rw.from {
397 rw.Header().Set("Location", rw.to)
398 }
399 rw.ResponseWriter.WriteHeader(status)
400}
401
402func (rw *rewriteLocation) Write(b []byte) (int, error) {
403 return rw.ResponseWriter.Write(b)
404}
405
406// signedOutAfter wraps rastrillo's Signout (standalone), which ends the
407// session and redirects to the sign-in form: a page that, with no word
408// about what just happened, read like an error (polish audit §B5). It
409// goes to /signed-out instead, which says so. (With Home, connect's
410// Signout chains to id.* and id.* returns the browser to /signed-out.)
411func signedOutAfter(signout http.HandlerFunc) http.HandlerFunc {
412 return func(w http.ResponseWriter, r *http.Request) {
413 signout(&rewriteLocation{ResponseWriter: w, from: signinPath, to: "/signed-out"}, r)
414 }
415}
416