package connect import ( "crypto/sha256" "errors" "net/http" "net/url" "strings" "amadan.net/oficina/home/handoff" "amadan.net/oficina/home/handoff/seal" ) const LocalCompletePath = localLinkCompletePath type RoutesConfig struct { LocalLandingPath string Namespace, Origin, Issuer, SessionCookie string FormPolicy string DEK []byte ReadSession func(*http.Request) (*Session, error) SignOut func(http.ResponseWriter, *http.Request) LocalSignin http.HandlerFunc Protect func(http.Handler) http.Handler Render func(http.ResponseWriter, *http.Request, string, string, int) } type Routes struct { bridge *Bridge navigation *localLinkNavigation cfg RoutesConfig } func NewRoutes(b *Bridge, c RoutesConfig) (*Routes, error) { 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 { return nil, errors.New("home connect: invalid routes") } s, err := seal.New(c.DEK, c.Namespace) if err != nil { return nil, err } n := newLocalLinkNavigation(s, c) if n == nil { return nil, errors.New("home connect: invalid navigation") } n.now = b.now b.returnPath = n.returnPath return &Routes{bridge: b, navigation: n, cfg: c}, nil } func cookieCount(r *http.Request, name string) int { n := 0 for _, c := range r.Cookies() { if c.Name == name { n++ } } return n } // Only the signed assertion callback bypasses the application's CSRF guard. func (h *Routes) Middleware(next http.Handler) http.Handler { checked := h.cfg.Protect(next) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { policy := h.cfg.FormPolicy if policy == "" { policy = FormPolicy(h.cfg.Issuer) } w.Header().Set("Content-Security-Policy", policy) if r.Host != strings.TrimPrefix(h.cfg.Origin, "https://") { http.NotFound(w, r) return } if r.Method == http.MethodPost && r.URL.Path == handoff.CallbackPath { next.ServeHTTP(w, r) return } if cookieCount(r, h.cfg.SessionCookie) > 1 { h.bridge.fail(w, r, http.StatusBadRequest) return } checked.ServeHTTP(w, r) }) } func FormPolicy(issuer string) string { return "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self' " + issuer } func (h *Routes) LocalGuard(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if cookieCount(r, h.cfg.SessionCookie) > 1 || cookieCount(r, "__Host-rastrillo_pending") > 1 { h.bridge.fail(w, r, http.StatusBadRequest) return } next(w, r) } } func (h *Routes) Signin(w http.ResponseWriter, r *http.Request) { q, err := url.ParseQuery(r.URL.RawQuery) if err != nil { h.bridge.fail(w, r, http.StatusBadRequest) return } if q.Has("sent") || q.Has("err") || q.Has("force") { h.cfg.LocalSignin(w, r) return } path := "/" if values, ok := q["return_to"]; ok && len(values) == 1 && handoff.SafePath(values[0]) { path = values[0] } // Already signed in: go where the person was headed, with no form and // no second exchange (spec shared-chrome §9.4). SafePath refuses // /signin and /auth/*, so this cannot loop. if h.signedIn(r) { w.Header().Set("Cache-Control", "no-store") http.Redirect(w, r, path, http.StatusSeeOther) return } if !h.navigation.rememberReturn(w, path) { h.bridge.fail(w, r, http.StatusServiceUnavailable) return } w.Header().Set("Cache-Control", "no-store") http.Redirect(w, r, handoff.StartPath+"?"+url.Values{"return_to": {path}}.Encode(), http.StatusSeeOther) } // signedIn reports a live, signed-in app session: exactly one session // cookie, which ReadSession resolves to a person who signed in, through // Home (HomeMethod) or a local link (magiclink, keymail). An ambiguous // pair or a revoked cookie is not one, and neither is any other method: // Calls' anonymous per-meeting guests ("guest") are sessions but not // sign-ins, and sending one to the root instead of the exchange ends on a // 404 (the #74 review, finding 3). An unknown method falls back to the // exchange, which is what /signin did before this check existed. func (h *Routes) signedIn(r *http.Request) bool { if cookieCount(r, h.cfg.SessionCookie) != 1 { return false } s, err := h.cfg.ReadSession(r) if err != nil || s == nil || s.Subject == "" { return false } switch s.Method { case HomeMethod, "magiclink", "keymail": return true } return false } func (h *Routes) SignedOut(w http.ResponseWriter, r *http.Request) { h.cfg.Render(w, r, "signedout", "", http.StatusOK) } func (h *Routes) LocalComplete(w http.ResponseWriter, r *http.Request) { h.navigation.Complete(w, r) } func (h *Routes) fresh(r *http.Request) bool { if cookieCount(r, h.cfg.SessionCookie) != 1 { return false } s, err := h.cfg.ReadSession(r) if err != nil || s == nil { return false } _, ok := FreshLocal(*s, h.bridge.now()) return ok } func (h *Routes) Account(w http.ResponseWriter, r *http.Request) { if !h.fresh(r) { h.navigation.Begin(w, r) return } h.bridge.LinkPage(w, r) } func (h *Routes) LinkStart(w http.ResponseWriter, r *http.Request) { if !h.fresh(r) { w.Header().Set("Cache-Control", "no-store") http.Redirect(w, r, "/account/home", http.StatusSeeOther) return } h.bridge.LinkStart(w, r) } func (h *Routes) ConfirmPost(w http.ResponseWriter, r *http.Request) { localNavigationCookie(w, homeReturnCookie, "", -1) h.bridge.ConfirmPost(w, r) } // Signout ends the app session and clears the hand-off cookies. With Home // configured it then hands the same POST on to {Issuer}/signout, which ends // the id.* session and returns the browser to this origin's /signed-out (spec // shared-chrome §9.5). Ending only the app session left "Sign in" on the // signed-out page passing silently through the live 30-day id.* session. // // - 307, not 303, so the hop stays a POST. A GET sign-out is one any link // or can trigger; id.* ignores GET. // - The browser sends "Origin: null" on the redirected POST, so id.* admits // it by Referer. This response sets the policy that makes Referer exactly // this origin. A page that itself sends Referrer-Policy: no-referrer still // strips it (no redirect can restore it), and its sign-out lands on id.*'s // "Finish signing out" page: recoverable, but a page with the account menu // should use strict-origin instead. // - FormPolicy already names the issuer in form-action, which browsers // enforce on the redirect target of a form submission. An app that // supplies its own policy must keep the issuer there. // // Without an issuer (never the case for Routes built by NewRoutes) it ends // here, as before. func (h *Routes) Signout(w http.ResponseWriter, r *http.Request) { h.cfg.SignOut(w, r) for _, name := range []string{homeInitCookie, homeProofCookie, localLinkNavigationCookie, homeReturnCookie, "__Host-oficina-assertion-pending", "__Host-oficina-assertion-inbox"} { localNavigationCookie(w, name, "", -1) } w.Header().Set("Cache-Control", "no-store") if h.cfg.Issuer == "" { http.Redirect(w, r, "/signed-out", http.StatusSeeOther) return } w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") http.Redirect(w, r, h.cfg.Issuer+"/signout", http.StatusTemporaryRedirect) }