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 "encoding/base64"
5 "net/http"
6 "net/url"
7 "strings"
8 "time"
9
10 "amadan.net/oficina/home/internal/home/directorydata"
11 "amadan.net/rastrillo/rastrillo/assertion"
12 json "github.com/go-json-experiment/json"
13 "github.com/keymaildev/signin"
14)
15
16// /resolve on the credential origin (team-members.md §4, steps 2 and 3): an
17// owner adding someone to a team types the address here, never on the
18// directory. Home normalises and blind-indexes it as sign-in does, finds the
19// person or mints a stub (findOrMintPersonOn), signs a member-resolution
20// receipt for the directory and drops the address. The page renders fixed
21// copy only: no team name, label or sqid ever reaches this origin (gate 5),
22// and the answer is the same whether or not the person existed.
23
24const (
25 resolvePath = "/resolve"
26 // resolveIntentCookie carries the directory's intent id across this
27 // origin's sign-in, sealed, as the assertion intent does for /authorize.
28 resolveIntentCookie = "__Host-oficina-resolve-intent"
29 // resolveBudget is §4 step 3's "20 per subject per hour"; the per-IP
30 // budget is sign-in's own (signinIPBudget, the same bucket).
31 resolveBudget = 20
32 signinIPBudget = 20
33 resolveTTL = 10 * time.Minute
34)
35
36type resolveIntent struct {
37 Intent string `json:"intent"`
38 Expires int64 `json:"expires"`
39}
40
41func (a *App) writeResolveIntent(w http.ResponseWriter, id string, now time.Time) error {
42 b, err := json.Marshal(resolveIntent{Intent: id, Expires: now.Add(resolveTTL).Unix()})
43 if err != nil {
44 return err
45 }
46 sealed, err := a.secrets.Sealer.Seal("resolve.intent", b)
47 if err != nil {
48 return err
49 }
50 http.SetCookie(w, &http.Cookie{Name: resolveIntentCookie, Value: base64.RawURLEncoding.EncodeToString(sealed), Path: "/", MaxAge: int(resolveTTL.Seconds()), Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
51 return nil
52}
53
54func clearResolveIntent(w http.ResponseWriter) {
55 http.SetCookie(w, &http.Cookie{Name: resolveIntentCookie, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
56}
57
58func (a *App) readResolveIntent(r *http.Request, now time.Time) (string, bool) {
59 value, count := "", 0
60 for _, c := range r.Cookies() {
61 if c.Name == resolveIntentCookie {
62 value = c.Value
63 count++
64 }
65 }
66 if count != 1 || len(value) > 1024 {
67 return "", false
68 }
69 sealed, ok := canonicalRawURL(value)
70 if !ok {
71 return "", false
72 }
73 plain, err := a.secrets.Sealer.Open("resolve.intent", sealed)
74 if err != nil {
75 return "", false
76 }
77 var in resolveIntent
78 if json.Unmarshal(plain, &in, json.RejectUnknownMembers(true)) != nil || !directorydata.ValidIntentID(in.Intent) || in.Expires <= now.Unix() || in.Expires > now.Add(resolveTTL).Unix() {
79 return "", false
80 }
81 return in.Intent, true
82}
83
84// handleResolve: with the directory's query it seals the intent into a
85// cookie and redirects to the bare path, so the id leaves the URL; without
86// one it needs a complete credential session and draws the address form.
87func (a *App) handleResolve(w http.ResponseWriter, r *http.Request) {
88 w.Header().Set("Cache-Control", "no-store")
89 now := time.Now()
90 if r.URL.RawQuery != "" {
91 q, err := url.ParseQuery(r.URL.RawQuery)
92 if err != nil || len(q) != 2 || len(q["consumer"]) != 1 || q.Get("consumer") != "directory" || len(q["intent"]) != 1 || !directorydata.ValidIntentID(q.Get("intent")) {
93 a.notFound(w, r)
94 return
95 }
96 if err = a.writeResolveIntent(w, q.Get("intent"), now); err != nil {
97 a.serverError(w, r)
98 return
99 }
100 http.Redirect(w, r, resolvePath, http.StatusSeeOther)
101 return
102 }
103 if _, ok := a.sessions.From(r); !ok {
104 http.Redirect(w, r, "/signin?return_to=%2Fresolve", http.StatusSeeOther)
105 return
106 }
107 if _, ok := a.readResolveIntent(r, now); !ok {
108 a.render(w, r, http.StatusBadRequest, "resolve.html", map[string]any{"Expired": true})
109 return
110 }
111 a.render(w, r, http.StatusOK, "resolve.html", map[string]any{})
112}
113
114func (a *App) resolveFailed(w http.ResponseWriter, r *http.Request, status int, msg string) {
115 a.logger.Info("member resolve", "outcome", "refused")
116 a.render(w, r, status, "resolve.html", map[string]any{"Error": msg})
117}
118
119// handleResolvePost resolves the address and hands the receipt on.
120func (a *App) handleResolvePost(w http.ResponseWriter, r *http.Request) {
121 w.Header().Set("Cache-Control", "no-store")
122 now := time.Now()
123 s, ok := a.sessions.From(r)
124 if !ok {
125 http.Redirect(w, r, resolvePath, http.StatusSeeOther)
126 return
127 }
128 intent, ok := a.readResolveIntent(r, now)
129 if !ok {
130 a.logger.Info("member resolve", "outcome", "expired")
131 a.render(w, r, http.StatusBadRequest, "resolve.html", map[string]any{"Expired": true})
132 return
133 }
134 if err := r.ParseForm(); err != nil || len(r.PostForm) != 1 || len(r.PostForm["address"]) != 1 {
135 a.resolveFailed(w, r, http.StatusBadRequest, "That did not look like a form.")
136 return
137 }
138 address := strings.TrimSpace(r.PostFormValue("address"))
139 // Both budgets are spent before the address is looked at, so a refusal
140 // says nothing about it.
141 if allowed, err := a.resolveLimiter.Allow(r.Context(), "subject:"+s.Subject, now, resolveBudget); err != nil || !allowed {
142 a.resolveFailed(w, r, http.StatusTooManyRequests, "Too many attempts. Try again later.")
143 return
144 }
145 if ip := clientIP(r); ip != "" {
146 if allowed, err := a.signinLimiter.Allow(r.Context(), "ip:"+ip, now, signinIPBudget); err != nil || !allowed {
147 a.resolveFailed(w, r, http.StatusTooManyRequests, "Too many attempts. Try again later.")
148 return
149 }
150 }
151 if len(address) > 320 {
152 a.resolveFailed(w, r, http.StatusBadRequest, "That does not look like an email address.")
153 return
154 }
155 // Sign-in's normalisation, exactly: SplitAddress trims, refuses control
156 // bytes and lowercases the domain; blindIndex lowercases the whole.
157 local, domain, err := signin.SplitAddress(address)
158 if err != nil {
159 a.resolveFailed(w, r, http.StatusBadRequest, "That does not look like an email address.")
160 return
161 }
162 person, err := findOrMintPersonOn(r.Context(), a.db.Writer(), a.secrets.Pepper, local+"@"+domain, now)
163 if err != nil {
164 a.serverError(w, r)
165 return
166 }
167 jti, err := assertion.RandomID()
168 if err != nil {
169 a.serverError(w, r)
170 return
171 }
172 receipt, err := signMemberReceipt(a.runtime.resolveSigner, memberReceipt{Version: 1, Purpose: memberResolvePurpose, Issuer: a.origins.Credential, Audience: a.origins.Directory, Requester: s.Subject, Intent: intent, PersonRef: person, IssuedAt: now.Unix(), ExpiresAt: now.Unix() + memberReceiptLife, ID: jti})
173 if err != nil {
174 a.serverError(w, r)
175 return
176 }
177 clearResolveIntent(w)
178 a.logger.Info("member resolve", "outcome", "signed")
179 // no-referrer would turn the cross-origin form POST's Origin into null.
180 w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
181 a.render(w, r, http.StatusOK, "resolve_handoff.html", map[string]any{"Action": a.origins.Directory + teamResolvedPath, "Receipt": receipt})
182}
183