internal/store/users.go
517 lines · 15609 bytes
1package store
2
3import (
4 "database/sql"
5 "errors"
6 "fmt"
7 "strings"
8)
9
10type User struct {
11 ID int64
12 Username string
13 IsAdmin bool
14 Pending bool // self-registered, email not yet verified
15 Disabled bool // administratively suspended
16}
17
18type SSHKey struct {
19 ID int64
20 UserID int64
21 Fingerprint string
22 Algo string
23 Blob []byte
24 Scope string
25 Label string // "" when the key was added with no name
26 CreatedAt string
27 LastUsedAt string // "" when the key has never authenticated
28}
29
30// ErrDuplicateKey carries the exact user-facing message from the spec. It
31// deliberately does not name the owning account (enumeration oracle).
32var ErrDuplicateKey = errors.New("that key is already registered to another account; remove it there first or use a different key")
33
34var ErrNotFound = errors.New("not found")
35
36func (s *Store) CreateUser(username string, isAdmin bool) (int64, error) {
37 if taken, err := ownerNameTaken(s.DB, username); err != nil {
38 return 0, err
39 } else if taken {
40 return 0, fmt.Errorf("username %q is taken", username)
41 }
42 res, err := s.DB.Exec("INSERT INTO users (username, is_admin) VALUES (?, ?)", username, boolInt(isAdmin))
43 if err != nil {
44 if isUniqueErr(err) {
45 return 0, fmt.Errorf("username %q is taken", username)
46 }
47 return 0, err
48 }
49 return res.LastInsertId()
50}
51
52// DeleteUser removes an account whose removal orphans nothing: no owned
53// repositories, no authored issues, MRs, comments, or reviews, and not the
54// only admin of an org. Everything else (keys, emails, sessions, tokens,
55// pins, memberships, activity) cascades. Blockers come back as an error
56// naming what stands in the way, so the operator can transfer, delete, or
57// disable instead.
58func (s *Store) DeleteUser(id int64) error {
59 var blockers []string
60 var checkErr error
61 count := func(q string, what string) {
62 var n int
63 if err := s.DB.QueryRow(q, id).Scan(&n); err != nil {
64 if checkErr == nil {
65 checkErr = fmt.Errorf("checking %s: %w", what, err)
66 }
67 return
68 }
69 if n > 0 {
70 blockers = append(blockers, fmt.Sprintf("%d %s", n, what))
71 }
72 }
73 count("SELECT COUNT(*) FROM repos WHERE owner_kind = 'user' AND owner_id = ?", "owned repositories")
74 count("SELECT COUNT(*) FROM issues WHERE author_id = ?", "authored issues")
75 count("SELECT COUNT(*) FROM merge_requests WHERE author_id = ?", "authored merge requests")
76 count("SELECT COUNT(*) FROM issue_comments WHERE author_id = ?", "issue comments")
77 count("SELECT COUNT(*) FROM mr_comments WHERE author_id = ?", "MR comments")
78 count("SELECT COUNT(*) FROM mr_diff_comments WHERE author_id = ?", "diff comments")
79 count("SELECT COUNT(*) FROM mr_reviews WHERE reviewer_id = ?", "reviews")
80 count(`SELECT COUNT(*) FROM org_members m WHERE m.user_id = ? AND m.role = 'admin'
81 AND NOT EXISTS (SELECT 1 FROM org_members o
82 WHERE o.org_id = m.org_id AND o.role = 'admin' AND o.user_id != m.user_id)`,
83 "organizations with no other admin")
84 if checkErr != nil {
85 return checkErr
86 }
87 if len(blockers) > 0 {
88 return fmt.Errorf("account still anchors: %s — transfer or delete those first, or disable the account instead",
89 strings.Join(blockers, ", "))
90 }
91 res, err := s.DB.Exec("DELETE FROM users WHERE id = ?", id)
92 if err != nil {
93 return err
94 }
95 if n, _ := res.RowsAffected(); n == 0 {
96 return ErrNotFound
97 }
98 return nil
99}
100
101// OwnerExists reports whether a user or org owns the name — the ACME host
102// policy check for pages subdomains.
103func (s *Store) OwnerExists(name string) bool {
104 var n int
105 s.DB.QueryRow(`SELECT (SELECT COUNT(*) FROM users WHERE username = ?1)
106 + (SELECT COUNT(*) FROM orgs WHERE name = ?1)`, name).Scan(&n)
107 return n > 0
108}
109
110func (s *Store) UserByUsername(name string) (User, error) {
111 var u User
112 var admin, pending, disabled int
113 err := s.DB.QueryRow("SELECT id, username, is_admin, pending, disabled FROM users WHERE username = ?", name).
114 Scan(&u.ID, &u.Username, &admin, &pending, &disabled)
115 if errors.Is(err, sql.ErrNoRows) {
116 return u, ErrNotFound
117 }
118 u.IsAdmin = admin != 0
119 u.Pending = pending != 0
120 u.Disabled = disabled != 0
121 return u, err
122}
123
124// UserEmailAddresses returns every address on the account, verified or not.
125func (s *Store) UserEmailAddresses(userID int64) ([]string, error) {
126 rows, err := s.DB.Query("SELECT address FROM emails WHERE user_id = ? ORDER BY is_primary DESC, address", userID)
127 if err != nil {
128 return nil, err
129 }
130 defer rows.Close()
131 var out []string
132 for rows.Next() {
133 var a string
134 if err := rows.Scan(&a); err != nil {
135 return nil, err
136 }
137 out = append(out, a)
138 }
139 return out, rows.Err()
140}
141
142// Email is one address on an account, with the state the signature rules
143// and notification routing depend on.
144type Email struct {
145 Address string
146 Verified bool
147 VerifiedBy string // smtp | admin, empty when unverified
148 Primary bool
149}
150
151// ListEmails returns every address on the account with its state.
152func (s *Store) ListEmails(userID int64) ([]Email, error) {
153 rows, err := s.DB.Query(`SELECT address, verified_at IS NOT NULL,
154 COALESCE(verified_by, ''), is_primary
155 FROM emails WHERE user_id = ? ORDER BY is_primary DESC, address`, userID)
156 if err != nil {
157 return nil, err
158 }
159 defer rows.Close()
160 var out []Email
161 for rows.Next() {
162 var e Email
163 if err := rows.Scan(&e.Address, &e.Verified, &e.VerifiedBy, &e.Primary); err != nil {
164 return nil, err
165 }
166 out = append(out, e)
167 }
168 return out, rows.Err()
169}
170
171// SetUserDisabled suspends or restores an account. Disabling drops every
172// credential that would grant a session on its own — web sessions, API
173// tokens, unclaimed login links — and leaves the SSH keys registered but
174// refused at every entry point until re-enabled.
175func (s *Store) SetUserDisabled(userID int64, disabled bool) error {
176 v := 0
177 if disabled {
178 v = 1
179 }
180 res, err := s.DB.Exec("UPDATE users SET disabled = ? WHERE id = ?", v, userID)
181 if err != nil {
182 return err
183 }
184 if n, _ := res.RowsAffected(); n == 0 {
185 return ErrNotFound
186 }
187 if disabled {
188 // A pending login link is a session in waiting, so it goes with
189 // the sessions and API tokens. Re-enabling means minting again.
190 for _, table := range []string{"web_sessions", "api_tokens", "login_tokens"} {
191 if _, err = s.DB.Exec("DELETE FROM "+table+" WHERE user_id = ?", userID); err != nil {
192 return err
193 }
194 }
195 }
196 return err
197}
198
199// MailEnabled reports whether activity notifications reach the account
200// by mail as well as the inbox.
201func (s *Store) MailEnabled(userID int64) (bool, error) {
202 var on int
203 err := s.DB.QueryRow("SELECT notify_mail FROM users WHERE id = ?", userID).Scan(&on)
204 if errors.Is(err, sql.ErrNoRows) {
205 return false, ErrNotFound
206 }
207 return on != 0, err
208}
209
210func (s *Store) SetMailEnabled(userID int64, on bool) error {
211 v := 0
212 if on {
213 v = 1
214 }
215 _, err := s.DB.Exec("UPDATE users SET notify_mail = ? WHERE id = ?", v, userID)
216 return err
217}
218
219func (s *Store) UserByID(id int64) (User, error) {
220 var u User
221 var admin, pending, disabled int
222 err := s.DB.QueryRow("SELECT id, username, is_admin, pending, disabled FROM users WHERE id = ?", id).
223 Scan(&u.ID, &u.Username, &admin, &pending, &disabled)
224 if errors.Is(err, sql.ErrNoRows) {
225 return u, ErrNotFound
226 }
227 u.IsAdmin = admin != 0
228 u.Pending = pending != 0
229 u.Disabled = disabled != 0
230 return u, err
231}
232
233// AddSSHKey registers a key and bumps the key epoch in one transaction.
234func (s *Store) AddSSHKey(userID int64, fingerprint, algo string, blob []byte, scope, label string) error {
235 tx, err := s.DB.Begin()
236 if err != nil {
237 return err
238 }
239 defer tx.Rollback()
240 if _, err := tx.Exec(
241 "INSERT INTO ssh_keys (user_id, fingerprint, algo, blob, scope, label) VALUES (?, ?, ?, ?, ?, ?)",
242 userID, fingerprint, algo, blob, scope, label); err != nil {
243 if isUniqueErr(err) {
244 return ErrDuplicateKey
245 }
246 return err
247 }
248 if err := bumpKeyEpoch(tx); err != nil {
249 return err
250 }
251 return tx.Commit()
252}
253
254// RemoveSSHKey removes a key owned by userID and bumps the key epoch.
255func (s *Store) RemoveSSHKey(userID int64, fingerprint string) error {
256 tx, err := s.DB.Begin()
257 if err != nil {
258 return err
259 }
260 defer tx.Rollback()
261 res, err := tx.Exec("DELETE FROM ssh_keys WHERE user_id = ? AND fingerprint = ?", userID, fingerprint)
262 if err != nil {
263 return err
264 }
265 if n, _ := res.RowsAffected(); n == 0 {
266 return ErrNotFound
267 }
268 if err := bumpKeyEpoch(tx); err != nil {
269 return err
270 }
271 return tx.Commit()
272}
273
274// SetSSHKeyLabel renames a key owned by userID. Labels do not touch the
275// key epoch: nothing about authentication changes.
276func (s *Store) SetSSHKeyLabel(userID int64, fingerprint, label string) error {
277 res, err := s.DB.Exec("UPDATE ssh_keys SET label = ? WHERE user_id = ? AND fingerprint = ?", label, userID, fingerprint)
278 if err != nil {
279 return err
280 }
281 if n, _ := res.RowsAffected(); n == 0 {
282 return ErrNotFound
283 }
284 return nil
285}
286
287func (s *Store) SSHKeyByFingerprint(fingerprint string) (SSHKey, error) {
288 var k SSHKey
289 err := s.DB.QueryRow(
290 "SELECT id, user_id, fingerprint, algo, blob, scope, label FROM ssh_keys WHERE fingerprint = ?",
291 fingerprint).Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label)
292 if errors.Is(err, sql.ErrNoRows) {
293 return k, ErrNotFound
294 }
295 return k, err
296}
297
298func (s *Store) ListSSHKeys(userID int64) ([]SSHKey, error) {
299 rows, err := s.DB.Query(
300 `SELECT id, user_id, fingerprint, algo, blob, scope, label, created_at, COALESCE(last_used_at, '')
301 FROM ssh_keys WHERE user_id = ? ORDER BY id`,
302 userID)
303 if err != nil {
304 return nil, err
305 }
306 defer rows.Close()
307 var keys []SSHKey
308 for rows.Next() {
309 var k SSHKey
310 if err := rows.Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label, &k.CreatedAt, &k.LastUsedAt); err != nil {
311 return nil, err
312 }
313 keys = append(keys, k)
314 }
315 return keys, rows.Err()
316}
317
318// TouchSSHKey records key use; best-effort, callers ignore the error.
319func (s *Store) TouchSSHKey(id int64) error {
320 _, err := s.DB.Exec(
321 "UPDATE ssh_keys SET last_used_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?", id)
322 return err
323}
324
325// AddEmail adds an address; verifiedBy is "" (unverified), "smtp", or "admin".
326// Adding an already-verified address bumps the key epoch: it is a trust input
327// for signature states.
328func (s *Store) AddEmail(userID int64, address, verifiedBy string, primary bool) error {
329 tx, err := s.DB.Begin()
330 if err != nil {
331 return err
332 }
333 defer tx.Rollback()
334 var vAt, vBy any
335 if verifiedBy != "" {
336 vAt = "now"
337 vBy = verifiedBy
338 }
339 _, err = tx.Exec(
340 `INSERT INTO emails (user_id, address, verified_at, verified_by, is_primary)
341 VALUES (?, ?, CASE WHEN ? IS NULL THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%fZ','now') END, ?, ?)`,
342 userID, address, vAt, vBy, boolInt(primary))
343 if isUniqueErr(err) {
344 return fmt.Errorf("address %q is already in use", address)
345 }
346 if err != nil {
347 return err
348 }
349 if verifiedBy != "" {
350 if err := bumpKeyEpoch(tx); err != nil {
351 return err
352 }
353 }
354 return tx.Commit()
355}
356
357var (
358 ErrPrimaryEmail = errors.New("that is the primary address; make another address primary first")
359 ErrLastVerifiedEmail = errors.New("that is the only verified address on the account; verify another first")
360 ErrUnverifiedEmail = errors.New("that address is not verified")
361)
362
363// RemoveEmail drops an address from the account, and any verification
364// code pending for it. The primary and the last verified address stay:
365// activation, login links and commit identity all resolve through
366// verified addresses. Removing a verified address bumps the key epoch,
367// since the signature cache keys on verified addresses too.
368func (s *Store) RemoveEmail(userID int64, address string) error {
369 tx, err := s.DB.Begin()
370 if err != nil {
371 return err
372 }
373 defer tx.Rollback()
374 var primary, verified bool
375 err = tx.QueryRow("SELECT is_primary, verified_at IS NOT NULL FROM emails WHERE user_id = ? AND address = ?",
376 userID, address).Scan(&primary, &verified)
377 if errors.Is(err, sql.ErrNoRows) {
378 return ErrNotFound
379 }
380 if err != nil {
381 return err
382 }
383 if primary {
384 return ErrPrimaryEmail
385 }
386 if verified {
387 var others int
388 if err := tx.QueryRow("SELECT count(*) FROM emails WHERE user_id = ? AND verified_at IS NOT NULL AND address != ?",
389 userID, address).Scan(&others); err != nil {
390 return err
391 }
392 if others == 0 {
393 return ErrLastVerifiedEmail
394 }
395 }
396 if _, err := tx.Exec("DELETE FROM email_tokens WHERE user_id = ? AND address = ?", userID, address); err != nil {
397 return err
398 }
399 if _, err := tx.Exec("DELETE FROM emails WHERE user_id = ? AND address = ?", userID, address); err != nil {
400 return err
401 }
402 if verified {
403 if err := bumpKeyEpoch(tx); err != nil {
404 return err
405 }
406 }
407 return tx.Commit()
408}
409
410// SetPrimaryEmail makes a verified address the account's primary. The
411// verified set is unchanged, so the key epoch is not.
412func (s *Store) SetPrimaryEmail(userID int64, address string) error {
413 tx, err := s.DB.Begin()
414 if err != nil {
415 return err
416 }
417 defer tx.Rollback()
418 var verified bool
419 err = tx.QueryRow("SELECT verified_at IS NOT NULL FROM emails WHERE user_id = ? AND address = ?",
420 userID, address).Scan(&verified)
421 if errors.Is(err, sql.ErrNoRows) {
422 return ErrNotFound
423 }
424 if err != nil {
425 return err
426 }
427 if !verified {
428 return ErrUnverifiedEmail
429 }
430 if _, err := tx.Exec("UPDATE emails SET is_primary = 0 WHERE user_id = ?", userID); err != nil {
431 return err
432 }
433 if _, err := tx.Exec("UPDATE emails SET is_primary = 1 WHERE user_id = ? AND address = ?", userID, address); err != nil {
434 return err
435 }
436 return tx.Commit()
437}
438
439func (s *Store) KeyEpoch() (int64, error) {
440 var v int64
441 err := s.DB.QueryRow("SELECT value FROM settings WHERE key = 'key_epoch'").Scan(&v)
442 return v, err
443}
444
445type execer interface {
446 Exec(query string, args ...any) (sql.Result, error)
447}
448
449func bumpKeyEpoch(tx execer) error {
450 _, err := tx.Exec("UPDATE settings SET value = value + 1 WHERE key = 'key_epoch'")
451 return err
452}
453
454func boolInt(b bool) int {
455 if b {
456 return 1
457 }
458 return 0
459}
460
461func isUniqueErr(err error) bool {
462 return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed")
463}
464
465func (s *Store) SSHKeyByID(id int64) (SSHKey, error) {
466 var k SSHKey
467 err := s.DB.QueryRow(
468 "SELECT id, user_id, fingerprint, algo, blob, scope, label FROM ssh_keys WHERE id = ?",
469 id).Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label)
470 if errors.Is(err, sql.ErrNoRows) {
471 return k, ErrNotFound
472 }
473 return k, err
474}
475
476// ListDeployKeys returns the deploy keys bound to a repository.
477func (s *Store) ListDeployKeys(repoID int64) ([]SSHKey, error) {
478 rows, err := s.DB.Query(
479 "SELECT id, user_id, fingerprint, algo, blob, scope, label FROM ssh_keys WHERE scope LIKE 'deploy:' || ? || ':%' ORDER BY id",
480 repoID)
481 if err != nil {
482 return nil, err
483 }
484 defer rows.Close()
485 var keys []SSHKey
486 for rows.Next() {
487 var k SSHKey
488 if err := rows.Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label); err != nil {
489 return nil, err
490 }
491 keys = append(keys, k)
492 }
493 return keys, rows.Err()
494}
495
496// RemoveDeployKey removes a deploy key from a repository by fingerprint;
497// any repo admin may remove it regardless of who added it.
498func (s *Store) RemoveDeployKey(repoID int64, fingerprint string) error {
499 tx, err := s.DB.Begin()
500 if err != nil {
501 return err
502 }
503 defer tx.Rollback()
504 res, err := tx.Exec(
505 "DELETE FROM ssh_keys WHERE fingerprint = ? AND scope LIKE 'deploy:' || ? || ':%'",
506 fingerprint, repoID)
507 if err != nil {
508 return err
509 }
510 if n, _ := res.RowsAffected(); n == 0 {
511 return ErrNotFound
512 }
513 if err := bumpKeyEpoch(tx); err != nil {
514 return err
515 }
516 return tx.Commit()
517}