oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "context"
5 "errors"
6 "io"
7 "mime"
8 "net/http"
9 "net/url"
10 "time"
11
12 "amadan.net/oficina/estilo.git/menu"
13 "amadan.net/oficina/home/internal/home/directorydata"
14 "amadan.net/rastrillo/rastrillo/sessions"
15)
16
17// The Team page (implementation/team-members.md, Part A) on the directory
18// origin: every member of a team sees its member list, only owners change
19// it, and every change needs a fresh sign-in.
20//
21// - GET /team?team=<sqid> needs a directory session (anonymous: 303 to
22// /auth/start with the query kept, as the chooser does). Anyone not on
23// the team, and any unknown or malformed sqid, gets the same 404 as an
24// unknown route. The page's own answers are never 403.
25// - Every POST is owner-only: a member's POST gets that same 404. The
26// owner check and the freshness check are both made again inside the
27// write's transaction (directorydata), and that is the check that
28// counts. A session whose auth_time is more than 300 s old, or in the
29// future, is sent through the fresh consumer at /auth/fresh/start and
30// the change is not kept: the person repeats it on return.
31// - Adding by email leaves this origin: the address is typed on the
32// credential origin, which resolves it and signs a receipt (resolve.go).
33//
34// The freshness gap this page inherits (fresh-assertion.md, the open
35// rastrillo item): the fresh consumer's max_age=300 makes the issuer refuse
36// a Keymail session with no reported gesture, but a directory session
37// minted by ordinary SSO from such a session inside the last 300 s carries
38// auth_time = At and passes teamFresh, as it passes the operator confirm
39// page and Docs linking. A recovery-code sign-in mints AuthTime now and no
40// method rides the assertion, so it passes here too; that is accepted,
41// recovery being a current credential. Writes that arrive through
42// /auth/fresh/start are not affected.
43
44const (
45 teamPath = "/team"
46 teamAddPath = "/team/add"
47 teamRolePath = "/team/role"
48 teamNamePath = "/team/name"
49 teamRemovePath = "/team/remove"
50 teamResolvedPath = "/team/resolved"
51 teamConfirmPath = "/team/confirm"
52 // teamIntentCookie binds an add-by-email intent to the browser that
53 // started it, from /team/add to /team/confirm.
54 teamIntentCookie = "__Host-oficina-team-add"
55 // teamWriteBudget is §3 rule 6's "30 writes per owner per hour".
56 teamWriteBudget = 30
57 teamFreshness = 300 * time.Second
58)
59
60var teamPaths = map[string]bool{teamPath: true, teamAddPath: true, teamRolePath: true, teamNamePath: true, teamRemovePath: true, teamResolvedPath: true, teamConfirmPath: true}
61
62// teamFresh is the directory's freshness for a roster write: the session's
63// auth_time, from the assertion it was exchanged for, within 300 s and not
64// in the future. directoryFresh, the operator confirm page's, is the same
65// rule; it is restated here so that the two can never drift apart silently
66// (TestTeamFreshnessIsTheOperatorRule).
67func teamFresh(s sessions.Session, now time.Time) bool {
68 return s.Method != nativeSessionMethod && !s.AuthTime.IsZero() && !s.AuthTime.After(now) && now.Sub(s.AuthTime) <= teamFreshness
69}
70
71func teamReturn(sqid string) string {
72 if sqid == "" {
73 return "/"
74 }
75 return teamPath + "?" + url.Values{"team": {sqid}}.Encode()
76}
77
78func validSQID(s string) bool {
79 if len(s) == 0 || len(s) > 64 {
80 return false
81 }
82 for _, c := range []byte(s) {
83 if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') {
84 return false
85 }
86 }
87 return true
88}
89
90// teamQuery is GET /team's one parameter, or "".
91func teamQuery(r *http.Request) string {
92 q, err := url.ParseQuery(r.URL.RawQuery)
93 if err != nil || len(q) != 1 || len(q["team"]) != 1 || !validSQID(q.Get("team")) {
94 return ""
95 }
96 return q.Get("team")
97}
98
99// ---- reading ----
100
101type memberView struct {
102 Ref, Label, Role, Added, Name string
103 You, Owner, Sole bool
104}
105
106type teamView struct {
107 Name, SQID, Error string
108 Owner, CanAdd bool
109 // Seeded: the team has a live Equipo or Base, whose own lists of
110 // people a change here does not reach (team-bundle spec §5.1 rule 1).
111 Seeded bool
112 Members []memberView
113 AddName, AddRole, FieldError string
114}
115
116func shortRef(ref string) string {
117 if len(ref) < 4 {
118 return ref
119 }
120 return "…" + ref[len(ref)-4:]
121}
122
123func roleLabel(role string) string {
124 if role == "owner" {
125 return "Owner"
126 }
127 return "Member"
128}
129
130func memberDay(day int64) string {
131 if day <= 0 {
132 return ""
133 }
134 return time.Unix(day*86400, 0).UTC().Format("2 Jan 2006")
135}
136
137func (a *App) teamView(viewer string, t directorydata.Team, members []directorydata.Member) teamView {
138 v := teamView{Name: t.Name, SQID: t.SQID, Owner: t.Role == "owner"}
139 v.CanAdd = v.Owner && a.runtime.resolvePublic != nil
140 owners := 0
141 for _, m := range members {
142 if m.Role == "owner" {
143 owners++
144 }
145 }
146 for _, m := range members {
147 label := m.Name
148 if label == "" {
149 label = roleLabel(m.Role) + " " + shortRef(m.PersonRef)
150 }
151 v.Members = append(v.Members, memberView{Ref: m.PersonRef, Label: label, Name: m.Name, Role: roleLabel(m.Role), Added: memberDay(m.AddedDay), You: m.PersonRef == viewer, Owner: m.Role == "owner", Sole: m.Role == "owner" && owners == 1})
152 }
153 return v
154}
155
156func (a *App) handleTeam(w http.ResponseWriter, r *http.Request) {
157 w.Header().Set("Cache-Control", "no-store")
158 sqid := teamQuery(r)
159 s, ok := sessions.Current(r)
160 if !ok {
161 if sqid == "" {
162 a.notFound(w, r)
163 return
164 }
165 http.Redirect(w, r, a.consumer.StartPath()+"?"+url.Values{"return_to": {teamReturn(sqid)}}.Encode(), http.StatusSeeOther)
166 return
167 }
168 if sqid == "" || !ValidPersonRef(s.Subject) {
169 a.notFound(w, r)
170 return
171 }
172 a.renderTeam(w, r, s.Subject, sqid, http.StatusOK, teamView{})
173}
174
175// renderTeam draws the list for viewer, with notice's error and field values.
176func (a *App) renderTeam(w http.ResponseWriter, r *http.Request, viewer, sqid string, status int, notice teamView) {
177 t, members, err := a.directory.store.TeamMembers(r.Context(), viewer, sqid)
178 switch {
179 case errors.Is(err, directorydata.ErrNotFound):
180 a.notFound(w, r)
181 return
182 case err != nil:
183 a.errorPage(w, r, http.StatusServiceUnavailable)
184 return
185 }
186 v := a.teamView(viewer, t, members)
187 if v.Seeded, err = a.directory.store.HasLiveSeededApp(r.Context(), t.ID); err != nil {
188 a.errorPage(w, r, http.StatusServiceUnavailable)
189 return
190 }
191 v.Error, v.FieldError, v.AddName, v.AddRole = notice.Error, notice.FieldError, notice.AddName, notice.AddRole
192 if v.AddRole == "" {
193 v.AddRole = "member"
194 }
195 a.render(w, r, status, "team.html", v)
196}
197
198// ---- writing ----
199
200// teamForm reads a Team-page POST: a form body of at most 4 KiB (a
201// receipt is at most 2 KiB) whose keys are exactly want (every one present
202// once; "name" may be empty).
203func teamForm(w http.ResponseWriter, r *http.Request, want ...string) (url.Values, bool) {
204 media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
205 if err != nil || media != "application/x-www-form-urlencoded" || r.URL.RawQuery != "" {
206 return nil, false
207 }
208 body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4096))
209 if err != nil {
210 return nil, false
211 }
212 form, err := url.ParseQuery(string(body))
213 if err != nil || len(form) != len(want) {
214 return nil, false
215 }
216 for _, k := range want {
217 if len(form[k]) != 1 {
218 return nil, false
219 }
220 }
221 return form, true
222}
223
224// teamWriter answers the request itself unless it carries a session on a
225// team the subject owns and the subject has budget left. Freshness is not
226// checked here: the write's own transaction checks it, and a stale session
227// is answered by teamWriteFailed.
228func (a *App) teamWriter(w http.ResponseWriter, r *http.Request, want ...string) (sessions.Session, url.Values, bool) {
229 w.Header().Set("Cache-Control", "no-store")
230 form, formOK := teamForm(w, r, want...)
231 sqid := ""
232 if formOK && validSQID(form.Get("team")) {
233 sqid = form.Get("team")
234 }
235 s, ok := sessions.Current(r)
236 if !ok {
237 // Start a new GET navigation after the form response; the
238 // submitted change is discarded, as the chooser discards a choice.
239 a.renderContinuation(w, r, a.origins.Directory+a.consumer.StartPath()+"?"+url.Values{"return_to": {teamReturn(sqid)}}.Encode(), "Sign in to continue")
240 return s, nil, false
241 }
242 if !formOK || sqid == "" || !ValidPersonRef(s.Subject) {
243 a.notFound(w, r)
244 return s, nil, false
245 }
246 t, err := a.directory.store.TeamForMember(r.Context(), s.Subject, sqid)
247 switch {
248 case errors.Is(err, directorydata.ErrNotFound) || err == nil && t.Role != "owner":
249 a.notFound(w, r)
250 return s, nil, false
251 case err != nil:
252 a.errorPage(w, r, http.StatusServiceUnavailable)
253 return s, nil, false
254 }
255 if allowed, err := a.teamWrites.Allow(r.Context(), "owner:"+s.Subject, time.Now(), teamWriteBudget); err != nil || !allowed {
256 a.renderTeam(w, r, s.Subject, sqid, http.StatusTooManyRequests, teamView{Error: "Too many changes. Wait a while, then try again."})
257 return s, nil, false
258 }
259 return s, form, true
260}
261
262// stepUp sends a stale session through the fresh consumer, back to back.
263func (a *App) stepUp(w http.ResponseWriter, r *http.Request, back string) {
264 a.renderContinuation(w, r, a.origins.Directory+a.fresh.StartPath()+"?"+url.Values{"return_to": {back}}.Encode(), "Confirm it’s you")
265}
266
267func (a *App) freshCheck(s sessions.Session) func() bool {
268 return func() bool { return teamFresh(s, time.Now()) }
269}
270
271// teamWriteFailed answers a refused write. Success is the caller's.
272func (a *App) teamWriteFailed(w http.ResponseWriter, r *http.Request, s sessions.Session, sqid string, err error, notice teamView) {
273 a.logger.Info("team write", "outcome", "refused")
274 switch {
275 case errors.Is(err, directorydata.ErrStale):
276 a.stepUp(w, r, teamReturn(sqid))
277 return
278 case errors.Is(err, directorydata.ErrNotFound), errors.Is(err, directorydata.ErrInvalid):
279 a.notFound(w, r)
280 return
281 case errors.Is(err, directorydata.ErrLastOwner):
282 notice.Error = "A team needs at least one owner. Make someone else an owner first."
283 a.renderTeam(w, r, s.Subject, sqid, http.StatusConflict, notice)
284 case errors.Is(err, directorydata.ErrNameAt):
285 notice.Error = "A name can’t contain @, so that it can never be an email address."
286 notice.FieldError = notice.Error
287 a.renderTeam(w, r, s.Subject, sqid, http.StatusBadRequest, notice)
288 case errors.Is(err, directorydata.ErrName):
289 notice.Error = "A name is 1 to 64 characters, with no line breaks."
290 notice.FieldError = notice.Error
291 a.renderTeam(w, r, s.Subject, sqid, http.StatusBadRequest, notice)
292 default:
293 a.errorPage(w, r, http.StatusServiceUnavailable)
294 }
295}
296
297func (a *App) teamWritten(w http.ResponseWriter, r *http.Request, sqid string) {
298 a.logger.Info("team write", "outcome", "committed")
299 http.Redirect(w, r, teamReturn(sqid), http.StatusSeeOther)
300}
301
302func (a *App) handleTeamRole(w http.ResponseWriter, r *http.Request) {
303 s, form, ok := a.teamWriter(w, r, "team", "person", "role")
304 if !ok {
305 return
306 }
307 sqid := form.Get("team")
308 if err := a.directory.store.SetRole(r.Context(), s.Subject, sqid, form.Get("person"), form.Get("role"), a.freshCheck(s)); err != nil {
309 a.teamWriteFailed(w, r, s, sqid, err, teamView{})
310 return
311 }
312 a.teamWritten(w, r, sqid)
313}
314
315func (a *App) handleTeamRemove(w http.ResponseWriter, r *http.Request) {
316 s, form, ok := a.teamWriter(w, r, "team", "person")
317 if !ok {
318 return
319 }
320 sqid := form.Get("team")
321 if err := a.directory.store.Remove(r.Context(), s.Subject, sqid, form.Get("person"), a.freshCheck(s)); err != nil {
322 a.teamWriteFailed(w, r, s, sqid, err, teamView{})
323 return
324 }
325 if form.Get("person") == s.Subject {
326 // An owner who left can no longer read the list: back to Oficina.
327 a.logger.Info("team write", "outcome", "committed")
328 http.Redirect(w, r, "/", http.StatusSeeOther)
329 return
330 }
331 a.teamWritten(w, r, sqid)
332}
333
334func (a *App) handleTeamName(w http.ResponseWriter, r *http.Request) {
335 s, form, ok := a.teamWriter(w, r, "team", "person", "name")
336 if !ok {
337 return
338 }
339 sqid := form.Get("team")
340 if err := a.directory.store.SetName(r.Context(), s.Subject, sqid, form.Get("person"), form.Get("name"), time.Now(), a.freshCheck(s)); err != nil {
341 a.teamWriteFailed(w, r, s, sqid, err, teamView{})
342 return
343 }
344 a.teamWritten(w, r, sqid)
345}
346
347// ---- adding by email (team-members.md §4) ----
348
349func (a *App) setTeamIntent(w http.ResponseWriter, id string, maxAge int) {
350 http.SetCookie(w, &http.Cookie{Name: teamIntentCookie, Value: id, Path: "/", MaxAge: maxAge, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
351}
352
353// teamIntent is the browser's add intent id, or "".
354func teamIntent(r *http.Request) string {
355 value, count := "", 0
356 for _, c := range r.Cookies() {
357 if c.Name == teamIntentCookie {
358 value = c.Value
359 count++
360 }
361 }
362 if count != 1 || !directorydata.ValidIntentID(value) {
363 return ""
364 }
365 return value
366}
367
368// handleTeamAdd (step 1) stores the owner's intent and sends the browser to
369// the credential origin, where the address is typed. Nothing about the team
370// rides the URL: only the consumer and the random intent id.
371func (a *App) handleTeamAdd(w http.ResponseWriter, r *http.Request) {
372 if a.runtime.resolvePublic == nil {
373 w.Header().Set("Cache-Control", "no-store")
374 a.notFound(w, r)
375 return
376 }
377 s, form, ok := a.teamWriter(w, r, "team", "role", "name")
378 if !ok {
379 return
380 }
381 sqid, role, name := form.Get("team"), form.Get("role"), form.Get("name")
382 if role != "owner" && role != "member" {
383 a.notFound(w, r)
384 return
385 }
386 id, err := a.directory.store.CreateAddIntent(r.Context(), s.Subject, sqid, role, name, time.Now(), a.freshCheck(s))
387 if err != nil {
388 a.teamWriteFailed(w, r, s, sqid, err, teamView{AddName: name, AddRole: role})
389 return
390 }
391 a.setTeamIntent(w, id, int(directorydata.AddIntentLifetime.Seconds()))
392 a.logger.Info("team write", "outcome", "add started")
393 a.renderContinuation(w, r, a.origins.Credential+resolvePath+"?"+url.Values{"consumer": {"directory"}, "intent": {id}}.Encode(), "Continue to enter their email")
394}
395
396// handleTeamResolved (step 4) is the one Team route outside csrf.Protect: it
397// takes the credential origin's cross-origin POST, with its own exact Origin
398// check, as the handoff callback does. It verifies the receipt, requires the
399// receipt's requester, the intent's and this session's subject to be one
400// person and the browser to hold the intent, records the result once, and
401// writes no membership: GET /team/confirm shows it and asks.
402func (a *App) handleTeamResolved(w http.ResponseWriter, r *http.Request) {
403 w.Header().Set("Cache-Control", "no-store")
404 if a.runtime.resolvePublic == nil || r.Host != a.directoryHost || r.URL.Path != teamResolvedPath {
405 a.notFound(w, r)
406 return
407 }
408 if r.Method != http.MethodPost {
409 a.methodNotAllowed(w, r)
410 return
411 }
412 origins := r.Header.Values("Origin")
413 if len(origins) != 1 || origins[0] != a.origins.Credential {
414 a.teamAddFailed(w, r)
415 return
416 }
417 form, ok := teamForm(w, r, "receipt")
418 if !ok {
419 a.teamAddFailed(w, r)
420 return
421 }
422 now := time.Now()
423 receipt, err := verifyMemberReceipt(a.runtime.resolvePublic, form.Get("receipt"), a.origins.Credential, a.origins.Directory, now)
424 if err != nil {
425 a.teamAddFailed(w, r)
426 return
427 }
428 s, signed := sessions.Current(r)
429 if !signed || s.Subject != receipt.Requester || teamIntent(r) != receipt.Intent {
430 a.teamAddFailed(w, r)
431 return
432 }
433 if err = a.directory.store.ResolveAddIntent(r.Context(), receipt.Intent, receipt.Requester, receipt.PersonRef, receipt.ID, receipt.ExpiresAt, now); err != nil {
434 if errors.Is(err, directorydata.ErrNotFound) {
435 a.teamAddFailed(w, r)
436 return
437 }
438 a.errorPage(w, r, http.StatusServiceUnavailable)
439 return
440 }
441 a.logger.Info("team write", "outcome", "add resolved")
442 http.Redirect(w, r, teamConfirmPath, http.StatusSeeOther)
443}
444
445// teamAddFailed is every refusal on the add path: one page, one status.
446func (a *App) teamAddFailed(w http.ResponseWriter, r *http.Request) {
447 a.logger.Info("team write", "outcome", "add refused")
448 a.render(w, r, http.StatusBadRequest, "team_confirm.html", map[string]any{"Failed": true})
449}
450
451type confirmView struct {
452 Team, SQID, Person, Role, Name string
453 Member, Done, Failed bool
454 Error string
455}
456
457func confirmViewOf(in directorydata.AddIntent) confirmView {
458 return confirmView{Team: in.Team.Name, SQID: in.Team.SQID, Person: shortRef(in.Person), Role: roleLabel(in.Role), Name: in.Name, Member: in.Member}
459}
460
461// handleTeamConfirm (GET) shows the resolved add and asks the owner.
462func (a *App) handleTeamConfirm(w http.ResponseWriter, r *http.Request) {
463 w.Header().Set("Cache-Control", "no-store")
464 if a.runtime.resolvePublic == nil || r.URL.RawQuery != "" {
465 a.notFound(w, r)
466 return
467 }
468 s, ok := sessions.Current(r)
469 if !ok {
470 http.Redirect(w, r, a.consumer.StartPath()+"?"+url.Values{"return_to": {teamConfirmPath}}.Encode(), http.StatusSeeOther)
471 return
472 }
473 in, err := a.directory.store.PendingAdd(r.Context(), teamIntent(r), s.Subject, time.Now())
474 switch {
475 case errors.Is(err, directorydata.ErrNotFound):
476 a.notFound(w, r)
477 return
478 case err != nil:
479 a.errorPage(w, r, http.StatusServiceUnavailable)
480 return
481 }
482 if !teamFresh(s, time.Now()) {
483 // The intent is Home's, held for ten minutes; the step-up comes
484 // back here and the owner still has to confirm.
485 http.Redirect(w, r, a.fresh.StartPath()+"?"+url.Values{"return_to": {teamConfirmPath}}.Encode(), http.StatusSeeOther)
486 return
487 }
488 a.render(w, r, http.StatusOK, "team_confirm.html", confirmViewOf(in))
489}
490
491// handleTeamConfirmPost (step 5) writes the membership: owner and freshness
492// re-checked inside the transaction, the team the intent's own.
493func (a *App) handleTeamConfirmPost(w http.ResponseWriter, r *http.Request) {
494 w.Header().Set("Cache-Control", "no-store")
495 if a.runtime.resolvePublic == nil {
496 a.notFound(w, r)
497 return
498 }
499 s, ok := sessions.Current(r)
500 if !ok {
501 a.renderContinuation(w, r, a.origins.Directory+a.consumer.StartPath()+"?"+url.Values{"return_to": {teamConfirmPath}}.Encode(), "Sign in to continue")
502 return
503 }
504 if _, ok := teamForm(w, r); !ok {
505 a.notFound(w, r)
506 return
507 }
508 id := teamIntent(r)
509 pending, err := a.directory.store.PendingAdd(r.Context(), id, s.Subject, time.Now())
510 switch {
511 case errors.Is(err, directorydata.ErrNotFound):
512 a.notFound(w, r)
513 return
514 case err != nil:
515 a.errorPage(w, r, http.StatusServiceUnavailable)
516 return
517 }
518 if allowed, err := a.teamWrites.Allow(r.Context(), "owner:"+s.Subject, time.Now(), teamWriteBudget); err != nil || !allowed {
519 v := confirmViewOf(pending)
520 v.Error = "Too many changes. Wait a while, then try again."
521 a.render(w, r, http.StatusTooManyRequests, "team_confirm.html", v)
522 return
523 }
524 in, err := a.directory.store.ConfirmAdd(r.Context(), id, s.Subject, time.Now(), a.freshCheck(s))
525 switch {
526 case err == nil:
527 a.setTeamIntent(w, "", -1)
528 a.logger.Info("team write", "outcome", "committed")
529 v := confirmViewOf(in)
530 v.Done = true
531 a.render(w, r, http.StatusOK, "team_confirm.html", v)
532 case errors.Is(err, directorydata.ErrStale):
533 a.stepUp(w, r, teamConfirmPath)
534 case errors.Is(err, directorydata.ErrNotFound):
535 a.notFound(w, r)
536 case errors.Is(err, directorydata.ErrMember), errors.Is(err, directorydata.ErrFull):
537 v := confirmViewOf(pending)
538 v.Member = errors.Is(err, directorydata.ErrMember)
539 if errors.Is(err, directorydata.ErrFull) {
540 v.Error = "This team already has 500 people, the most a team can have."
541 }
542 a.logger.Info("team write", "outcome", "refused")
543 a.render(w, r, http.StatusConflict, "team_confirm.html", v)
544 default:
545 a.errorPage(w, r, http.StatusServiceUnavailable)
546 }
547}
548
549// teamMenu is the account menu's Team entries: one per directory team the
550// signed-in person is on, at most eight, oldest first.
551func (a *App) teamMenu(r *http.Request, subject string) []menu.Item {
552 if a.directory == nil || a.directory.store == nil || !ValidPersonRef(subject) {
553 return nil
554 }
555 ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
556 defer cancel()
557 teams, err := a.directory.store.TeamsForMember(ctx, subject, 8)
558 if err != nil {
559 return nil
560 }
561 var links []menu.Item
562 for _, t := range teams {
563 label := "Team"
564 if len(teams) > 1 {
565 label = "Team: " + t.Name
566 }
567 links = append(links, menu.Item{Href: teamReturn(t.SQID), Label: label})
568 }
569 return links
570}
571