oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1package web
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "net/http"
8 "net/url"
9 "time"
10
11 "amadan.net/oficina/home/connect"
12 "amadan.net/oficina/home/connect/linkstore"
13 "amadan.net/oficina/home/handoff"
14 "amadan.net/rastrillo/rastrillo/csrf"
15 "amadan.net/rastrillo/rastrillo/sessions"
16
17 "amadan.net/oficina/base/internal/store"
18)
19
20// Sign-in with Oficina ID, through Home's shared connect package, wired as
21// Oficina Calendar wires it. Base's roster stays the authority: an Oficina
22// account opens Base only through a link a member made by signing in the
23// local way once, and only while that member still exists. Nothing here
24// creates a member.
25
26// oficinaNamespace keeps Base's sealed hand-off state apart from every other
27// app's, as connect asks.
28const oficinaNamespace = "carlos/base"
29
30type oficina struct {
31 bridge *connect.Bridge
32 routes *connect.Routes
33 db *sql.DB
34 issuer string
35}
36
37func (a *app) newOficina(home *connect.DecodedCredentials) (*oficina, error) {
38 sess := a.sess
39 read := func(r *http.Request) (*connect.Session, error) {
40 s, ok := sess.From(r)
41 if !ok {
42 return nil, nil
43 }
44 return &connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, nil
45 }
46 // A link names a member by number. The address it hands back is the
47 // member's current one, so a link outlives nothing: a removed member's
48 // number names nobody, and connect refuses it.
49 lookup := func(ctx context.Context, q linkstore.Queryer, n int64) (string, error) {
50 return store.MemberAddress(ctx, q, n)
51 }
52 // A local session names a member by the address it proved. Passkey
53 // sessions are local too, but connect counts only an emailed link or
54 // Keymail as proof for linking.
55 local := func(ctx context.Context, s connect.Session) (connect.Person, error) {
56 if s.Method != "magiclink" && s.Method != "keymail" {
57 return connect.Person{}, sql.ErrNoRows
58 }
59 m, found, err := store.MemberByEmail(ctx, a.db, s.Subject)
60 if err != nil {
61 return connect.Person{}, err
62 }
63 if !found {
64 return connect.Person{}, sql.ErrNoRows
65 }
66 n, err := store.MemberNumber(ctx, a.db, m.ID)
67 if err != nil {
68 return connect.Person{}, err
69 }
70 return connect.Person{ID: n, Label: m.Email}, nil
71 }
72 cfg := connect.Config{DB: a.db, Origin: a.cfg.Origin, Issuer: home.Issuer, ConsumerID: home.ConsumerID, Keys: home.Keys, DEK: home.DEK,
73 Namespace: oficinaNamespace, SessionCookie: sess.CookieName(), ReadSession: read, LookupLocalSession: local, LookupPerson: lookup,
74 Render: a.oficinaPage,
75 MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error {
76 return sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime})
77 },
78 // The native app's session (connect.NativeExchange, method
79 // NativeMethod): the same store and cookie name, minted without a
80 // cookie and handed back in the answer. The store records when it
81 // was made (At), which is what ends it after seven days.
82 MintNativeSession: func(_ context.Context, s connect.Session) (string, error) {
83 return sess.Mint(sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime})
84 }}
85 b, err := connect.New(cfg)
86 if err != nil {
87 return nil, err
88 }
89 routes, err := connect.NewRoutes(b, connect.RoutesConfig{Namespace: oficinaNamespace, Origin: a.cfg.Origin, Issuer: home.Issuer,
90 SessionCookie: sess.CookieName(), DEK: home.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.signin,
91 Protect: csrf.Protect(a.cfg.Origin), Render: a.oficinaPage, FormPolicy: formPolicy(home.Issuer)})
92 if err != nil {
93 return nil, err
94 }
95 return &oficina{bridge: b, routes: routes, db: a.db, issuer: home.Issuer}, nil
96}
97
98// formPolicy is the Content-Security-Policy rastrillo gives every Base
99// response (serve.go's defaultCSP) with Oficina's issuer added to
100// form-action, as connect requires: Sign out's 307 to {issuer}/signout is a
101// form submission, and form-action governs where it may go.
102// TestFormPolicyIsRastrillosWithTheIssuer keeps the two in step.
103func formPolicy(issuer string) string {
104 return "default-src 'self'; " +
105 "style-src 'self' 'unsafe-hashes' 'sha256-yJxAE4rjdcckohdlnvecSporPcqS9xOaA4hJxi87LMc=' " +
106 "'sha256-81gZUb3tp60YCqhJ0dItBPh5hRQiGbfst4gpwCNPTfI='; " +
107 "img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self' " + issuer
108}
109
110// member is the member an Oficina session belongs to, through its link.
111func (o *oficina) member(r *http.Request) (store.Member, bool, error) {
112 p, err := o.bridge.ResolveSession(r)
113 if errors.Is(err, linkstore.ErrStorage) {
114 return store.Member{}, false, err
115 }
116 if err != nil {
117 return store.Member{}, false, nil
118 }
119 m, found, err := store.MemberByNumber(r.Context(), o.db, p.ID)
120 if err != nil || !found || m.Email != p.Label {
121 return store.Member{}, false, err
122 }
123 return m, true, nil
124}
125
126// linked reports whether member m has an Oficina account connected: a
127// link connect resolves. A dead link (deadLink) is no connection. An error
128// counts as linked, so Settings offers nothing it cannot be sure of.
129func (o *oficina) linked(ctx context.Context, m store.Member) bool {
130 n, err := store.MemberNumber(ctx, o.db, m.ID)
131 if err != nil {
132 return true
133 }
134 linked, err := o.bridge.Linked(ctx, n)
135 if err != nil || !linked {
136 return err != nil
137 }
138 _, dead, err := o.deadLink(ctx, o.db, n)
139 return err != nil || !dead
140}
141
142// deadLink reports whether member number n has a link connect no longer
143// resolves, and its subject. connect binds each link to Base's origin (and
144// the member's address), so every link made before BASE_ORIGIN changed is
145// one: it signs nobody in, yet it would stop the member linking again.
146// Asked only for a member who exists, so a refusal is the binding's.
147func (o *oficina) deadLink(ctx context.Context, q store.QueryRower, n int64) (subject string, dead bool, err error) {
148 subject, ok, err := store.OficinaLinkSubject(ctx, q, o.issuer, n)
149 if err != nil || !ok {
150 return "", false, err
151 }
152 switch _, err := o.bridge.ResolveOn(ctx, q, subject); {
153 case err == nil:
154 return subject, false, nil
155 case errors.Is(err, linkstore.ErrRefused):
156 return subject, true, nil
157 default:
158 return "", false, err
159 }
160}
161
162// dropDeadLink removes member m's dead link, if they have one, so that the
163// link they are confirming can take its place. connect's confirm refuses
164// while any link names the member or the subject, and offers no way to
165// replace one; connect asks the app to remove links itself (as
166// RemoveMember does). A link connect still resolves is never touched, nor
167// anyone else's.
168func (o *oficina) dropDeadLink(ctx context.Context, m store.Member) error {
169 tx, err := o.db.BeginTx(ctx, nil)
170 if err != nil {
171 return err
172 }
173 defer tx.Rollback()
174 n, err := store.MemberNumber(ctx, tx, m.ID)
175 if err != nil {
176 return err
177 }
178 subject, dead, err := o.deadLink(ctx, tx, n)
179 if err != nil || !dead {
180 return err
181 }
182 if err := store.DeleteOficinaLink(ctx, tx, o.issuer, subject, n); err != nil {
183 return err
184 }
185 return tx.Commit()
186}
187
188// oficinaConfirm is POST /account/home/confirm: connect's confirm, after
189// the member's dead link, if any, has made way. Only the member's own fresh
190// sign-in by email (connect.FreshLocal, what linking itself demands) clears
191// it; connect's confirm then checks that sign-in and the fresh Oficina
192// proof as always.
193func (a *app) oficinaConfirm(w http.ResponseWriter, r *http.Request) {
194 s, ok := sessions.Current(r)
195 if _, fresh := connect.FreshLocal(connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, time.Now()); ok && fresh {
196 m, found, err := store.MemberByEmail(r.Context(), a.db, s.Subject)
197 if err == nil && found {
198 err = a.oficina.dropDeadLink(r.Context(), m)
199 }
200 if err != nil {
201 a.logger.Error("oficina: dead link", "err", err)
202 http.Error(w, "unavailable", http.StatusServiceUnavailable)
203 return
204 }
205 }
206 a.oficina.routes.ConfirmPost(w, r)
207}
208
209// oficinaSignin is GET /signin with Oficina ID on. Someone signed in as a
210// current member goes where they were headed, as connect's Routes.Signin
211// sends them. A session that names nobody who is a member now ends here,
212// and the page is asked for again without it. Everyone else gets the sign-in
213// page, which leads with Oficina and keeps the email form and passkey below.
214func (a *app) oficinaSignin(w http.ResponseWriter, r *http.Request) {
215 back := r.URL.Query().Get("return_to")
216 if !handoff.SafePath(back) {
217 back = ""
218 }
219 if s, ok := a.sess.From(r); ok {
220 _, found, err := a.memberFor(r, s)
221 if err != nil {
222 a.logger.Error("sign-in: member lookup", "err", err)
223 http.Error(w, "unavailable", http.StatusServiceUnavailable)
224 return
225 }
226 w.Header().Set("Cache-Control", "no-store")
227 if found {
228 to := back
229 if to == "" {
230 to = "/"
231 }
232 http.Redirect(w, r, to, http.StatusSeeOther)
233 return
234 }
235 a.sess.SignOut(w, r)
236 http.Redirect(w, r, r.URL.RequestURI(), http.StatusSeeOther)
237 return
238 }
239 start := handoff.StartPath
240 if back != "" {
241 start += "?" + url.Values{"return_to": {back}}.Encode()
242 }
243 a.signinWith(w, r, start)
244}
245
246// oficinaPage is connect's Render hook: the shared connect pages, and where
247// Oficina's sign-out lands, drawn in Base's look. The words are connect's
248// English, as Calendar shows them; the signed-out page is in the Oficina
249// door's words, as Calendar's is.
250func (a *app) oficinaPage(w http.ResponseWriter, r *http.Request, state, label string, status int) {
251 p := oficinaView{Name: a.cfg.Name, Back: "/settings"}
252 if state == "signedout" {
253 p.Tab = "Signed out"
254 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"}
255 } else {
256 p.Page = connect.PageFor(r, state, label)
257 p.Tab = p.Page.Title
258 }
259 w.Header().Set("Cache-Control", "no-store")
260 if err := a.pages.PageStatus(w, status, "oficina", p); err != nil {
261 a.logger.Error("render", "page", "oficina", "err", err)
262 http.Error(w, "something went wrong", http.StatusInternalServerError)
263 }
264}
265
266type oficinaView struct {
267 Name, Tab, Back string
268 Page connect.PageData
269}
270