| 1 | package connect |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/base64" |
| 7 | "errors" |
| 8 | "net/http" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/home/connect/linkstore" |
| 13 | "amadan.net/oficina/home/handoff" |
| 14 | "amadan.net/oficina/home/handoff/seal" |
| 15 | "amadan.net/rastrillo/rastrillo/assertion" |
| 16 | ) |
| 17 | |
| 18 | const homeInitCookie = "__Host-oficina-home-init" |
| 19 | const homeProofCookie = "__Host-oficina-home-proof" |
| 20 | |
| 21 | var errHomeBridge = errors.New("home connect: exchange unavailable") |
| 22 | var errIdentityRefused = errors.New("home connect: identity refused") |
| 23 | |
| 24 | type Bridge struct { |
| 25 | origin, issuer, sessionCookie string |
| 26 | namespace string |
| 27 | keyHash [32]byte |
| 28 | links *linkstore.Store |
| 29 | exchange *handoff.Store |
| 30 | mintNative func(context.Context, Session) (string, error) |
| 31 | ordinary, fresh *handoff.Consumer |
| 32 | now func() time.Time |
| 33 | returnPath func(*http.Request) string |
| 34 | readSession func(*http.Request) (*Session, error) |
| 35 | mintSession func(http.ResponseWriter, *http.Request, Session) error |
| 36 | localPerson func(context.Context, Session) (Person, error) |
| 37 | render func(http.ResponseWriter, *http.Request, string, string, int) |
| 38 | unlinked, homeOnly func(context.Context, string, string) (Person, error) |
| 39 | admit func(context.Context, string, string) error |
| 40 | // formKey binds the choose page's form token to its proof cookie. |
| 41 | formKey []byte |
| 42 | // rememberUnknown is set by NewRoutes: an assertion with no link here |
| 43 | // leaves the sealed navigation marker that resumes linking after the |
| 44 | // person signs in locally. |
| 45 | rememberUnknown func(http.ResponseWriter) |
| 46 | } |
| 47 | type homeFinishKey struct{} |
| 48 | type homeFinishResult struct { |
| 49 | session *Session |
| 50 | init string |
| 51 | state string |
| 52 | status int |
| 53 | } |
| 54 | |
| 55 | // Both subsystem schemas must be migrated before construction. The consumers |
| 56 | // share one replay store; choosing a different Finish cannot weaken freshness. |
| 57 | func New(c Config) (*Bridge, error) { |
| 58 | if c.DB == nil || c.ReadSession == nil || c.MintHomeSession == nil || c.LookupLocalSession == nil || c.LookupPerson == nil || c.Render == nil || !validSessionCookie(c.SessionCookie) || (c.Unlinked == nil) != (c.HomeOnly == nil) || (c.Admit == nil) != (c.HomeOnly == nil) { |
| 59 | return nil, errHomeBridge |
| 60 | } |
| 61 | sealer, err := seal.New(c.DEK, c.Namespace) |
| 62 | if err != nil { |
| 63 | return nil, errHomeBridge |
| 64 | } |
| 65 | exchange, err := handoff.NewStore(c.DB, sealer, c.Issuer, c.Origin, c.Keys) |
| 66 | if err != nil { |
| 67 | return nil, errHomeBridge |
| 68 | } |
| 69 | linker, err := linkstore.New(c.DB, c.DEK, c.Origin, c.Issuer, c.Namespace, c.LookupPerson) |
| 70 | if err != nil { |
| 71 | return nil, errHomeBridge |
| 72 | } |
| 73 | now := c.Now |
| 74 | if now == nil { |
| 75 | now = time.Now |
| 76 | } |
| 77 | b := &Bridge{namespace: c.Namespace, keyHash: sha256.Sum256(c.DEK), origin: c.Origin, issuer: c.Issuer, sessionCookie: c.SessionCookie, links: linker, now: now, returnPath: c.ReturnPath, readSession: c.ReadSession, mintSession: c.MintHomeSession, localPerson: c.LookupLocalSession, render: c.Render, unlinked: c.Unlinked, homeOnly: c.HomeOnly, admit: c.Admit, formKey: formKey(c.DEK, c.Origin), exchange: exchange, mintNative: c.MintNativeSession} |
| 78 | cfg := handoff.ConsumerConfig{Store: exchange, ConsumerID: c.ConsumerID, Complete: b.complete, Fail: b.fail, Now: func() time.Time { return b.now() }, CurrentSubject: func(r *http.Request) string { |
| 79 | result, _ := r.Context().Value(homeFinishKey{}).(*homeFinishResult) |
| 80 | if result != nil && result.session != nil && IsHomeDerived(result.session.Method) && !Expired(*result.session, b.now()) { |
| 81 | return result.session.Subject |
| 82 | } |
| 83 | return "" |
| 84 | }} |
| 85 | b.ordinary, err = handoff.NewConsumer(cfg) |
| 86 | if err != nil { |
| 87 | return nil, errHomeBridge |
| 88 | } |
| 89 | cfg.RequireFreshAuth = true |
| 90 | cfg.BindStart = func(r *http.Request, nonce string) error { |
| 91 | secret, present, ok := homeCookie(r, homeInitCookie) |
| 92 | if !present || !ok { |
| 93 | return errIdentityRefused |
| 94 | } |
| 95 | local, _, err := b.localBinding(r) |
| 96 | if err != nil { |
| 97 | return err |
| 98 | } |
| 99 | return b.links.BindNonce(r.Context(), secret, local, nonce, b.now()) |
| 100 | } |
| 101 | b.fresh, err = handoff.NewConsumer(cfg) |
| 102 | if err != nil { |
| 103 | return nil, errHomeBridge |
| 104 | } |
| 105 | if exchange.Sweep(context.Background(), b.now()) != nil || linker.Sweep(context.Background(), b.now()) != nil { |
| 106 | return nil, errHomeBridge |
| 107 | } |
| 108 | return b, nil |
| 109 | } |
| 110 | |
| 111 | // homeCookie distinguishes absent cookies from malformed or duplicate values. |
| 112 | // Neither a duplicate nor an invalid link cookie may select ordinary sign-in. |
| 113 | func homeCookie(r *http.Request, name string) (value string, present, valid bool) { |
| 114 | count := 0 |
| 115 | for _, c := range r.Cookies() { |
| 116 | if c.Name == name { |
| 117 | count++ |
| 118 | value = c.Value |
| 119 | } |
| 120 | } |
| 121 | if count == 0 { |
| 122 | return "", false, true |
| 123 | } |
| 124 | if count != 1 || len(value) != 43 { |
| 125 | return "", true, false |
| 126 | } |
| 127 | raw, err := base64.RawURLEncoding.Strict().DecodeString(value) |
| 128 | return value, true, err == nil && len(raw) == 32 && base64.RawURLEncoding.EncodeToString(raw) == value |
| 129 | } |
| 130 | func setHomeCookie(w http.ResponseWriter, name, value string, seconds int) { |
| 131 | http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", MaxAge: seconds, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| 132 | } |
| 133 | func (b *Bridge) actualSession(r *http.Request) (*Session, error) { |
| 134 | _, present, ok := homeCookie(r, b.sessionCookie) |
| 135 | if !ok { |
| 136 | return nil, errIdentityRefused |
| 137 | } |
| 138 | if !present { |
| 139 | return nil, nil |
| 140 | } |
| 141 | session, err := b.readSession(r) |
| 142 | if err != nil || session == nil { |
| 143 | return nil, errIdentityRefused |
| 144 | } |
| 145 | return session, nil |
| 146 | } |
| 147 | func (b *Bridge) Start(w http.ResponseWriter, r *http.Request) { |
| 148 | _, present, ok := homeCookie(r, homeInitCookie) |
| 149 | if !ok { |
| 150 | b.fail(w, r, http.StatusBadRequest) |
| 151 | return |
| 152 | } |
| 153 | // Duplicate auth cookies must fail before a fresh hook or future mint. |
| 154 | if _, err := b.actualSession(r); err != nil { |
| 155 | b.fail(w, r, http.StatusForbidden) |
| 156 | return |
| 157 | } |
| 158 | if present { |
| 159 | b.fresh.Start(w, r) |
| 160 | } else { |
| 161 | b.ordinary.Start(w, r) |
| 162 | } |
| 163 | } |
| 164 | func (b *Bridge) Callback(w http.ResponseWriter, r *http.Request) { b.ordinary.Callback(w, r) } |
| 165 | func (b *Bridge) Finish(w http.ResponseWriter, r *http.Request) { |
| 166 | init, _, ok := homeCookie(r, homeInitCookie) |
| 167 | if !ok { |
| 168 | b.fail(w, r, http.StatusBadRequest) |
| 169 | return |
| 170 | } |
| 171 | _, _, ok = homeCookie(r, homeProofCookie) |
| 172 | if !ok { |
| 173 | b.fail(w, r, http.StatusBadRequest) |
| 174 | return |
| 175 | } |
| 176 | session, err := b.actualSession(r) |
| 177 | if err != nil { |
| 178 | b.fail(w, r, http.StatusForbidden) |
| 179 | return |
| 180 | } |
| 181 | result := &homeFinishResult{session: session, init: init} |
| 182 | b.ordinary.Finish(w, r.WithContext(context.WithValue(r.Context(), homeFinishKey{}, result))) |
| 183 | } |
| 184 | func (b *Bridge) fail(w http.ResponseWriter, r *http.Request, status int) { |
| 185 | state := "failed" |
| 186 | if result, ok := r.Context().Value(homeFinishKey{}).(*homeFinishResult); ok && result.state != "" { |
| 187 | state, status = result.state, result.status |
| 188 | } |
| 189 | if state == "choose" { |
| 190 | // A Member with no link: the proof cookie is set; the page asks. |
| 191 | // The return path stays with the exchange, so after a choice the |
| 192 | // person lands on "/". |
| 193 | http.Redirect(w, r, ChoosePath, http.StatusSeeOther) |
| 194 | return |
| 195 | } |
| 196 | b.render(w, r, state, "", status) |
| 197 | } |
| 198 | func rejectHome(r *http.Request, state string, status int) error { |
| 199 | if result, ok := r.Context().Value(homeFinishKey{}).(*homeFinishResult); ok { |
| 200 | result.state, result.status = state, status |
| 201 | } |
| 202 | return errIdentityRefused |
| 203 | } |
| 204 | func (b *Bridge) complete(w http.ResponseWriter, r *http.Request, claims assertion.Claims) error { |
| 205 | result, ok := r.Context().Value(homeFinishKey{}).(*homeFinishResult) |
| 206 | if !ok { |
| 207 | return errHomeBridge |
| 208 | } |
| 209 | if result.init != "" { |
| 210 | setHomeCookie(w, homeInitCookie, "", -1) |
| 211 | local, _, err := b.localBinding(r) |
| 212 | if err != nil { |
| 213 | return rejectHome(r, "failed", http.StatusForbidden) |
| 214 | } |
| 215 | secret, err := b.links.Complete(r.Context(), result.init, local, linkstore.Home{Issuer: claims.Issuer, Subject: claims.Subject, Nonce: claims.Nonce, AuthTime: time.Unix(claims.AuthTime, 0)}, b.now()) |
| 216 | if errors.Is(err, linkstore.ErrRefused) { |
| 217 | return rejectHome(r, "failed", http.StatusForbidden) |
| 218 | } |
| 219 | if err != nil { |
| 220 | return errHomeBridge |
| 221 | } |
| 222 | setHomeCookie(w, homeProofCookie, secret, 300) |
| 223 | return nil |
| 224 | } |
| 225 | // The exchange verified the issuer; an assertion from any other is |
| 226 | // treated as an unlinked subject, as linkstore always has. |
| 227 | arriving, err := Person{}, error(linkstore.ErrRefused) |
| 228 | if claims.Issuer == b.issuer { |
| 229 | arriving, err = b.Resolve(r.Context(), claims.Subject) |
| 230 | } |
| 231 | if errors.Is(err, linkstore.ErrRefused) && b.admit != nil && result.session == nil && claims.Issuer == b.issuer { |
| 232 | // Nobody is signed in here and the subject has no person: take the |
| 233 | // roster decision, which allocates nothing. With a session present |
| 234 | // the arrival is refused below as unknown, before Admit and with |
| 235 | // no proof issued, whoever that session belongs to. A non-member |
| 236 | // falls through to exactly the unknown answer an instance without |
| 237 | // the hooks gives. A Member gets a single-use choice proof and the |
| 238 | // choose page; nothing is created until they choose. "Cannot |
| 239 | // decide now" is errHomeBridge, which the exchange answers 503. |
| 240 | switch decision := b.admit(r.Context(), claims.Issuer, claims.Subject); { |
| 241 | case decision == nil: |
| 242 | secret, err := b.links.StartChoice(r.Context(), linkstore.Choice{Subject: claims.Subject, AuthTime: time.Unix(claims.AuthTime, 0)}, b.now()) |
| 243 | if err != nil { |
| 244 | return errHomeBridge |
| 245 | } |
| 246 | setHomeCookie(w, homeChoiceCookie, secret, choiceCookieLifetime) |
| 247 | return rejectHome(r, "choose", http.StatusSeeOther) |
| 248 | case !errors.Is(decision, ErrNoPerson): |
| 249 | return errHomeBridge |
| 250 | } |
| 251 | } |
| 252 | if errors.Is(err, linkstore.ErrRefused) { |
| 253 | if b.rememberUnknown != nil { |
| 254 | b.rememberUnknown(w) |
| 255 | } |
| 256 | return rejectHome(r, "unknown", http.StatusForbidden) |
| 257 | } |
| 258 | if err != nil { |
| 259 | return errHomeBridge |
| 260 | } |
| 261 | if result.session != nil { |
| 262 | person, err := b.existingPerson(r, *result.session) |
| 263 | if err != nil || person.ID != arriving.ID { |
| 264 | return rejectHome(r, "failed", http.StatusForbidden) |
| 265 | } |
| 266 | } |
| 267 | if err := b.mint(w, r, Session{Subject: claims.Subject, Method: HomeMethod, AuthTime: time.Unix(claims.AuthTime, 0)}, arriving); err != nil { |
| 268 | return errHomeBridge |
| 269 | } |
| 270 | return nil |
| 271 | } |
| 272 | |
| 273 | // existingPerson never creates a person or samples, even during ordinary SSO. |
| 274 | func (b *Bridge) existingPerson(r *http.Request, session Session) (Person, error) { |
| 275 | if IsHomeDerived(session.Method) { |
| 276 | if Expired(session, b.now()) { |
| 277 | return Person{}, errIdentityRefused |
| 278 | } |
| 279 | return b.Resolve(r.Context(), session.Subject) |
| 280 | } |
| 281 | if session.Method != "magiclink" && session.Method != "keymail" { |
| 282 | return Person{}, errIdentityRefused |
| 283 | } |
| 284 | p, err := b.localPerson(r.Context(), session) |
| 285 | if err != nil || p.ID <= 0 || p.Label == "" { |
| 286 | return Person{}, errIdentityRefused |
| 287 | } |
| 288 | return p, nil |
| 289 | } |
| 290 | func (b *Bridge) localBinding(r *http.Request) (linkstore.Local, Person, error) { |
| 291 | session, err := b.actualSession(r) |
| 292 | if err != nil || session == nil { |
| 293 | return linkstore.Local{}, Person{}, errIdentityRefused |
| 294 | } |
| 295 | at, fresh := FreshLocal(*session, b.now()) |
| 296 | if !fresh { |
| 297 | return linkstore.Local{}, Person{}, errIdentityRefused |
| 298 | } |
| 299 | person, err := b.existingPerson(r, *session) |
| 300 | if err != nil { |
| 301 | return linkstore.Local{}, Person{}, err |
| 302 | } |
| 303 | token, _, _ := homeCookie(r, b.sessionCookie) |
| 304 | return linkstore.Local{PersonID: person.ID, SessionToken: token, AuthTime: at}, person, nil |
| 305 | } |
| 306 | func (b *Bridge) host() string { return strings.TrimPrefix(b.origin, "https://") } |
| 307 | |
| 308 | func (b *Bridge) guard(w http.ResponseWriter, r *http.Request, method, path string) bool { |
| 309 | w.Header().Set("Cache-Control", "no-store") |
| 310 | if r.Host != b.host() || r.URL.Path != path { |
| 311 | b.fail(w, r, http.StatusNotFound) |
| 312 | return false |
| 313 | } |
| 314 | if r.Method != method { |
| 315 | w.Header().Set("Allow", method) |
| 316 | b.fail(w, r, http.StatusMethodNotAllowed) |
| 317 | return false |
| 318 | } |
| 319 | if r.URL.RawQuery != "" { |
| 320 | b.fail(w, r, http.StatusBadRequest) |
| 321 | return false |
| 322 | } |
| 323 | return true |
| 324 | } |
| 325 | |
| 326 | func validSessionCookie(name string) bool { |
| 327 | if !strings.HasPrefix(name, "__Host-") || len(name) <= 7 || len(name) > 128 { |
| 328 | return false |
| 329 | } |
| 330 | for _, c := range name { |
| 331 | if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '-') { |
| 332 | return false |
| 333 | } |
| 334 | } |
| 335 | return true |
| 336 | } |
| 337 | |