| 1 | package oficinaid |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/rastrillo/rastrillo/carlos" |
| 5 | "amadan.net/rastrillo/rastrillo/clientip" |
| 6 | "encoding/base64" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "mime" |
| 10 | "net/http" |
| 11 | "net/url" |
| 12 | stdpath "path" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/equipo/identity" |
| 18 | "amadan.net/oficina/home/handoff" |
| 19 | "amadan.net/rastrillo/rastrillo/auth" |
| 20 | "amadan.net/rastrillo/rastrillo/sessions" |
| 21 | "github.com/go-chi/chi/v5" |
| 22 | "github.com/keymaildev/signin" |
| 23 | ) |
| 24 | |
| 25 | const pendingCookie = "__Host-equipo-id-pending" |
| 26 | const inboxCookie = "__Host-equipo-id-inbox" |
| 27 | const initCookie = "__Host-equipo-id-init" |
| 28 | const proofCookie = "__Host-equipo-id-proof" |
| 29 | const reauthCookie = "__Host-equipo-id-reauth" |
| 30 | const logoutCookie = "__Host-equipo-id-logout" |
| 31 | const settingsPath = "/conversation/settings/oficina-id" |
| 32 | |
| 33 | type View struct { |
| 34 | State string |
| 35 | Subject string |
| 36 | LinkedAt time.Time |
| 37 | HomeSignout string |
| 38 | } |
| 39 | type HTTP struct { |
| 40 | startOnce sync.Once |
| 41 | startLimiter *signin.MemoryLimiter |
| 42 | Store *Store |
| 43 | Auth *auth.Auth |
| 44 | Render func(http.ResponseWriter, *http.Request, View, int) |
| 45 | // SignedIn, when set, is called once Finish has minted a web session |
| 46 | // on w (minted), before the redirect: the sign-in door's memory of an |
| 47 | // Oficina ID sign-in. |
| 48 | SignedIn func(w http.ResponseWriter, r *http.Request, minted *http.Cookie) |
| 49 | } |
| 50 | |
| 51 | func cookie(r *http.Request, name string) string { |
| 52 | value := "" |
| 53 | n := 0 |
| 54 | for _, c := range r.Cookies() { |
| 55 | if c.Name == name { |
| 56 | n++ |
| 57 | value = c.Value |
| 58 | } |
| 59 | } |
| 60 | if n != 1 || len(value) != 43 { |
| 61 | return "" |
| 62 | } |
| 63 | b, e := base64.RawURLEncoding.Strict().DecodeString(value) |
| 64 | if e != nil || len(b) != 32 || base64.RawURLEncoding.EncodeToString(b) != value { |
| 65 | return "" |
| 66 | } |
| 67 | return value |
| 68 | } |
| 69 | func set(w http.ResponseWriter, name, value string, seconds int) { |
| 70 | http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", MaxAge: seconds, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| 71 | } |
| 72 | func (h *HTTP) token(r *http.Request) string { return cookie(r, h.Auth.SessionCookie()) } |
| 73 | func (h *HTTP) fail(w http.ResponseWriter, r *http.Request, e error) { |
| 74 | state := "failed" |
| 75 | status := http.StatusBadRequest |
| 76 | if errors.Is(e, ErrUnlinked) { |
| 77 | state = "unlinked" |
| 78 | status = http.StatusForbidden |
| 79 | } else if errors.Is(e, ErrUnavailable) { |
| 80 | // Storage failed: nothing is known, so try again later. |
| 81 | status = http.StatusServiceUnavailable |
| 82 | w.Header().Set("Retry-After", "5") |
| 83 | } |
| 84 | h.Render(w, r, View{State: state}, status) |
| 85 | } |
| 86 | func (h *HTTP) guard(next http.HandlerFunc) http.HandlerFunc { |
| 87 | return func(w http.ResponseWriter, r *http.Request) { |
| 88 | w.Header().Set("Cache-Control", "no-store") |
| 89 | w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") |
| 90 | if r.Host != strings.TrimPrefix(h.Store.Origin, "https://") { |
| 91 | h.fail(w, r, ErrRefused) |
| 92 | return |
| 93 | } |
| 94 | for _, name := range []string{h.Auth.SessionCookie(), pendingCookie, inboxCookie, initCookie, proofCookie, reauthCookie} { |
| 95 | n := 0 |
| 96 | for _, c := range r.Cookies() { |
| 97 | if c.Name == name { |
| 98 | n++ |
| 99 | } |
| 100 | } |
| 101 | if n > 1 { |
| 102 | h.fail(w, r, ErrRefused) |
| 103 | return |
| 104 | } |
| 105 | } |
| 106 | if r.Method == http.MethodPost && r.URL.Path != "/auth/assertion" { |
| 107 | v := r.Header.Values("Origin") |
| 108 | if len(v) != 1 || v[0] != h.Store.Origin { |
| 109 | h.fail(w, r, ErrRefused) |
| 110 | return |
| 111 | } |
| 112 | } |
| 113 | next(w, r) |
| 114 | } |
| 115 | } |
| 116 | func (h *HTTP) Routes(r chi.Router) { |
| 117 | r.Post(NativePath, h.NativeExchange) |
| 118 | r.Get("/auth/home", h.guard(h.Start)) |
| 119 | r.Get("/auth/start", h.guard(h.Start)) |
| 120 | r.Handle("/auth/assertion", h.guard(h.Callback)) |
| 121 | r.Get("/auth/finish", h.guard(h.Finish)) |
| 122 | r.Get(settingsPath, h.guard(h.Settings)) |
| 123 | r.Post("/account/home/reauth", h.guard(h.BeginReauth)) |
| 124 | r.Get("/account/home/reauth-complete", h.guard(h.CompleteReauth)) |
| 125 | r.Get("/account/home/confirm", h.guard(h.Confirmation)) |
| 126 | r.Post("/account/home/confirm", h.guard(h.Confirm)) |
| 127 | r.Get("/account/home/unlink", h.guard(h.UnlinkPage)) |
| 128 | r.Post("/account/home/unlink", h.guard(h.Unlink)) |
| 129 | r.Get("/signed-out", h.guard(h.SignedOut)) |
| 130 | } |
| 131 | func (h *HTTP) Start(w http.ResponseWriter, r *http.Request) { |
| 132 | q, e := url.ParseQuery(r.URL.RawQuery) |
| 133 | if e != nil || len(q) > 1 || len(q["return_to"]) > 1 { |
| 134 | h.fail(w, r, ErrRefused) |
| 135 | return |
| 136 | } |
| 137 | path := "/" |
| 138 | if len(q) > 0 { |
| 139 | if len(q["return_to"]) != 1 { |
| 140 | h.fail(w, r, ErrRefused) |
| 141 | return |
| 142 | } |
| 143 | path = q.Get("return_to") |
| 144 | } |
| 145 | init := cookie(r, initCookie) |
| 146 | start := h.Store.Exchange.Start |
| 147 | if init != "" { |
| 148 | path = "/account/home/confirm" |
| 149 | start = h.Store.Exchange.StartFresh |
| 150 | } else if strings.HasPrefix(path, "/account/home/") { |
| 151 | h.fail(w, r, ErrRefused) |
| 152 | return |
| 153 | } |
| 154 | if !handoff.SafePath(path) { |
| 155 | h.fail(w, r, ErrRefused) |
| 156 | return |
| 157 | } |
| 158 | if u, e := url.Parse(path); e == nil && stdpath.Clean("/"+strings.ReplaceAll(u.Path, "\\", "/")) == "/signed-out" { |
| 159 | path = "/" // a fresh sign-in never lands on "You’re signed out" |
| 160 | } |
| 161 | h.startOnce.Do(func() { h.startLimiter = signin.NewMemoryLimiter(10 * time.Minute) }) |
| 162 | hops := 0 |
| 163 | if carlos.Running() { |
| 164 | hops = clientip.DefaultHops |
| 165 | } |
| 166 | allowed, err := h.startLimiter.Allow(r.Context(), clientip.From(r, hops), time.Now(), 20) |
| 167 | if err != nil || !allowed { |
| 168 | w.Header().Set("Retry-After", "600") |
| 169 | h.Render(w, r, View{State: "failed"}, http.StatusTooManyRequests) |
| 170 | return |
| 171 | } |
| 172 | secret, nonce, e := start(r.Context(), path, cookie(r, pendingCookie), time.Now()) |
| 173 | if e != nil { |
| 174 | h.fail(w, r, e) |
| 175 | return |
| 176 | } |
| 177 | if init != "" { |
| 178 | if e = h.Store.Bind(r.Context(), init, h.token(r), nonce, time.Now()); e != nil { |
| 179 | h.fail(w, r, e) |
| 180 | return |
| 181 | } |
| 182 | } |
| 183 | set(w, pendingCookie, secret, 600) |
| 184 | q = url.Values{"consumer": {h.Store.Config.ConsumerID}, "nonce": {nonce}} |
| 185 | if init != "" { |
| 186 | q.Set("max_age", "300") |
| 187 | } |
| 188 | http.Redirect(w, r, h.Store.Config.Issuer+"/authorize?"+q.Encode(), http.StatusSeeOther) |
| 189 | } |
| 190 | func (h *HTTP) Callback(w http.ResponseWriter, r *http.Request) { |
| 191 | if r.Method != http.MethodPost { |
| 192 | w.Header().Set("Allow", http.MethodPost) |
| 193 | h.Render(w, r, View{State: "failed"}, http.StatusMethodNotAllowed) |
| 194 | return |
| 195 | } |
| 196 | origins := r.Header.Values("Origin") |
| 197 | media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 198 | if len(origins) != 1 || origins[0] != h.Store.Config.Issuer || r.URL.RawQuery != "" || e != nil || media != "application/x-www-form-urlencoded" { |
| 199 | h.fail(w, r, ErrRefused) |
| 200 | return |
| 201 | } |
| 202 | b, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024)) |
| 203 | if e != nil { |
| 204 | h.fail(w, r, e) |
| 205 | return |
| 206 | } |
| 207 | form, e := url.ParseQuery(string(b)) |
| 208 | if e != nil || len(form) != 1 || len(form["assertion"]) != 1 { |
| 209 | h.fail(w, r, ErrRefused) |
| 210 | return |
| 211 | } |
| 212 | handle, e := h.Store.Exchange.ReceivePending(r.Context(), form.Get("assertion"), time.Now()) |
| 213 | if e != nil { |
| 214 | h.fail(w, r, e) |
| 215 | return |
| 216 | } |
| 217 | set(w, inboxCookie, handle, 120) |
| 218 | http.Redirect(w, r, "/auth/finish", http.StatusSeeOther) |
| 219 | } |
| 220 | func (h *HTTP) Finish(w http.ResponseWriter, r *http.Request) { |
| 221 | if r.URL.RawQuery != "" { |
| 222 | h.fail(w, r, ErrRefused) |
| 223 | return |
| 224 | } |
| 225 | init := cookie(r, initCookie) |
| 226 | result, path, e := h.Store.Finish(r.Context(), cookie(r, pendingCookie), cookie(r, inboxCookie), h.token(r), init, time.Now()) |
| 227 | set(w, pendingCookie, "", -1) |
| 228 | set(w, inboxCookie, "", -1) |
| 229 | set(w, initCookie, "", -1) |
| 230 | if e != nil { |
| 231 | h.fail(w, r, e) |
| 232 | return |
| 233 | } |
| 234 | if init != "" { |
| 235 | set(w, proofCookie, result, 300) |
| 236 | } else { |
| 237 | set(w, h.Auth.SessionCookie(), result, 30*24*3600) |
| 238 | if h.SignedIn != nil { |
| 239 | h.SignedIn(w, r, &http.Cookie{Name: h.Auth.SessionCookie(), Value: result}) |
| 240 | } |
| 241 | } |
| 242 | http.Redirect(w, r, path, http.StatusSeeOther) |
| 243 | } |
| 244 | func (h *HTTP) Settings(w http.ResponseWriter, r *http.Request) { |
| 245 | linked, e := h.Store.Linked(r.Context(), h.token(r), time.Now()) |
| 246 | if errors.Is(e, ErrRefused) { |
| 247 | http.Redirect(w, r, "/signin?return_to="+url.QueryEscape(settingsPath), http.StatusSeeOther) |
| 248 | return |
| 249 | } |
| 250 | if e != nil { |
| 251 | // Unknown, not signed out: the door would send it straight back. |
| 252 | h.fail(w, r, ErrUnavailable) |
| 253 | return |
| 254 | } |
| 255 | h.Render(w, r, View{State: "settings", Subject: linked.Subject, LinkedAt: linked.At}, 200) |
| 256 | } |
| 257 | func (h *HTTP) BeginReauth(w http.ResponseWriter, r *http.Request) { |
| 258 | r.Body = http.MaxBytesReader(w, r.Body, 1024) |
| 259 | if r.ParseForm() != nil { |
| 260 | h.fail(w, r, ErrRefused) |
| 261 | return |
| 262 | } |
| 263 | secret, e := h.Store.BeginReauth(r.Context(), h.token(r), r.PostForm.Get("purpose"), time.Now()) |
| 264 | if e != nil { |
| 265 | h.fail(w, r, e) |
| 266 | return |
| 267 | } |
| 268 | set(w, reauthCookie, secret, 300) |
| 269 | set(w, initCookie, "", -1) |
| 270 | set(w, proofCookie, "", -1) |
| 271 | // A step-up: the email-only door, which never offers Oficina ID. |
| 272 | http.Redirect(w, r, "/signin/local?force=1&reauth=1&return_to=%2Faccount%2Fhome%2Freauth-complete", http.StatusSeeOther) |
| 273 | } |
| 274 | func (h *HTTP) CompleteReauth(w http.ResponseWriter, r *http.Request) { |
| 275 | next, purpose, e := h.Store.CompleteReauth(r.Context(), cookie(r, reauthCookie), h.token(r), time.Now()) |
| 276 | if e != nil { |
| 277 | h.fail(w, r, e) |
| 278 | return |
| 279 | } |
| 280 | if purpose == "link" { |
| 281 | set(w, reauthCookie, "", -1) |
| 282 | set(w, initCookie, next, 300) |
| 283 | http.Redirect(w, r, "/auth/home", http.StatusSeeOther) |
| 284 | } else { |
| 285 | http.Redirect(w, r, "/account/home/unlink", http.StatusSeeOther) |
| 286 | } |
| 287 | } |
| 288 | func (h *HTTP) Confirmation(w http.ResponseWriter, r *http.Request) { |
| 289 | if e := h.Store.Pending(r.Context(), cookie(r, proofCookie), h.token(r), time.Now()); e != nil { |
| 290 | h.fail(w, r, e) |
| 291 | return |
| 292 | } |
| 293 | h.Render(w, r, View{State: "confirm"}, 200) |
| 294 | } |
| 295 | func (h *HTTP) Confirm(w http.ResponseWriter, r *http.Request) { |
| 296 | if e := h.Store.Confirm(r.Context(), cookie(r, proofCookie), h.token(r), time.Now()); e != nil { |
| 297 | h.fail(w, r, e) |
| 298 | return |
| 299 | } |
| 300 | set(w, proofCookie, "", -1) |
| 301 | http.Redirect(w, r, settingsPath, http.StatusSeeOther) |
| 302 | } |
| 303 | func (h *HTTP) UnlinkPage(w http.ResponseWriter, r *http.Request) { |
| 304 | if _, e := h.Store.Session(r.Context(), h.token(r), time.Now()); e != nil { |
| 305 | h.fail(w, r, e) |
| 306 | return |
| 307 | } |
| 308 | h.Render(w, r, View{State: "unlink"}, 200) |
| 309 | } |
| 310 | func (h *HTTP) Unlink(w http.ResponseWriter, r *http.Request) { |
| 311 | if e := h.Store.Unlink(r.Context(), cookie(r, reauthCookie), h.token(r), time.Now()); e != nil { |
| 312 | h.fail(w, r, e) |
| 313 | return |
| 314 | } |
| 315 | set(w, reauthCookie, "", -1) |
| 316 | http.Redirect(w, r, settingsPath, http.StatusSeeOther) |
| 317 | } |
| 318 | func (h *HTTP) Session(r *http.Request) (auth.Identity, bool) { |
| 319 | raw, ok := h.Auth.SessionFrom(r) |
| 320 | if !ok { |
| 321 | return auth.Identity{}, false |
| 322 | } |
| 323 | if !IsHomeDerived(string(raw.Method)) { |
| 324 | return raw, true |
| 325 | } |
| 326 | sess, e := h.Store.Session(r.Context(), h.token(r), time.Now()) |
| 327 | if e != nil { |
| 328 | return auth.Identity{}, false |
| 329 | } |
| 330 | return auth.Identity{Address: sess.Subject, Method: signin.Method(sess.Method), AuthTime: sess.AuthTime, At: sess.At}, true |
| 331 | } |
| 332 | func (h *HTTP) Authenticate(next http.Handler) http.Handler { |
| 333 | return h.Auth.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 334 | raw, ok := auth.From(r) |
| 335 | if !ok { |
| 336 | h.fail(w, r, ErrRefused) |
| 337 | return |
| 338 | } |
| 339 | if !IsHomeDerived(string(raw.Method)) { |
| 340 | next.ServeHTTP(w, r) |
| 341 | return |
| 342 | } |
| 343 | sess, e := h.Store.Session(r.Context(), h.token(r), time.Now()) |
| 344 | if e != nil { |
| 345 | h.fail(w, r, e) |
| 346 | return |
| 347 | } |
| 348 | id := auth.Identity{Address: sess.Subject, Method: signin.Method(sess.Method), AuthTime: sess.AuthTime, At: sess.At} |
| 349 | next.ServeHTTP(w, identity.With(sessions.WithSession(r, sess), id)) |
| 350 | })) |
| 351 | } |
| 352 | |