service.go231 lines, 7.6 KB
| 1 | // Package auth is the auth service: users, passwords, and the tokens that |
| 2 | // prove who a request comes from. |
| 3 | package auth |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/rand" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "log/slog" |
| 11 | "net/mail" |
| 12 | "strings" |
| 13 | "time" |
| 14 | "unicode/utf8" |
| 15 | |
| 16 | "github.com/fiston-user/payments/internal/auth/authdb" |
| 17 | "github.com/fiston-user/payments/internal/platform/apperr" |
| 18 | "github.com/google/uuid" |
| 19 | "github.com/jackc/pgx/v5" |
| 20 | "github.com/jackc/pgx/v5/pgconn" |
| 21 | "github.com/jackc/pgx/v5/pgxpool" |
| 22 | ) |
| 23 | |
| 24 | // Errors clients see. Login and refresh failures say as little as possible. |
| 25 | var ( |
| 26 | ErrEmailTaken = fmt.Errorf("%w: email already registered", apperr.ErrConflict) |
| 27 | ErrInvalidCredentials = fmt.Errorf("%w: invalid email or password", apperr.ErrUnauthenticated) |
| 28 | ErrInvalidRefreshToken = fmt.Errorf("%w: invalid refresh token", apperr.ErrUnauthenticated) |
| 29 | ErrUserNotFound = fmt.Errorf("user %w", apperr.ErrNotFound) |
| 30 | ) |
| 31 | |
| 32 | // User is a registered user. It has no password hash on purpose: nothing |
| 33 | // outside this package ever needs it. |
| 34 | type User struct { |
| 35 | ID uuid.UUID |
| 36 | Email string |
| 37 | CreatedAt time.Time |
| 38 | } |
| 39 | |
| 40 | func toUser(u authdb.User) User { |
| 41 | return User{ID: u.ID, Email: u.Email, CreatedAt: u.CreatedAt} |
| 42 | } |
| 43 | |
| 44 | // Tokens are what a login or a refresh returns. |
| 45 | type Tokens struct { |
| 46 | Access string // a JWT, for every request |
| 47 | ExpiresIn time.Duration // how long Access lasts |
| 48 | Refresh string // opaque, used once, to get the next Tokens |
| 49 | } |
| 50 | |
| 51 | // Service is the auth service's business logic. Its queries are simple, so it |
| 52 | // uses the generated code directly, without a store in between. |
| 53 | type Service struct { |
| 54 | pool *pgxpool.Pool |
| 55 | q *authdb.Queries |
| 56 | signer *Signer |
| 57 | refreshTTL time.Duration |
| 58 | dummyHash string |
| 59 | } |
| 60 | |
| 61 | // NewService returns a Service that keeps users and refresh tokens in pool's |
| 62 | // database, and signs access tokens with signer. |
| 63 | func NewService(pool *pgxpool.Pool, signer *Signer, refreshTTL time.Duration) *Service { |
| 64 | // What Login checks a password against when the email isn't registered. |
| 65 | // Its password is random, and thrown away. |
| 66 | dummy, _ := HashPassword(context.Background(), rand.Text()) // only fails if canceled |
| 67 | return &Service{ |
| 68 | pool: pool, |
| 69 | q: authdb.New(pool), |
| 70 | signer: signer, |
| 71 | refreshTTL: refreshTTL, |
| 72 | dummyHash: dummy, |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | // Register creates a user. Emails are unique without regard to case. |
| 77 | func (s *Service) Register(ctx context.Context, email, password string) (User, error) { |
| 78 | email = strings.TrimSpace(email) |
| 79 | var v apperr.ValidationError |
| 80 | if addr, err := mail.ParseAddress(email); err != nil || addr.Address != email || len(email) > 254 { |
| 81 | v.Add("email", "must be an email address, like alice@example.com") |
| 82 | } |
| 83 | // Length is what makes a password strong. No rules about digits or symbols. |
| 84 | if n := utf8.RuneCountInString(password); n < 12 || n > 128 { |
| 85 | v.Add("password", "must be 12 to 128 characters long") |
| 86 | } |
| 87 | if err := v.Err(); err != nil { |
| 88 | return User{}, err |
| 89 | } |
| 90 | |
| 91 | hash, err := HashPassword(ctx, password) |
| 92 | if err != nil { |
| 93 | return User{}, err |
| 94 | } |
| 95 | u, err := s.q.CreateUser(ctx, authdb.CreateUserParams{Email: email, PasswordHash: hash}) |
| 96 | if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok && pgErr.Code == "23505" { |
| 97 | return User{}, ErrEmailTaken // unique_violation |
| 98 | } |
| 99 | if err != nil { |
| 100 | return User{}, fmt.Errorf("create user: %w", err) |
| 101 | } |
| 102 | return toUser(u), nil |
| 103 | } |
| 104 | |
| 105 | // Login checks a user's email and password, and starts a session: a new |
| 106 | // refresh token family. A wrong password and an unknown email look exactly |
| 107 | // the same, so nobody can find out who has an account. |
| 108 | func (s *Service) Login(ctx context.Context, email, password string) (Tokens, error) { |
| 109 | u, err := s.q.GetUserByEmail(ctx, strings.TrimSpace(email)) |
| 110 | if errors.Is(err, pgx.ErrNoRows) { |
| 111 | // Hash anyway, so this takes as long as a wrong password does. |
| 112 | VerifyPassword(ctx, password, s.dummyHash) |
| 113 | return Tokens{}, ErrInvalidCredentials |
| 114 | } |
| 115 | if err != nil { |
| 116 | return Tokens{}, fmt.Errorf("get user: %w", err) |
| 117 | } |
| 118 | ok, err := VerifyPassword(ctx, password, u.PasswordHash) |
| 119 | if err != nil { |
| 120 | return Tokens{}, err |
| 121 | } |
| 122 | if !ok { |
| 123 | return Tokens{}, ErrInvalidCredentials |
| 124 | } |
| 125 | return s.issue(ctx, s.q, u.ID, uuid.New(), nil) |
| 126 | } |
| 127 | |
| 128 | // issue makes a new pair of tokens for a user: an access token, and a refresh |
| 129 | // token in family. parent is the refresh token it replaces, or nil. |
| 130 | func (s *Service) issue( |
| 131 | ctx context.Context, q *authdb.Queries, userID, family uuid.UUID, parent *uuid.UUID, |
| 132 | ) (Tokens, error) { |
| 133 | // Roles are read every time: one that's taken away is gone from the next |
| 134 | // access token, fifteen minutes later at most. |
| 135 | u, err := q.GetUser(ctx, userID) |
| 136 | if err != nil { |
| 137 | return Tokens{}, fmt.Errorf("get user: %w", err) |
| 138 | } |
| 139 | now := time.Now() |
| 140 | access, err := s.signer.Issue(userID, now, u.Roles...) |
| 141 | if err != nil { |
| 142 | return Tokens{}, err |
| 143 | } |
| 144 | refresh := newRefreshToken() |
| 145 | err = q.CreateRefreshToken(ctx, authdb.CreateRefreshTokenParams{ |
| 146 | UserID: userID, |
| 147 | TokenHash: hashToken(refresh), |
| 148 | FamilyID: family, |
| 149 | ParentID: parent, |
| 150 | ExpiresAt: now.Add(s.refreshTTL), |
| 151 | }) |
| 152 | if err != nil { |
| 153 | return Tokens{}, fmt.Errorf("store refresh token: %w", err) |
| 154 | } |
| 155 | return Tokens{Access: access, ExpiresIn: s.signer.ttl, Refresh: refresh}, nil |
| 156 | } |
| 157 | |
| 158 | // Refresh trades a refresh token for a new pair, and retires the old one, so |
| 159 | // each refresh token works once. If a retired token comes back, two parties |
| 160 | // hold copies of it, and we can't tell which one is the thief: we revoke its |
| 161 | // whole family, and the user logs in again. |
| 162 | func (s *Service) Refresh(ctx context.Context, token string) (Tokens, error) { |
| 163 | tx, err := s.pool.Begin(ctx) |
| 164 | if err != nil { |
| 165 | return Tokens{}, fmt.Errorf("begin: %w", err) |
| 166 | } |
| 167 | defer tx.Rollback(ctx) |
| 168 | q := s.q.WithTx(tx) |
| 169 | |
| 170 | // The row lock makes two refreshes with the same token take turns: the |
| 171 | // second one sees that the first one rotated it. |
| 172 | old, err := q.GetRefreshTokenForUpdate(ctx, hashToken(token)) |
| 173 | if errors.Is(err, pgx.ErrNoRows) { |
| 174 | return Tokens{}, ErrInvalidRefreshToken |
| 175 | } |
| 176 | if err != nil { |
| 177 | return Tokens{}, fmt.Errorf("get refresh token: %w", err) |
| 178 | } |
| 179 | |
| 180 | switch { |
| 181 | case old.RevokedAt.Valid || !old.ExpiresAt.After(time.Now()): |
| 182 | return Tokens{}, ErrInvalidRefreshToken |
| 183 | case old.RotatedAt.Valid: |
| 184 | // Reuse. Revoke the family, and commit that, even though we fail. |
| 185 | n, err := q.RevokeFamily(ctx, old.FamilyID) |
| 186 | if err != nil { |
| 187 | return Tokens{}, fmt.Errorf("revoke family: %w", err) |
| 188 | } |
| 189 | if err := tx.Commit(ctx); err != nil { |
| 190 | return Tokens{}, fmt.Errorf("commit: %w", err) |
| 191 | } |
| 192 | slog.WarnContext(ctx, "refresh token reused, family revoked", |
| 193 | "user_id", old.UserID, "family_id", old.FamilyID, "revoked", n) |
| 194 | return Tokens{}, ErrInvalidRefreshToken |
| 195 | } |
| 196 | |
| 197 | // Rotate: retire the old token, and issue its successor in the same family. |
| 198 | if err := q.RotateRefreshToken(ctx, old.ID); err != nil { |
| 199 | return Tokens{}, fmt.Errorf("rotate refresh token: %w", err) |
| 200 | } |
| 201 | tokens, err := s.issue(ctx, q, old.UserID, old.FamilyID, &old.ID) |
| 202 | if err != nil { |
| 203 | return Tokens{}, err |
| 204 | } |
| 205 | if err := tx.Commit(ctx); err != nil { |
| 206 | return Tokens{}, fmt.Errorf("commit: %w", err) |
| 207 | } |
| 208 | return tokens, nil |
| 209 | } |
| 210 | |
| 211 | // Logout ends the session that token belongs to, by revoking its family. An |
| 212 | // unknown token is not an error: the session is over either way. Access |
| 213 | // tokens already issued keep working until they expire. |
| 214 | func (s *Service) Logout(ctx context.Context, token string) error { |
| 215 | if _, err := s.q.RevokeFamilyOf(ctx, hashToken(token)); err != nil { |
| 216 | return fmt.Errorf("revoke family: %w", err) |
| 217 | } |
| 218 | return nil |
| 219 | } |
| 220 | |
| 221 | // User returns the user with the given ID. |
| 222 | func (s *Service) User(ctx context.Context, id uuid.UUID) (User, error) { |
| 223 | u, err := s.q.GetUser(ctx, id) |
| 224 | if errors.Is(err, pgx.ErrNoRows) { |
| 225 | return User{}, ErrUserNotFound |
| 226 | } |
| 227 | if err != nil { |
| 228 | return User{}, fmt.Errorf("get user: %w", err) |
| 229 | } |
| 230 | return toUser(u), nil |
| 231 | } |