package web import ( "context" "database/sql" "errors" "net/http" "net/url" "time" "amadan.net/oficina/home/connect" "amadan.net/oficina/home/connect/linkstore" "amadan.net/oficina/home/handoff" "amadan.net/rastrillo/rastrillo/csrf" "amadan.net/rastrillo/rastrillo/sessions" "amadan.net/oficina/base/internal/store" ) // Sign-in with Oficina ID, through Home's shared connect package, wired as // Oficina Calendar wires it. Base's roster stays the authority: an Oficina // account opens Base only through a link a member made by signing in the // local way once, and only while that member still exists. Nothing here // creates a member. // oficinaNamespace keeps Base's sealed hand-off state apart from every other // app's, as connect asks. const oficinaNamespace = "carlos/base" type oficina struct { bridge *connect.Bridge routes *connect.Routes db *sql.DB issuer string } func (a *app) newOficina(home *connect.DecodedCredentials) (*oficina, error) { sess := a.sess read := func(r *http.Request) (*connect.Session, error) { s, ok := sess.From(r) if !ok { return nil, nil } return &connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, nil } // A link names a member by number. The address it hands back is the // member's current one, so a link outlives nothing: a removed member's // number names nobody, and connect refuses it. lookup := func(ctx context.Context, q linkstore.Queryer, n int64) (string, error) { return store.MemberAddress(ctx, q, n) } // A local session names a member by the address it proved. Passkey // sessions are local too, but connect counts only an emailed link or // Keymail as proof for linking. local := func(ctx context.Context, s connect.Session) (connect.Person, error) { if s.Method != "magiclink" && s.Method != "keymail" { return connect.Person{}, sql.ErrNoRows } m, found, err := store.MemberByEmail(ctx, a.db, s.Subject) if err != nil { return connect.Person{}, err } if !found { return connect.Person{}, sql.ErrNoRows } n, err := store.MemberNumber(ctx, a.db, m.ID) if err != nil { return connect.Person{}, err } return connect.Person{ID: n, Label: m.Email}, nil } cfg := connect.Config{DB: a.db, Origin: a.cfg.Origin, Issuer: home.Issuer, ConsumerID: home.ConsumerID, Keys: home.Keys, DEK: home.DEK, Namespace: oficinaNamespace, SessionCookie: sess.CookieName(), ReadSession: read, LookupLocalSession: local, LookupPerson: lookup, Render: a.oficinaPage, MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error { return sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}) }, // The native app's session (connect.NativeExchange, method // NativeMethod): the same store and cookie name, minted without a // cookie and handed back in the answer. The store records when it // was made (At), which is what ends it after seven days. MintNativeSession: func(_ context.Context, s connect.Session) (string, error) { return sess.Mint(sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}) }} b, err := connect.New(cfg) if err != nil { return nil, err } routes, err := connect.NewRoutes(b, connect.RoutesConfig{Namespace: oficinaNamespace, Origin: a.cfg.Origin, Issuer: home.Issuer, SessionCookie: sess.CookieName(), DEK: home.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.signin, Protect: csrf.Protect(a.cfg.Origin), Render: a.oficinaPage, FormPolicy: formPolicy(home.Issuer)}) if err != nil { return nil, err } return &oficina{bridge: b, routes: routes, db: a.db, issuer: home.Issuer}, nil } // formPolicy is the Content-Security-Policy rastrillo gives every Base // response (serve.go's defaultCSP) with Oficina's issuer added to // form-action, as connect requires: Sign out's 307 to {issuer}/signout is a // form submission, and form-action governs where it may go. // TestFormPolicyIsRastrillosWithTheIssuer keeps the two in step. func formPolicy(issuer string) string { return "default-src 'self'; " + "style-src 'self' 'unsafe-hashes' 'sha256-yJxAE4rjdcckohdlnvecSporPcqS9xOaA4hJxi87LMc=' " + "'sha256-81gZUb3tp60YCqhJ0dItBPh5hRQiGbfst4gpwCNPTfI='; " + "img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self' " + issuer } // member is the member an Oficina session belongs to, through its link. func (o *oficina) member(r *http.Request) (store.Member, bool, error) { p, err := o.bridge.ResolveSession(r) if errors.Is(err, linkstore.ErrStorage) { return store.Member{}, false, err } if err != nil { return store.Member{}, false, nil } m, found, err := store.MemberByNumber(r.Context(), o.db, p.ID) if err != nil || !found || m.Email != p.Label { return store.Member{}, false, err } return m, true, nil } // linked reports whether member m has an Oficina account connected: a // link connect resolves. A dead link (deadLink) is no connection. An error // counts as linked, so Settings offers nothing it cannot be sure of. func (o *oficina) linked(ctx context.Context, m store.Member) bool { n, err := store.MemberNumber(ctx, o.db, m.ID) if err != nil { return true } linked, err := o.bridge.Linked(ctx, n) if err != nil || !linked { return err != nil } _, dead, err := o.deadLink(ctx, o.db, n) return err != nil || !dead } // deadLink reports whether member number n has a link connect no longer // resolves, and its subject. connect binds each link to Base's origin (and // the member's address), so every link made before BASE_ORIGIN changed is // one: it signs nobody in, yet it would stop the member linking again. // Asked only for a member who exists, so a refusal is the binding's. func (o *oficina) deadLink(ctx context.Context, q store.QueryRower, n int64) (subject string, dead bool, err error) { subject, ok, err := store.OficinaLinkSubject(ctx, q, o.issuer, n) if err != nil || !ok { return "", false, err } switch _, err := o.bridge.ResolveOn(ctx, q, subject); { case err == nil: return subject, false, nil case errors.Is(err, linkstore.ErrRefused): return subject, true, nil default: return "", false, err } } // dropDeadLink removes member m's dead link, if they have one, so that the // link they are confirming can take its place. connect's confirm refuses // while any link names the member or the subject, and offers no way to // replace one; connect asks the app to remove links itself (as // RemoveMember does). A link connect still resolves is never touched, nor // anyone else's. func (o *oficina) dropDeadLink(ctx context.Context, m store.Member) error { tx, err := o.db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() n, err := store.MemberNumber(ctx, tx, m.ID) if err != nil { return err } subject, dead, err := o.deadLink(ctx, tx, n) if err != nil || !dead { return err } if err := store.DeleteOficinaLink(ctx, tx, o.issuer, subject, n); err != nil { return err } return tx.Commit() } // oficinaConfirm is POST /account/home/confirm: connect's confirm, after // the member's dead link, if any, has made way. Only the member's own fresh // sign-in by email (connect.FreshLocal, what linking itself demands) clears // it; connect's confirm then checks that sign-in and the fresh Oficina // proof as always. func (a *app) oficinaConfirm(w http.ResponseWriter, r *http.Request) { s, ok := sessions.Current(r) if _, fresh := connect.FreshLocal(connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, time.Now()); ok && fresh { m, found, err := store.MemberByEmail(r.Context(), a.db, s.Subject) if err == nil && found { err = a.oficina.dropDeadLink(r.Context(), m) } if err != nil { a.logger.Error("oficina: dead link", "err", err) http.Error(w, "unavailable", http.StatusServiceUnavailable) return } } a.oficina.routes.ConfirmPost(w, r) } // oficinaSignin is GET /signin with Oficina ID on. Someone signed in as a // current member goes where they were headed, as connect's Routes.Signin // sends them. A session that names nobody who is a member now ends here, // and the page is asked for again without it. Everyone else gets the sign-in // page, which leads with Oficina and keeps the email form and passkey below. func (a *app) oficinaSignin(w http.ResponseWriter, r *http.Request) { back := r.URL.Query().Get("return_to") if !handoff.SafePath(back) { back = "" } if s, ok := a.sess.From(r); ok { _, found, err := a.memberFor(r, s) if err != nil { a.logger.Error("sign-in: member lookup", "err", err) http.Error(w, "unavailable", http.StatusServiceUnavailable) return } w.Header().Set("Cache-Control", "no-store") if found { to := back if to == "" { to = "/" } http.Redirect(w, r, to, http.StatusSeeOther) return } a.sess.SignOut(w, r) http.Redirect(w, r, r.URL.RequestURI(), http.StatusSeeOther) return } start := handoff.StartPath if back != "" { start += "?" + url.Values{"return_to": {back}}.Encode() } a.signinWith(w, r, start) } // oficinaPage is connect's Render hook: the shared connect pages, and where // Oficina's sign-out lands, drawn in Base's look. The words are connect's // English, as Calendar shows them; the signed-out page is in the Oficina // door's words, as Calendar's is. func (a *app) oficinaPage(w http.ResponseWriter, r *http.Request, state, label string, status int) { p := oficinaView{Name: a.cfg.Name, Back: "/settings"} if state == "signedout" { p.Tab = "Signed out" p.Page = connect.PageData{Title: "You’re signed out", Body: "You’ve signed out of " + a.cfg.Name + " on this device.", Action: "/signin", ActionLabel: "Sign in"} } else { p.Page = connect.PageFor(r, state, label) p.Tab = p.Page.Title } w.Header().Set("Cache-Control", "no-store") if err := a.pages.PageStatus(w, status, "oficina", p); err != nil { a.logger.Error("render", "page", "oficina", "err", err) http.Error(w, "something went wrong", http.StatusInternalServerError) } } type oficinaView struct { Name, Tab, Back string Page connect.PageData }