| 1 | package setup |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/identity" |
| 5 | "amadan.net/rastrillo/rastrillo/auth" |
| 6 | "amadan.net/rastrillo/rastrillo/db" |
| 7 | "amadan.net/rastrillo/rastrillo/mail" |
| 8 | "amadan.net/rastrillo/rastrillo/pow" |
| 9 | "bytes" |
| 10 | "context" |
| 11 | "errors" |
| 12 | "log/slog" |
| 13 | "net/http" |
| 14 | "net/url" |
| 15 | "path" |
| 16 | "strings" |
| 17 | ) |
| 18 | |
| 19 | // SigninPath is the sign-in door, and ForgetPath rastrillo auth's Forget: |
| 20 | // "Use a different email" on the door and "Forget me on this device" on |
| 21 | // the signed-out page. |
| 22 | const ( |
| 23 | SigninPath = "/signin" |
| 24 | ForgetPath = "/auth/forget" |
| 25 | ) |
| 26 | |
| 27 | type SessionHandler struct { |
| 28 | Auth *auth.Auth |
| 29 | Authenticate func(http.Handler) http.Handler |
| 30 | Member func(context.Context, string) (Member, error) |
| 31 | Remember func(context.Context, Actor) error |
| 32 | // Door draws a's sign-in door for r with status: rastrillo's screen |
| 33 | // for auth's SigninState (the confirm step included), and with refused |
| 34 | // the refusal of an address that verified but may not sign in. |
| 35 | Door func(a *auth.Auth, w http.ResponseWriter, r *http.Request, status int, refused bool) |
| 36 | Failure func(http.ResponseWriter, *http.Request, int) |
| 37 | NotFound error |
| 38 | } |
| 39 | type AuthOptions struct { |
| 40 | Origin, Key string |
| 41 | AllowLoggedMail bool |
| 42 | MissingMailer, UnconfiguredMailer error |
| 43 | Normalize func(string) string |
| 44 | MayVerify func(context.Context, string) (bool, error) |
| 45 | Handler *SessionHandler |
| 46 | } |
| 47 | |
| 48 | func NewAuth(d *db.DB, o AuthOptions, mailer mail.Sender, logger *slog.Logger) (*auth.Auth, error) { |
| 49 | if mailer == nil { |
| 50 | return nil, o.MissingMailer |
| 51 | } |
| 52 | if !mail.IsConfigured(mailer) && !o.AllowLoggedMail { |
| 53 | return nil, o.UnconfiguredMailer |
| 54 | } |
| 55 | guard, err := pow.New(pow.Config{InstanceKey: o.Key, Nonces: pow.SQLNonces(d.Writer()), Difficulty: pow.NoProof, MinAge: pow.DefaultMinAge}) |
| 56 | if err != nil { |
| 57 | return nil, err |
| 58 | } |
| 59 | h := o.Handler |
| 60 | h.Auth, err = auth.New(auth.Config{ |
| 61 | DB: d.Writer(), Origin: o.Origin, InstanceKey: o.Key, Mailer: mailer, Logger: logger, |
| 62 | Proof: guard, KeymailServers: []string{"keymail.dev"}, SigninScreen: true, SigninOneWay: true, |
| 63 | SigninPath: SigninPath, BeginPath: "/auth/begin", ForgetPath: ForgetPath, SignedInPath: "/", |
| 64 | Authorize: func(address string) bool { |
| 65 | member, err := h.Member(context.Background(), address) |
| 66 | if err == nil && member.Active { |
| 67 | return true |
| 68 | } |
| 69 | if err != nil && !errors.Is(err, h.NotFound) { |
| 70 | return false |
| 71 | } |
| 72 | pending, err := o.MayVerify(context.Background(), address) |
| 73 | return err == nil && pending |
| 74 | }, |
| 75 | SubjectFor: func(address string) (string, error) { return o.Normalize(address), nil }, |
| 76 | RenderConfirm: func(w http.ResponseWriter, r *http.Request, _ auth.ConfirmPageData) { h.Signin(w, r) }, |
| 77 | // A link or Keymail proved the address and Authorize said no: the |
| 78 | // door with the refusal, in a 403, rather than rastrillo's bare text. |
| 79 | Refused: func(w http.ResponseWriter, r *http.Request, _ auth.Identity) { |
| 80 | h.door(w, r, http.StatusForbidden, true) |
| 81 | }, |
| 82 | }) |
| 83 | return h.Auth, err |
| 84 | } |
| 85 | func (h *SessionHandler) fail(w http.ResponseWriter, r *http.Request, status int) { |
| 86 | w.Header().Set("Cache-Control", "no-store") |
| 87 | h.Failure(w, r, status) |
| 88 | } |
| 89 | func (h *SessionHandler) Signin(w http.ResponseWriter, r *http.Request) { |
| 90 | if h.Auth == nil { |
| 91 | h.fail(w, r, http.StatusServiceUnavailable) |
| 92 | return |
| 93 | } |
| 94 | h.door(w, r, http.StatusOK, false) |
| 95 | } |
| 96 | |
| 97 | func (h *SessionHandler) door(w http.ResponseWriter, r *http.Request, status int, refused bool) { |
| 98 | if h.Door == nil { |
| 99 | h.fail(w, r, http.StatusServiceUnavailable) |
| 100 | return |
| 101 | } |
| 102 | h.Door(h.Auth, w, r, status, refused) |
| 103 | } |
| 104 | |
| 105 | // Active reports whether address is an active member: false, with no |
| 106 | // error, for one not on the team. |
| 107 | func (h *SessionHandler) Active(ctx context.Context, address string) (bool, error) { |
| 108 | member, err := h.Member(ctx, address) |
| 109 | if errors.Is(err, h.NotFound) { |
| 110 | return false, nil |
| 111 | } |
| 112 | return member.Active, err |
| 113 | } |
| 114 | |
| 115 | func (h *SessionHandler) RequireMember(next http.Handler) http.Handler { |
| 116 | if h.Auth == nil || h.Member == nil { |
| 117 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.fail(w, r, http.StatusServiceUnavailable) }) |
| 118 | } |
| 119 | authenticate := h.Auth.RequireSession |
| 120 | if h.Authenticate != nil { |
| 121 | authenticate = h.Authenticate |
| 122 | } |
| 123 | browser := authenticate(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 124 | w.Header().Set("Cache-Control", "no-store") |
| 125 | id, ok := identity.From(r) |
| 126 | if !ok { |
| 127 | h.fail(w, r, http.StatusForbidden) |
| 128 | return |
| 129 | } |
| 130 | member, err := h.Member(r.Context(), id.Address) |
| 131 | if err != nil && !errors.Is(err, h.NotFound) { |
| 132 | h.fail(w, r, http.StatusServiceUnavailable) |
| 133 | return |
| 134 | } |
| 135 | if err != nil || !member.Active || id.At.IsZero() || id.At.Unix() < member.SessionEpoch { |
| 136 | h.fail(w, r, http.StatusForbidden) |
| 137 | return |
| 138 | } |
| 139 | next.ServeHTTP(w, r) |
| 140 | })) |
| 141 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 142 | if len(r.Header.Values("Authorization")) != 0 { |
| 143 | w.Header().Set("Cache-Control", "no-store") |
| 144 | h.fail(w, r, http.StatusForbidden) |
| 145 | return |
| 146 | } |
| 147 | browser.ServeHTTP(w, r) |
| 148 | }) |
| 149 | } |
| 150 | |
| 151 | // Buffer the auth response until its newly minted session has been checked. |
| 152 | // This preserves the framework's return_to handling, including task deep links. |
| 153 | func (h *SessionHandler) RememberSignIn(next http.HandlerFunc) http.HandlerFunc { |
| 154 | return func(w http.ResponseWriter, r *http.Request) { |
| 155 | out := &signInResponse{header: make(http.Header)} |
| 156 | next(out, r) |
| 157 | response := http.Response{Header: out.header} |
| 158 | for _, cookie := range response.Cookies() { |
| 159 | if cookie.Name != h.Auth.SessionCookie() || cookie.Value == "" || cookie.MaxAge < 0 { |
| 160 | continue |
| 161 | } |
| 162 | // A minted session never lands on a sign-in page: a kept page |
| 163 | // that cleans to one (/./signed-out, /work/../signin) is "/". |
| 164 | if loc := out.header.Get("Location"); loc != "" && notALanding(loc) { |
| 165 | out.header.Set("Location", "/") |
| 166 | } |
| 167 | request := r.Clone(r.Context()) |
| 168 | request.Header = r.Header.Clone() |
| 169 | request.Header.Del("Cookie") |
| 170 | request.AddCookie(cookie) |
| 171 | id, ok := h.Auth.SessionFrom(request) |
| 172 | if !ok { |
| 173 | h.fail(w, r, http.StatusServiceUnavailable) |
| 174 | return |
| 175 | } |
| 176 | member, err := h.Member(r.Context(), id.Address) |
| 177 | // Invite recipients have verified an identity but have not joined yet. |
| 178 | if errors.Is(err, h.NotFound) || (err == nil && !member.Active) { |
| 179 | continue |
| 180 | } |
| 181 | if err == nil { |
| 182 | err = h.Remember(r.Context(), Actor{Address: id.Address}) |
| 183 | } |
| 184 | if err != nil { |
| 185 | h.fail(w, r, http.StatusServiceUnavailable) |
| 186 | return |
| 187 | } |
| 188 | } |
| 189 | for key, values := range out.header { |
| 190 | w.Header()[key] = values |
| 191 | } |
| 192 | status := out.status |
| 193 | if status == 0 { |
| 194 | status = http.StatusOK |
| 195 | } |
| 196 | w.WriteHeader(status) |
| 197 | _, _ = w.Write(out.body.Bytes()) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // notALanding reports whether a redirect's path, cleaned as the browser |
| 202 | // will clean it (backslashes as slashes), is /signed-out or a sign-in |
| 203 | // page: no place for a session just minted to land. |
| 204 | func notALanding(loc string) bool { |
| 205 | u, err := url.Parse(loc) |
| 206 | if err != nil { |
| 207 | return true |
| 208 | } |
| 209 | p := path.Clean("/" + strings.ReplaceAll(u.Path, "\\", "/")) |
| 210 | return p == "/signed-out" || p == "/signin" || strings.HasPrefix(p, "/signin/") || p == "/auth" || strings.HasPrefix(p, "/auth/") |
| 211 | } |
| 212 | |
| 213 | type signInResponse struct { |
| 214 | header http.Header |
| 215 | status int |
| 216 | body bytes.Buffer |
| 217 | } |
| 218 | |
| 219 | func (w *signInResponse) Header() http.Header { return w.header } |
| 220 | func (w *signInResponse) WriteHeader(status int) { |
| 221 | if w.status == 0 { |
| 222 | w.status = status |
| 223 | } |
| 224 | } |
| 225 | func (w *signInResponse) Write(b []byte) (int, error) { |
| 226 | if w.status == 0 { |
| 227 | w.status = http.StatusOK |
| 228 | } |
| 229 | return w.body.Write(b) |
| 230 | } |
| 231 | |