| 1 | package connect |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "path" |
| 10 | "strings" |
| 11 | |
| 12 | "amadan.net/oficina/home/handoff" |
| 13 | "amadan.net/oficina/home/handoff/seal" |
| 14 | ) |
| 15 | |
| 16 | const LocalCompletePath = localLinkCompletePath |
| 17 | |
| 18 | type RoutesConfig struct { |
| 19 | LocalLandingPath string |
| 20 | Namespace, Origin, Issuer, SessionCookie string |
| 21 | FormPolicy string |
| 22 | DEK []byte |
| 23 | ReadSession func(*http.Request) (*Session, error) |
| 24 | SignOut func(http.ResponseWriter, *http.Request) |
| 25 | LocalSignin http.HandlerFunc |
| 26 | Protect func(http.Handler) http.Handler |
| 27 | Render func(http.ResponseWriter, *http.Request, string, string, int) |
| 28 | // ForgetPath is optional: where the app mounted rastrillo auth's |
| 29 | // Forget (auth.Config.ForgetPath, "/signin/forget" by default). With it |
| 30 | // set, the signed-out page offers "Forget me on this device", a POST |
| 31 | // there (PageData.ForgetAction). It must be an absolute local path with |
| 32 | // no query. The form is a plain same-origin POST with no token, so it |
| 33 | // passes csrf.SameOrigin (Protect, and Forget's own check) and needs no |
| 34 | // exemption in Middleware. Empty offers none, as before. |
| 35 | ForgetPath string |
| 36 | } |
| 37 | |
| 38 | type Routes struct { |
| 39 | bridge *Bridge |
| 40 | navigation *localLinkNavigation |
| 41 | cfg RoutesConfig |
| 42 | } |
| 43 | |
| 44 | func NewRoutes(b *Bridge, c RoutesConfig) (*Routes, error) { |
| 45 | if c.ForgetPath != "" && !localPath(c.ForgetPath) { |
| 46 | return nil, errors.New("home connect: invalid routes") |
| 47 | } |
| 48 | if (c.LocalLandingPath != "" && !handoff.SafePath(c.LocalLandingPath)) || b == nil || c.ReadSession == nil || c.SignOut == nil || c.LocalSignin == nil || c.Protect == nil || c.Render == nil || c.Origin != b.origin || c.Issuer != b.issuer || c.SessionCookie != b.sessionCookie || c.Namespace != b.namespace || sha256.Sum256(c.DEK) != b.keyHash { |
| 49 | return nil, errors.New("home connect: invalid routes") |
| 50 | } |
| 51 | s, err := seal.New(c.DEK, c.Namespace) |
| 52 | if err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | n := newLocalLinkNavigation(s, c) |
| 56 | if n == nil { |
| 57 | return nil, errors.New("home connect: invalid navigation") |
| 58 | } |
| 59 | n.now = b.now |
| 60 | n.resume = b.resumeLink |
| 61 | b.returnPath = n.returnPath |
| 62 | b.rememberUnknown = n.rememberUnknown |
| 63 | return &Routes{bridge: b, navigation: n, cfg: c}, nil |
| 64 | } |
| 65 | |
| 66 | // localPath is a path on this origin, with nothing a form action could take |
| 67 | // elsewhere: absolute, no scheme or host, no query or fragment, clean. |
| 68 | func localPath(p string) bool { |
| 69 | u, err := url.Parse(p) |
| 70 | return err == nil && u.Scheme == "" && u.Host == "" && u.User == nil && u.RawQuery == "" && u.Fragment == "" && !u.ForceQuery && |
| 71 | u.Path == p && strings.HasPrefix(p, "/") && !strings.HasPrefix(p, "//") && !strings.ContainsAny(p, "\\\x00") && path.Clean(p) == p |
| 72 | } |
| 73 | |
| 74 | type forgetKey struct{} |
| 75 | |
| 76 | func cookieCount(r *http.Request, name string) int { |
| 77 | n := 0 |
| 78 | for _, c := range r.Cookies() { |
| 79 | if c.Name == name { |
| 80 | n++ |
| 81 | } |
| 82 | } |
| 83 | return n |
| 84 | } |
| 85 | |
| 86 | // Only the signed assertion callback bypasses the application's CSRF guard. |
| 87 | func (h *Routes) Middleware(next http.Handler) http.Handler { |
| 88 | checked := h.cfg.Protect(next) |
| 89 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 90 | policy := h.cfg.FormPolicy |
| 91 | if policy == "" { |
| 92 | policy = FormPolicy(h.cfg.Issuer) |
| 93 | } |
| 94 | w.Header().Set("Content-Security-Policy", policy) |
| 95 | if r.Host != strings.TrimPrefix(h.cfg.Origin, "https://") { |
| 96 | http.NotFound(w, r) |
| 97 | return |
| 98 | } |
| 99 | // The assertion callback verifies its browser-bound assertion, and |
| 100 | // the native exchange refuses anything a browser sends; neither |
| 101 | // can pass a same-origin check, and neither needs one. |
| 102 | if r.Method == http.MethodPost && (r.URL.Path == handoff.CallbackPath || r.URL.Path == NativeExchangePath) { |
| 103 | next.ServeHTTP(w, r) |
| 104 | return |
| 105 | } |
| 106 | if cookieCount(r, h.cfg.SessionCookie) > 1 { |
| 107 | h.bridge.fail(w, r, http.StatusBadRequest) |
| 108 | return |
| 109 | } |
| 110 | checked.ServeHTTP(w, r) |
| 111 | }) |
| 112 | } |
| 113 | |
| 114 | func FormPolicy(issuer string) string { |
| 115 | return "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self' " + issuer |
| 116 | } |
| 117 | |
| 118 | func (h *Routes) LocalGuard(next http.HandlerFunc) http.HandlerFunc { |
| 119 | return func(w http.ResponseWriter, r *http.Request) { |
| 120 | if cookieCount(r, h.cfg.SessionCookie) > 1 || cookieCount(r, "__Host-rastrillo_pending") > 1 { |
| 121 | h.bridge.fail(w, r, http.StatusBadRequest) |
| 122 | return |
| 123 | } |
| 124 | next(w, r) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | // signedIn reports a live, signed-in app session: exactly one session |
| 129 | // cookie, which ReadSession resolves to a person who signed in, through |
| 130 | // Home (IsHomeDerived and not Expired) or a local link (magiclink, |
| 131 | // keymail). An ambiguous pair or a revoked cookie is not one, and neither |
| 132 | // is any other method: Calls' anonymous per-meeting guests ("guest") are |
| 133 | // sessions but not sign-ins, and sending one to the root instead of the |
| 134 | // door ends on a 404 (the #74 review, finding 3). An unknown method gets the |
| 135 | // door (SigninDoor) or the exchange (SigninOficina), as if signed out. |
| 136 | // |
| 137 | // It reads the session cookie and nothing else. An app whose signed-in |
| 138 | // routes refuse some live sessions (a removed member, a revoked share) must |
| 139 | // end or hide such a session before SigninDoor or SigninOficina, or the two |
| 140 | // redirect to each other forever (Astra on Docs #65, Sheets #39). |
| 141 | func (h *Routes) signedIn(r *http.Request) bool { |
| 142 | if cookieCount(r, h.cfg.SessionCookie) != 1 { |
| 143 | return false |
| 144 | } |
| 145 | s, err := h.cfg.ReadSession(r) |
| 146 | if err != nil || s == nil || s.Subject == "" { |
| 147 | return false |
| 148 | } |
| 149 | if IsHomeDerived(s.Method) { |
| 150 | return !Expired(*s, h.bridge.now()) |
| 151 | } |
| 152 | return s.Method == "magiclink" || s.Method == "keymail" |
| 153 | } |
| 154 | |
| 155 | // SignedOut is GET /signed-out, where Signout lands: Render with state |
| 156 | // "signedout". With RoutesConfig.ForgetPath set, PageFor on that request |
| 157 | // carries it as PageData.ForgetAction, the page's second form, "Forget me |
| 158 | // on this device". |
| 159 | func (h *Routes) SignedOut(w http.ResponseWriter, r *http.Request) { |
| 160 | if h.cfg.ForgetPath != "" { |
| 161 | r = r.WithContext(context.WithValue(r.Context(), forgetKey{}, h.cfg.ForgetPath)) |
| 162 | } |
| 163 | h.cfg.Render(w, r, "signedout", "", http.StatusOK) |
| 164 | } |
| 165 | func (h *Routes) LocalComplete(w http.ResponseWriter, r *http.Request) { h.navigation.Complete(w, r) } |
| 166 | func (h *Routes) fresh(r *http.Request) bool { |
| 167 | if cookieCount(r, h.cfg.SessionCookie) != 1 { |
| 168 | return false |
| 169 | } |
| 170 | s, err := h.cfg.ReadSession(r) |
| 171 | if err != nil || s == nil { |
| 172 | return false |
| 173 | } |
| 174 | _, ok := FreshLocal(*s, h.bridge.now()) |
| 175 | return ok |
| 176 | } |
| 177 | func (h *Routes) Account(w http.ResponseWriter, r *http.Request) { |
| 178 | if !h.fresh(r) { |
| 179 | h.navigation.Begin(w, r) |
| 180 | return |
| 181 | } |
| 182 | h.bridge.LinkPage(w, r) |
| 183 | } |
| 184 | func (h *Routes) LinkStart(w http.ResponseWriter, r *http.Request) { |
| 185 | if !h.fresh(r) { |
| 186 | w.Header().Set("Cache-Control", "no-store") |
| 187 | http.Redirect(w, r, "/account/home", http.StatusSeeOther) |
| 188 | return |
| 189 | } |
| 190 | h.bridge.LinkStart(w, r) |
| 191 | } |
| 192 | func (h *Routes) ConfirmPost(w http.ResponseWriter, r *http.Request) { |
| 193 | localNavigationCookie(w, homeReturnCookie, "", -1) |
| 194 | h.bridge.ConfirmPost(w, r) |
| 195 | } |
| 196 | |
| 197 | // Signout ends the app session and clears the hand-off cookies. With Home |
| 198 | // configured it then hands the same POST on to {Issuer}/signout, which ends |
| 199 | // the id.* session and returns the browser to this origin's /signed-out (spec |
| 200 | // shared-chrome §9.5). Ending only the app session left "Sign in" on the |
| 201 | // signed-out page passing silently through the live 30-day id.* session. |
| 202 | // |
| 203 | // - 307, not 303, so the hop stays a POST. A GET sign-out is one any link |
| 204 | // or <img> can trigger; id.* ignores GET. |
| 205 | // - The browser sends "Origin: null" on the redirected POST, so id.* admits |
| 206 | // it by Referer. This response sets the policy that makes Referer exactly |
| 207 | // this origin. A page that itself sends Referrer-Policy: no-referrer still |
| 208 | // strips it (no redirect can restore it), and its sign-out lands on id.*'s |
| 209 | // "Finish signing out" page: recoverable, but a page with the account menu |
| 210 | // should use strict-origin instead. |
| 211 | // - FormPolicy already names the issuer in form-action, which browsers |
| 212 | // enforce on the redirect target of a form submission. An app that |
| 213 | // supplies its own policy must keep the issuer there. |
| 214 | // |
| 215 | // Without an issuer (never the case for Routes built by NewRoutes) it ends |
| 216 | // here, as before. |
| 217 | func (h *Routes) Signout(w http.ResponseWriter, r *http.Request) { |
| 218 | h.cfg.SignOut(w, r) |
| 219 | // A pending member choice ends with the browser's sign-out: its row, |
| 220 | // not only its cookie. Best effort; the proof expires in ten minutes. |
| 221 | if secret, present, ok := homeCookie(r, homeChoiceCookie); present && ok && h.bridge.links != nil { |
| 222 | _ = h.bridge.links.DropChoice(r.Context(), secret) |
| 223 | } |
| 224 | for _, name := range []string{homeInitCookie, homeProofCookie, homeChoiceCookie, localLinkNavigationCookie, homeReturnCookie, "__Host-oficina-assertion-pending", "__Host-oficina-assertion-inbox"} { |
| 225 | localNavigationCookie(w, name, "", -1) |
| 226 | } |
| 227 | w.Header().Set("Cache-Control", "no-store") |
| 228 | if h.cfg.Issuer == "" { |
| 229 | http.Redirect(w, r, "/signed-out", http.StatusSeeOther) |
| 230 | return |
| 231 | } |
| 232 | w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") |
| 233 | http.Redirect(w, r, h.cfg.Issuer+"/signout", http.StatusTemporaryRedirect) |
| 234 | } |
| 235 | |