oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package connect
2
3import (
4 "bytes"
5 "encoding/base64"
6 "encoding/json"
7 "errors"
8 "math"
9 "net/http"
10 "net/url"
11 "time"
12
13 "amadan.net/oficina/home/handoff"
14)
15
16const localLinkNavigationCookie = "__Host-oficina-local-link-navigation"
17const localLinkNavigationLifetime = int64(600)
18const localLinkNavigationLimit = 1024
19const localLinkCompletePath = "/auth/local/complete"
20
21type localLinkMarker struct {
22 Version int `json:"v"`
23 Action string `json:"action"`
24 Issued int64 `json:"issued"`
25 Expires int64 `json:"expires"`
26}
27
28type localLinkNavigation struct {
29 landingPath string
30 sealer handoff.Sealer
31 sessionCookie string
32 readSession func(*http.Request) (*Session, error)
33 namespace string
34 fail func(http.ResponseWriter, *http.Request, int)
35 origin, host string
36 now func() time.Time
37 // resume begins the link for the actual fresh local session and
38 // redirects to the Home freshness check, or reports false having
39 // written nothing (Bridge.resumeLink).
40 resume func(http.ResponseWriter, *http.Request) bool
41}
42
43// The marker's two actions. linkStart is the account menu's: after local
44// sign-in, show the Connect page. linkResume is remembered when an Oficina
45// assertion arrived that this app has no link for: after local sign-in,
46// begin the link at once, so the person lands on the confirm step rather
47// than hunting for the menu item.
48const (
49 linkStart = "link-start"
50 linkResume = "link-resume"
51)
52
53func newLocalLinkNavigation(sealer handoff.Sealer, c RoutesConfig) *localLinkNavigation {
54 u, err := url.Parse(c.Origin)
55 if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || sealer == nil || c.ReadSession == nil {
56 return nil
57 }
58 landing := c.LocalLandingPath
59 if landing == "" {
60 landing = "/"
61 }
62 if !handoff.SafePath(landing) {
63 return nil
64 }
65 return &localLinkNavigation{landingPath: landing, sealer: sealer, sessionCookie: c.SessionCookie, readSession: c.ReadSession, namespace: c.Namespace, origin: c.Origin, host: u.Host, now: time.Now, fail: func(w http.ResponseWriter, r *http.Request, status int) { c.Render(w, r, "failed", "", status) }}
66}
67
68func localNavigationCookie(w http.ResponseWriter, name, value string, age int) {
69 http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: age})
70}
71
72func (n *localLinkNavigation) purpose() string {
73 return n.namespace + ".local-link-navigation.v1:" + n.origin
74}
75
76func (n *localLinkNavigation) guard(w http.ResponseWriter, r *http.Request, path string) bool {
77 w.Header().Set("Cache-Control", "no-store")
78 if r.Method != http.MethodGet {
79 w.Header().Set("Allow", http.MethodGet)
80 n.fail(w, r, http.StatusMethodNotAllowed)
81 return false
82 }
83 if r.Host != n.host || r.URL.Path != path || r.URL.RawQuery != "" {
84 http.Redirect(w, r, "/", http.StatusSeeOther)
85 return false
86 }
87 return true
88}
89
90// Begin abandons browser pointers to an old link. Rotation and freshness also
91// invalidate its binding; clearing cookies does not consume database rows.
92// A cross-site top-level GET may abandon a flow, but cannot create a link.
93func (n *localLinkNavigation) Begin(w http.ResponseWriter, r *http.Request) {
94 localNavigationCookie(w, localLinkNavigationCookie, "", -1)
95 if !n.guard(w, r, "/account/home") {
96 return
97 }
98 localNavigationCookie(w, homeInitCookie, "", -1)
99 localNavigationCookie(w, homeProofCookie, "", -1)
100 encoded, err := n.seal(linkStart)
101 if errors.Is(err, errNavigationClock) {
102 http.Redirect(w, r, "/", http.StatusSeeOther)
103 return
104 }
105 if err != nil {
106 n.fail(w, r, http.StatusServiceUnavailable)
107 return
108 }
109 localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime))
110 http.Redirect(w, r, linkStepUpPath, http.StatusSeeOther)
111}
112
113// linkStepUpPath is where linking sends a person to sign in again: the
114// email-only door, marked as a step-up. The mark is what keeps it local
115// past the first page. rastrillo sends every outcome, chooser link and
116// Forget to auth.Config.SigninPath, which is SigninPath once an app is on
117// the smart door; reauth=1 rides all of them (and Begin's form), so the
118// door it lands on still offers no Oficina ID (OficinaHref, auth's
119// offers) and SigninDoor's signed-in shortcut does not bounce the person
120// to "/" before they have signed in again. The copy is rastrillo's
121// "Sign in again to continue", which is what linking asks.
122const linkStepUpPath = SigninLocalPath + "?reauth=1"
123
124var (
125 errNavigationClock = errors.New("home connect: navigation clock unusable")
126 errNavigationSeal = errors.New("home connect: navigation marker unavailable")
127)
128
129// seal returns the encoded marker for action.
130func (n *localLinkNavigation) seal(action string) (string, error) {
131 now := n.now().Unix()
132 if now <= 0 || now > math.MaxInt64-localLinkNavigationLifetime {
133 return "", errNavigationClock
134 }
135 payload, _ := json.Marshal(localLinkMarker{Version: 1, Action: action, Issued: now, Expires: now + localLinkNavigationLifetime})
136 sealed, err := n.sealer.Seal(n.purpose(), payload)
137 if err != nil {
138 return "", errNavigationSeal
139 }
140 encoded := base64.RawURLEncoding.EncodeToString(sealed)
141 if len(encoded) > localLinkNavigationLimit {
142 return "", errNavigationSeal
143 }
144 return encoded, nil
145}
146
147// rememberUnknown records, in the same sealed short-lived marker, that an
148// Oficina assertion arrived with no link here. It carries no identity: the
149// link is still bound to a fresh Home assertion and an explicit confirm, as
150// from the menu. Failing to seal costs only the shortcut.
151func (n *localLinkNavigation) rememberUnknown(w http.ResponseWriter) {
152 if encoded, err := n.seal(linkResume); err == nil {
153 localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime))
154 }
155}
156
157// marker returns the action of the one valid, unexpired marker, or "".
158func (n *localLinkNavigation) marker(r *http.Request, now int64) string {
159 value := ""
160 count := 0
161 for _, c := range r.Cookies() {
162 if c.Name == localLinkNavigationCookie {
163 count++
164 value = c.Value
165 }
166 }
167 if count != 1 || value == "" || len(value) > localLinkNavigationLimit {
168 return ""
169 }
170 sealed, err := base64.RawURLEncoding.Strict().DecodeString(value)
171 if err != nil || base64.RawURLEncoding.EncodeToString(sealed) != value {
172 return ""
173 }
174 payload, err := n.sealer.Open(n.purpose(), sealed)
175 if err != nil || len(payload) > localLinkNavigationLimit {
176 return ""
177 }
178 var marker localLinkMarker
179 if json.Unmarshal(payload, &marker) != nil {
180 return ""
181 }
182 // Only this helper writes the payload. Exact re-encoding excludes duplicate
183 // and unknown fields, alternate numbers, and any trailing JSON value.
184 canonical, _ := json.Marshal(marker)
185 if !bytes.Equal(payload, canonical) {
186 return ""
187 }
188 if marker.Version == 1 && (marker.Action == linkStart || marker.Action == linkResume) && marker.Issued > 0 && marker.Issued <= now && now < marker.Expires && marker.Expires > marker.Issued && marker.Expires-marker.Issued <= localLinkNavigationLifetime {
189 return marker.Action
190 }
191 return ""
192}
193
194// Complete reads the newly presented session after local verification. It
195// never confirms a link, and never treats a Home mint as local proof. With
196// a remembered unknown assertion it begins one, exactly as the Connect
197// button would, which is bound to this fresh session and still needs a
198// fresh Home assertion and an explicit same-origin confirm. A copied marker
199// can at most repeat that navigation. An expired marker is ignored: the
200// person lands as from any sign-in, with the menu item still on offer.
201func (n *localLinkNavigation) Complete(w http.ResponseWriter, r *http.Request) {
202 localNavigationCookie(w, localLinkNavigationCookie, "", -1)
203 if !n.guard(w, r, localLinkCompletePath) {
204 return
205 }
206 now := n.now()
207 target := n.landingPath
208 if action := n.marker(r, now.Unix()); action != "" {
209 count := 0
210 for _, c := range r.Cookies() {
211 if c.Name == n.sessionCookie {
212 count++
213 }
214 }
215 if count == 1 {
216 if session, err := n.readSession(r); err == nil && session != nil {
217 if _, fresh := FreshLocal(*session, now); fresh {
218 if action == linkResume && n.resume != nil && n.resume(w, r) {
219 return
220 }
221 target = "/account/home"
222 }
223 }
224 }
225 }
226 http.Redirect(w, r, target, http.StatusSeeOther)
227}
228