oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1package sheets
2
3// Returning to the page a sign-in began from, across the door.
4//
5// Standalone, rastrillo carries it itself: the door's forms post return_to
6// (SigninState.ReturnTo), Begin keeps it across the mail or Keymail round
7// trip, and the new session lands there instead of SignedInPath.
8//
9// With Home configured that landing must not happen. Every local sign-in
10// lands on connect's /auth/local/complete (SignedInPath), because connect
11// resumes a pending account link from there, and only then is the person
12// sent on: connect lands them on LocalLandingPath, /sheets. So Sheets keeps
13// the page in its own sealed, ten-minute cookie beside connect's, and puts
14// it in place of /sheets there (App.homeLocalComplete). An Oficina ID
15// sign-in keeps its page in connect's own memory (SigninOficina).
16//
17// The remembered path is validated by handoff.SafePath (a same-origin path:
18// no scheme, no host, no //, no control characters), so it can never become
19// an off-site destination, and it authorizes nothing: not linking, and not
20// access to the sheet it names.
21
22import (
23 "bytes"
24 "encoding/base64"
25 "encoding/json"
26 "math"
27 "net/http"
28 "net/url"
29 "time"
30
31 "amadan.net/oficina/home/connect"
32 "amadan.net/oficina/home/handoff"
33 "amadan.net/rastrillo/rastrillo/auth"
34 "amadan.net/rastrillo/rastrillo/sessions"
35)
36
37const homeReturnCookie = "__Host-oficina-sheets-home-return"
38const homeReturnLimit = 4096
39const homeReturnLifetime = int64(600)
40
41// returnMemory is the page a Home instance's local sign-in began from, in
42// a sealed cookie under Home's DEK.
43type returnMemory struct {
44 sealer handoff.Sealer
45 origin string
46 now func() time.Time
47}
48
49type homeReturnIntent struct {
50 Path string `json:"path"`
51 Issued int64 `json:"issued"`
52 Expires int64 `json:"expires"`
53}
54
55func (n *returnMemory) purpose() string { return "sheets.home-return.v1:" + n.origin }
56
57// remember keeps path ("/" when it is not one safe local path, or is the
58// signed-out page, which would land a fresh sign-in on "You're signed
59// out").
60func (n *returnMemory) remember(w http.ResponseWriter, path string) bool {
61 if !handoff.SafePath(path) || signedOutPage(path) {
62 path = "/"
63 }
64 now := n.now().Unix()
65 if now <= 0 || now > math.MaxInt64-homeReturnLifetime {
66 return false
67 }
68 raw, err := json.Marshal(homeReturnIntent{path, now, now + homeReturnLifetime})
69 if err != nil {
70 return false
71 }
72 sealed, err := n.sealer.Seal(n.purpose(), raw)
73 if err != nil {
74 return false
75 }
76 value := base64.RawURLEncoding.EncodeToString(sealed)
77 if len(value) > homeReturnLimit {
78 return false
79 }
80 setReturnCookie(w, value, int(homeReturnLifetime))
81 return true
82}
83
84// path is the remembered page, "/" when there is none, or more than one,
85// or it cannot be read or has expired.
86func (n *returnMemory) path(r *http.Request) string {
87 count := 0
88 for _, c := range r.Cookies() {
89 if c.Name == homeReturnCookie {
90 count++
91 }
92 }
93 if count != 1 {
94 return "/"
95 }
96 cookie, err := r.Cookie(homeReturnCookie)
97 if err != nil || cookie.Value == "" || len(cookie.Value) > homeReturnLimit {
98 return "/"
99 }
100 sealed, err := base64.RawURLEncoding.Strict().DecodeString(cookie.Value)
101 if err != nil || base64.RawURLEncoding.EncodeToString(sealed) != cookie.Value {
102 return "/"
103 }
104 raw, err := n.sealer.Open(n.purpose(), sealed)
105 if err != nil || len(raw) > homeReturnLimit {
106 return "/"
107 }
108 var intent homeReturnIntent
109 if json.Unmarshal(raw, &intent) != nil {
110 return "/"
111 }
112 canonical, _ := json.Marshal(intent)
113 now := n.now().Unix()
114 if !bytes.Equal(raw, canonical) || intent.Issued <= 0 || intent.Issued > now || intent.Expires <= now ||
115 intent.Expires <= intent.Issued || intent.Expires-intent.Issued > homeReturnLifetime || !handoff.SafePath(intent.Path) {
116 return "/"
117 }
118 return intent.Path
119}
120
121// signedOutPage reports whether path is /signed-out, with or without a
122// query or fragment.
123func signedOutPage(path string) bool {
124 u, err := url.Parse(path)
125 return err != nil || u.Path == "/signed-out"
126}
127
128// forgetReturn clears the return memory: Forget and Sign out end what a
129// sign-in in progress had kept.
130func forgetReturn(w http.ResponseWriter) { setReturnCookie(w, "", -1) }
131
132func setReturnCookie(w http.ResponseWriter, value string, age int) {
133 http.SetCookie(w, &http.Cookie{Name: homeReturnCookie, Value: value, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: age})
134}
135
136// requestedReturn is the return_to a sign-in GET carries, when it is
137// exactly one same-origin path.
138func requestedReturn(r *http.Request) (string, bool) {
139 q, err := url.ParseQuery(r.URL.RawQuery)
140 if err != nil {
141 return "", false
142 }
143 values, ok := q["return_to"]
144 if !ok || len(values) != 1 || !handoff.SafePath(values[0]) {
145 return "", false
146 }
147 return values[0], true
148}
149
150// rememberSigninReturn keeps the page a sign-in began from in the return
151// memory, when the door is opened afresh with Home configured: a plain GET
152// of /signin or /signin/local that is not one of the door's states. A plain
153// /signin remembers the list, so a page remembered by an earlier, abandoned
154// attempt never wins over the one being made now. A plain /signin/local
155// does not: connect sends people there (failed, unknown, "Connect my
156// existing account") without return_to, mid-way through a sign-in that
157// already remembered its page, so the door carries that page on its forms
158// instead (st.ReturnTo), and the post remembers it again (beginSignin). The
159// chooser's links carry return_to, so moving between ways keeps it. The
160// confirm step and a refusal are drawn on /auth/*, and remember nothing.
161func (a *App) rememberSigninReturn(w http.ResponseWriter, r *http.Request, st *auth.SigninState) {
162 if a.returns == nil || r.Method != http.MethodGet || signinOutcome(r) ||
163 (r.URL.Path != connect.SigninPath && r.URL.Path != connect.SigninLocalPath) {
164 return
165 }
166 path, ok := requestedReturn(r)
167 switch {
168 case ok:
169 a.returns.remember(w, path)
170 case r.URL.Path == connect.SigninPath:
171 a.returns.remember(w, "/")
172 case st.ReturnTo == "":
173 if kept := a.returns.path(r); kept != "/" {
174 st.ReturnTo = kept
175 }
176 }
177}
178
179// beginSignin is POST /signin with Home configured: rastrillo's Begin, with
180// the destination kept Sheets' way.
181//
182// The door's forms post return_to, and rastrillo would carry it across the
183// round trip and land the new session there itself, skipping
184// /auth/local/complete, where connect resumes a pending account link. So
185// the posted return_to is remembered in the return memory and taken off the
186// form before Begin reads it, and put back on Begin's redirect to the door
187// (a problem, Sent, the Keymail continuation), so the next form there posts
188// it again and the chooser's links keep it.
189func (a *App) beginSignin(w http.ResponseWriter, r *http.Request) {
190 // Off the form whether or not the body parsed: Begin must never read a
191 // destination of its own.
192 to := ""
193 if r.ParseForm() == nil {
194 to = sessions.SafeReturnTo(r.PostForm.Get("return_to"), "")
195 }
196 if r.PostForm != nil {
197 r.PostForm.Del("return_to")
198 }
199 if r.Form != nil {
200 r.Form.Del("return_to")
201 }
202 // A post without one is a sign-in for the list (rastrillo's own rule),
203 // so a page another tab remembered does not win.
204 landing := to
205 if landing == "" {
206 landing = "/"
207 }
208 a.returns.remember(w, landing)
209 result := &bufferedResponse{header: make(http.Header)}
210 a.auth.Begin(result, r)
211 if to != "" && result.status == http.StatusSeeOther {
212 result.header.Set("Location", withReturnTo(result.header.Get("Location"), to))
213 }
214 result.replay(w)
215}
216
217// withReturnTo puts return_to on a redirect to the door, and leaves any
218// other Location as it is.
219func withReturnTo(location, to string) string {
220 u, err := url.Parse(location)
221 if err != nil || u.Scheme != "" || u.Host != "" || u.Path != connect.SigninPath {
222 return location
223 }
224 q := u.Query()
225 if q.Has("return_to") {
226 return location
227 }
228 q.Set("return_to", to)
229 u.RawQuery = q.Encode()
230 return u.String()
231}
232
233// bufferedResponse holds an auth handler's answer so the caller can change
234// its Location before it is sent.
235type bufferedResponse struct {
236 header http.Header
237 status int
238 body bytes.Buffer
239}
240
241func (w *bufferedResponse) Header() http.Header { return w.header }
242func (w *bufferedResponse) WriteHeader(status int) {
243 if w.status == 0 {
244 w.status = status
245 }
246}
247func (w *bufferedResponse) Write(p []byte) (int, error) {
248 if w.status == 0 {
249 w.WriteHeader(http.StatusOK)
250 }
251 return w.body.Write(p)
252}
253
254// replay writes the held answer to w.
255func (w *bufferedResponse) replay(to http.ResponseWriter) {
256 for name, values := range w.header {
257 for _, value := range values {
258 to.Header().Add(name, value)
259 }
260 }
261 if w.status == 0 {
262 w.status = http.StatusOK
263 }
264 to.WriteHeader(w.status)
265 _, _ = to.Write(w.body.Bytes())
266}
267