oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package handoff
2
3import (
4 "io"
5 "mime"
6 "net/http"
7 "net/url"
8 "path"
9 "strings"
10 "time"
11
12 "amadan.net/rastrillo/rastrillo/assertion"
13)
14
15const (
16 StartPath = "/auth/start"
17 CallbackPath = "/auth/assertion"
18 FinishPath = "/auth/finish"
19 pendingCookie = "__Host-oficina-assertion-pending"
20 inboxCookie = "__Host-oficina-assertion-inbox"
21)
22
23type ConsumerConfig struct {
24 Store *Store
25 ConsumerID string
26 // RequireFreshAuth requests and enforces actual authentication within five minutes.
27 RequireFreshAuth bool
28 // StartPath is the one path Start serves. Empty means the package
29 // StartPath, so a consumer that leaves it unset behaves exactly as before.
30 // It lets a second consumer on the same Store and ConsumerID, typically
31 // RequireFreshAuth, have its own entry (for example /auth/fresh/start).
32 // NewConsumer refuses a path that is not clean, lowercase [a-z0-9/_-]
33 // under /auth/ (SafePath refuses that prefix, so no return_to can point
34 // back into a start), or that is CallbackPath or FinishPath, which every
35 // consumer of a Store shares. Two consumers at one path are the router's
36 // business: an app may dispatch between them itself, as connect does.
37 //
38 // Callback and Finish do not read this field or RequireFreshAuth. The
39 // freshness class is sealed into the pending row by Start (Store.StartFresh's
40 // path prefix), and Store.Finish enforces it whichever consumer's Finish
41 // handles the browser, so one shared Finish serves both start paths and
42 // no Finish can change a row's class: a fresh row refuses (and burns) a
43 // proof older than five minutes or from the future, an ordinary row does
44 // not check age. Complete is not told which path started the flow; code
45 // that needs freshness after Finish reads the claims' AuthTime.
46 StartPath string
47 // BindStart binds the public nonce to an app initiation after pending storage
48 // commits, before any cookie or redirect. It must not make network calls or
49 // create grants. Rejection cancels this new pending request.
50 BindStart func(*http.Request, string) error
51 // Resolve before store transactions, using the app's session middleware.
52 CurrentSubject func(*http.Request) string
53 // Complete runs only after replay consumption is committed. It creates the
54 // app's session, preserving AuthTime. An error cannot restore the assertion.
55 Complete func(http.ResponseWriter, *http.Request, assertion.Claims) error
56 Fail func(http.ResponseWriter, *http.Request, int)
57 Now func() time.Time
58}
59type Consumer struct{ cfg ConsumerConfig }
60
61func NewConsumer(cfg ConsumerConfig) (*Consumer, error) {
62 if cfg.StartPath == "" {
63 cfg.StartPath = StartPath
64 }
65 if cfg.Store == nil || cfg.Store.db == nil || cfg.Complete == nil || !consumerID(cfg.ConsumerID) || !startPath(cfg.StartPath) {
66 return nil, ErrConfig
67 }
68 if cfg.Now == nil {
69 cfg.Now = time.Now
70 }
71 if cfg.CurrentSubject == nil {
72 cfg.CurrentSubject = func(*http.Request) string { return "" }
73 }
74 if cfg.Fail == nil {
75 cfg.Fail = func(w http.ResponseWriter, r *http.Request, status int) {
76 http.Error(w, "Unable to sign in. Start again.", status)
77 }
78 }
79 return &Consumer{cfg}, nil
80}
81func consumerID(s string) bool {
82 if len(s) == 0 || len(s) > 64 {
83 return false
84 }
85 for _, b := range []byte(s) {
86 if !(b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' || b == '_' || b == '-') {
87 return false
88 }
89 }
90 return true
91}
92
93// startPath accepts the package StartPath and any clean path in the exchange's
94// own /auth/ namespace other than the two shared routes. Every byte is checked,
95// so the value is a literal r.URL.Path with no query, escape or dot segment.
96func startPath(s string) bool {
97 if len(s) > 128 || !strings.HasPrefix(s, "/auth/") || path.Clean(s) != s || s == CallbackPath || s == FinishPath || SafePath(s) {
98 return false
99 }
100 for _, b := range []byte(s) {
101 if !(b >= 'a' && b <= 'z' || b >= '0' && b <= '9' || b == '/' || b == '_' || b == '-') {
102 return false
103 }
104 }
105 return true
106}
107
108// StartPath reports the path this consumer's Start serves, for apps that
109// mount it or link to it.
110func (c *Consumer) StartPath() string { return c.cfg.StartPath }
111
112func (c *Consumer) guard(w http.ResponseWriter, r *http.Request, method, path string) bool {
113 w.Header().Set("Cache-Control", "no-store")
114 if r.Host != strings.TrimPrefix(c.cfg.Store.audience, "https://") || r.URL.Path != path {
115 c.cfg.Fail(w, r, http.StatusNotFound)
116 return false
117 }
118 if r.Method != method {
119 w.Header().Set("Allow", method)
120 c.cfg.Fail(w, r, http.StatusMethodNotAllowed)
121 return false
122 }
123 return true
124}
125func cookie(r *http.Request, name string) (string, bool) {
126 value := ""
127 count := 0
128 for _, c := range r.Cookies() {
129 if c.Name == name {
130 count++
131 value = c.Value
132 }
133 }
134 return value, count == 1 && validHandle(value)
135}
136func setCookie(w http.ResponseWriter, name, value string, seconds int) {
137 http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", MaxAge: seconds, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
138}
139func (c *Consumer) fail(w http.ResponseWriter, r *http.Request, e error) {
140 status := http.StatusBadRequest
141 if e == ErrStorage || e == ErrClock || e == ErrFull {
142 status = http.StatusServiceUnavailable
143 }
144 c.cfg.Fail(w, r, status)
145}
146
147// Start accepts a bounded local return_to query and writes only sealed intent.
148func (c *Consumer) Start(w http.ResponseWriter, r *http.Request) {
149 if !c.guard(w, r, http.MethodGet, c.cfg.StartPath) {
150 return
151 }
152 q, e := url.ParseQuery(r.URL.RawQuery)
153 if e != nil || len(q) > 1 || len(q["return_to"]) > 1 {
154 c.fail(w, r, ErrRefused)
155 return
156 }
157 path := "/"
158 if len(q) > 0 {
159 values, ok := q["return_to"]
160 if !ok || len(values) != 1 {
161 c.fail(w, r, ErrRefused)
162 return
163 }
164 path = values[0]
165 }
166 matches := 0
167 for _, item := range r.Cookies() {
168 if item.Name == pendingCookie {
169 matches++
170 }
171 }
172 if matches > 1 {
173 c.fail(w, r, ErrRefused)
174 return
175 }
176 previous, ok := cookie(r, pendingCookie)
177 if !ok {
178 previous = ""
179 }
180 start := c.cfg.Store.Start
181 if c.cfg.RequireFreshAuth {
182 start = c.cfg.Store.StartFresh
183 }
184 secret, nonce, e := start(r.Context(), path, previous, c.cfg.Now())
185 if e != nil {
186 c.fail(w, r, e)
187 return
188 }
189 if c.cfg.BindStart != nil {
190 if e = c.cfg.BindStart(r, nonce); e != nil {
191 failure := ErrRefused
192 if c.cfg.Store.cancel(r.Context(), secret) != nil {
193 failure = ErrStorage
194 }
195 c.fail(w, r, failure)
196 return
197 }
198 }
199 setCookie(w, pendingCookie, secret, int(pendingLifetime))
200 query := url.Values{"consumer": {c.cfg.ConsumerID}, "nonce": {nonce}}
201 if c.cfg.RequireFreshAuth {
202 query.Set("max_age", "300")
203 }
204 target := c.cfg.Store.issuer + "/authorize?" + query.Encode()
205 http.Redirect(w, r, target, http.StatusSeeOther)
206}
207
208// Callback is the one route mounted outside ordinary same-origin CSRF checks.
209// It requires the exact issuer Origin even for a same-site request and needs no
210// cookies. Keep every other app mutation inside the app's CSRF middleware.
211func (c *Consumer) Callback(w http.ResponseWriter, r *http.Request) {
212 if !c.guard(w, r, http.MethodPost, CallbackPath) {
213 return
214 }
215 origins := r.Header.Values("Origin")
216 if len(origins) != 1 || origins[0] != c.cfg.Store.issuer || r.URL.RawQuery != "" {
217 c.fail(w, r, ErrRefused)
218 return
219 }
220 media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
221 if e != nil || media != "application/x-www-form-urlencoded" {
222 c.fail(w, r, ErrRefused)
223 return
224 }
225 // Form encoding expands the 8192-byte core wire bound; 12 KiB comfortably
226 // holds a base64url token while bounding input before parsing or crypto.
227 body, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024))
228 if e != nil {
229 c.fail(w, r, ErrRefused)
230 return
231 }
232 form, e := url.ParseQuery(string(body))
233 if e != nil || len(form) != 1 || len(form["assertion"]) != 1 {
234 c.fail(w, r, ErrRefused)
235 return
236 }
237 handle, e := c.cfg.Store.Receive(r.Context(), form["assertion"][0], c.cfg.Now())
238 if e != nil {
239 c.fail(w, r, e)
240 return
241 }
242 setCookie(w, inboxCookie, handle, int(inboxLifetime))
243 http.Redirect(w, r, FinishPath, http.StatusSeeOther)
244}
245
246// Finish receives the Lax cookies on the top-level GET after the callback's
247// redirect. Only its browser-bound transaction can reach Complete.
248func (c *Consumer) Finish(w http.ResponseWriter, r *http.Request) {
249 if !c.guard(w, r, http.MethodGet, FinishPath) {
250 return
251 }
252 if r.URL.RawQuery != "" {
253 c.fail(w, r, ErrRefused)
254 return
255 }
256 secret, ok := cookie(r, pendingCookie)
257 handle, have := cookie(r, inboxCookie)
258 if !ok || !have {
259 c.fail(w, r, ErrRefused)
260 return
261 }
262 setCookie(w, pendingCookie, "", -1)
263 setCookie(w, inboxCookie, "", -1)
264 existing := c.cfg.CurrentSubject(r)
265 claims, path, e := c.cfg.Store.Finish(r.Context(), secret, handle, existing, c.cfg.Now())
266 if e != nil {
267 c.fail(w, r, e)
268 return
269 }
270 if e = c.cfg.Complete(w, r, claims); e != nil {
271 c.fail(w, r, ErrStorage)
272 return
273 }
274 http.Redirect(w, r, path, http.StatusSeeOther)
275}
276