oficina / calendar Public

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

Plain git — no account needed to clone.

Download

Download this file

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