internal/store/users.go
538 lines · 16219 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
219// WatchEnabled reports whether the account hears about every issue and
220// merge request on the repositories it can write to, without a
221// repo_watchers row on each (#194).
222func (s *Store) WatchEnabled(userID int64) (bool, error) {
223 var on int
224 err := s.DB.QueryRow("SELECT notify_watch FROM users WHERE id = ?", userID).Scan(&on)
225 if errors.Is(err, sql.ErrNoRows) {
226 return false, ErrNotFound
227 }
228 return on != 0, err
229}
230
231func (s *Store) SetWatchEnabled(userID int64, on bool) error {
232 v := 0
233 if on {
234 v = 1
235 }
236 _, err := s.DB.Exec("UPDATE users SET notify_watch = ? WHERE id = ?", v, userID)
237 return err
238}
239
240func (s *Store) UserByID(id int64) (User, error) {
241 var u User
242 var admin, pending, disabled int
243 err := s.DB.QueryRow("SELECT id, username, is_admin, pending, disabled FROM users WHERE id = ?", id).
244 Scan(&u.ID, &u.Username, &admin, &pending, &disabled)
245 if errors.Is(err, sql.ErrNoRows) {
246 return u, ErrNotFound
247 }
248 u.IsAdmin = admin != 0
249 u.Pending = pending != 0
250 u.Disabled = disabled != 0
251 return u, err
252}
253
254// AddSSHKey registers a key and bumps the key epoch in one transaction.
255func (s *Store) AddSSHKey(userID int64, fingerprint, algo string, blob []byte, scope, label string) error {
256 tx, err := s.DB.Begin()
257 if err != nil {
258 return err
259 }
260 defer tx.Rollback()
261 if _, err := tx.Exec(
262 "INSERT INTO ssh_keys (user_id, fingerprint, algo, blob, scope, label) VALUES (?, ?, ?, ?, ?, ?)",
263 userID, fingerprint, algo, blob, scope, label); err != nil {
264 if isUniqueErr(err) {
265 return ErrDuplicateKey
266 }
267 return err
268 }
269 if err := bumpKeyEpoch(tx); err != nil {
270 return err
271 }
272 return tx.Commit()
273}
274
275// RemoveSSHKey removes a key owned by userID and bumps the key epoch.
276func (s *Store) RemoveSSHKey(userID int64, fingerprint string) error {
277 tx, err := s.DB.Begin()
278 if err != nil {
279 return err
280 }
281 defer tx.Rollback()
282 res, err := tx.Exec("DELETE FROM ssh_keys WHERE user_id = ? AND fingerprint = ?", userID, fingerprint)
283 if err != nil {
284 return err
285 }
286 if n, _ := res.RowsAffected(); n == 0 {
287 return ErrNotFound
288 }
289 if err := bumpKeyEpoch(tx); err != nil {
290 return err
291 }
292 return tx.Commit()
293}
294
295// SetSSHKeyLabel renames a key owned by userID. Labels do not touch the
296// key epoch: nothing about authentication changes.
297func (s *Store) SetSSHKeyLabel(userID int64, fingerprint, label string) error {
298 res, err := s.DB.Exec("UPDATE ssh_keys SET label = ? WHERE user_id = ? AND fingerprint = ?", label, userID, fingerprint)
299 if err != nil {
300 return err
301 }
302 if n, _ := res.RowsAffected(); n == 0 {
303 return ErrNotFound
304 }
305 return nil
306}
307
308func (s *Store) SSHKeyByFingerprint(fingerprint string) (SSHKey, error) {
309 var k SSHKey
310 err := s.DB.QueryRow(
311 "SELECT id, user_id, fingerprint, algo, blob, scope, label FROM ssh_keys WHERE fingerprint = ?",
312 fingerprint).Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label)
313 if errors.Is(err, sql.ErrNoRows) {
314 return k, ErrNotFound
315 }
316 return k, err
317}
318
319func (s *Store) ListSSHKeys(userID int64) ([]SSHKey, error) {
320 rows, err := s.DB.Query(
321 `SELECT id, user_id, fingerprint, algo, blob, scope, label, created_at, COALESCE(last_used_at, '')
322 FROM ssh_keys WHERE user_id = ? ORDER BY id`,
323 userID)
324 if err != nil {
325 return nil, err
326 }
327 defer rows.Close()
328 var keys []SSHKey
329 for rows.Next() {
330 var k SSHKey
331 if err := rows.Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label, &k.CreatedAt, &k.LastUsedAt); err != nil {
332 return nil, err
333 }
334 keys = append(keys, k)
335 }
336 return keys, rows.Err()
337}
338
339// TouchSSHKey records key use; best-effort, callers ignore the error.
340func (s *Store) TouchSSHKey(id int64) error {
341 _, err := s.DB.Exec(
342 "UPDATE ssh_keys SET last_used_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?", id)
343 return err
344}
345
346// AddEmail adds an address; verifiedBy is "" (unverified), "smtp", or "admin".
347// Adding an already-verified address bumps the key epoch: it is a trust input
348// for signature states.
349func (s *Store) AddEmail(userID int64, address, verifiedBy string, primary bool) error {
350 tx, err := s.DB.Begin()
351 if err != nil {
352 return err
353 }
354 defer tx.Rollback()
355 var vAt, vBy any
356 if verifiedBy != "" {
357 vAt = "now"
358 vBy = verifiedBy
359 }
360 _, err = tx.Exec(
361 `INSERT INTO emails (user_id, address, verified_at, verified_by, is_primary)
362 VALUES (?, ?, CASE WHEN ? IS NULL THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%fZ','now') END, ?, ?)`,
363 userID, address, vAt, vBy, boolInt(primary))
364 if isUniqueErr(err) {
365 return fmt.Errorf("address %q is already in use", address)
366 }
367 if err != nil {
368 return err
369 }
370 if verifiedBy != "" {
371 if err := bumpKeyEpoch(tx); err != nil {
372 return err
373 }
374 }
375 return tx.Commit()
376}
377
378var (
379 ErrPrimaryEmail = errors.New("that is the primary address; make another address primary first")
380 ErrLastVerifiedEmail = errors.New("that is the only verified address on the account; verify another first")
381 ErrUnverifiedEmail = errors.New("that address is not verified")
382)
383
384// RemoveEmail drops an address from the account, and any verification
385// code pending for it. The primary and the last verified address stay:
386// activation, login links and commit identity all resolve through
387// verified addresses. Removing a verified address bumps the key epoch,
388// since the signature cache keys on verified addresses too.
389func (s *Store) RemoveEmail(userID int64, address string) error {
390 tx, err := s.DB.Begin()
391 if err != nil {
392 return err
393 }
394 defer tx.Rollback()
395 var primary, verified bool
396 err = tx.QueryRow("SELECT is_primary, verified_at IS NOT NULL FROM emails WHERE user_id = ? AND address = ?",
397 userID, address).Scan(&primary, &verified)
398 if errors.Is(err, sql.ErrNoRows) {
399 return ErrNotFound
400 }
401 if err != nil {
402 return err
403 }
404 if primary {
405 return ErrPrimaryEmail
406 }
407 if verified {
408 var others int
409 if err := tx.QueryRow("SELECT count(*) FROM emails WHERE user_id = ? AND verified_at IS NOT NULL AND address != ?",
410 userID, address).Scan(&others); err != nil {
411 return err
412 }
413 if others == 0 {
414 return ErrLastVerifiedEmail
415 }
416 }
417 if _, err := tx.Exec("DELETE FROM email_tokens WHERE user_id = ? AND address = ?", userID, address); err != nil {
418 return err
419 }
420 if _, err := tx.Exec("DELETE FROM emails WHERE user_id = ? AND address = ?", userID, address); err != nil {
421 return err
422 }
423 if verified {
424 if err := bumpKeyEpoch(tx); err != nil {
425 return err
426 }
427 }
428 return tx.Commit()
429}
430
431// SetPrimaryEmail makes a verified address the account's primary. The
432// verified set is unchanged, so the key epoch is not.
433func (s *Store) SetPrimaryEmail(userID int64, address string) error {
434 tx, err := s.DB.Begin()
435 if err != nil {
436 return err
437 }
438 defer tx.Rollback()
439 var verified bool
440 err = tx.QueryRow("SELECT verified_at IS NOT NULL FROM emails WHERE user_id = ? AND address = ?",
441 userID, address).Scan(&verified)
442 if errors.Is(err, sql.ErrNoRows) {
443 return ErrNotFound
444 }
445 if err != nil {
446 return err
447 }
448 if !verified {
449 return ErrUnverifiedEmail
450 }
451 if _, err := tx.Exec("UPDATE emails SET is_primary = 0 WHERE user_id = ?", userID); err != nil {
452 return err
453 }
454 if _, err := tx.Exec("UPDATE emails SET is_primary = 1 WHERE user_id = ? AND address = ?", userID, address); err != nil {
455 return err
456 }
457 return tx.Commit()
458}
459
460func (s *Store) KeyEpoch() (int64, error) {
461 var v int64
462 err := s.DB.QueryRow("SELECT value FROM settings WHERE key = 'key_epoch'").Scan(&v)
463 return v, err
464}
465
466type execer interface {
467 Exec(query string, args ...any) (sql.Result, error)
468}
469
470func bumpKeyEpoch(tx execer) error {
471 _, err := tx.Exec("UPDATE settings SET value = value + 1 WHERE key = 'key_epoch'")
472 return err
473}
474
475func boolInt(b bool) int {
476 if b {
477 return 1
478 }
479 return 0
480}
481
482func isUniqueErr(err error) bool {
483 return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed")
484}
485
486func (s *Store) SSHKeyByID(id int64) (SSHKey, error) {
487 var k SSHKey
488 err := s.DB.QueryRow(
489 "SELECT id, user_id, fingerprint, algo, blob, scope, label FROM ssh_keys WHERE id = ?",
490 id).Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label)
491 if errors.Is(err, sql.ErrNoRows) {
492 return k, ErrNotFound
493 }
494 return k, err
495}
496
497// ListDeployKeys returns the deploy keys bound to a repository.
498func (s *Store) ListDeployKeys(repoID int64) ([]SSHKey, error) {
499 rows, err := s.DB.Query(
500 "SELECT id, user_id, fingerprint, algo, blob, scope, label FROM ssh_keys WHERE scope LIKE 'deploy:' || ? || ':%' ORDER BY id",
501 repoID)
502 if err != nil {
503 return nil, err
504 }
505 defer rows.Close()
506 var keys []SSHKey
507 for rows.Next() {
508 var k SSHKey
509 if err := rows.Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label); err != nil {
510 return nil, err
511 }
512 keys = append(keys, k)
513 }
514 return keys, rows.Err()
515}
516
517// RemoveDeployKey removes a deploy key from a repository by fingerprint;
518// any repo admin may remove it regardless of who added it.
519func (s *Store) RemoveDeployKey(repoID int64, fingerprint string) error {
520 tx, err := s.DB.Begin()
521 if err != nil {
522 return err
523 }
524 defer tx.Rollback()
525 res, err := tx.Exec(
526 "DELETE FROM ssh_keys WHERE fingerprint = ? AND scope LIKE 'deploy:' || ? || ':%'",
527 fingerprint, repoID)
528 if err != nil {
529 return err
530 }
531 if n, _ := res.RowsAffected(); n == 0 {
532 return ErrNotFound
533 }
534 if err := bumpKeyEpoch(tx); err != nil {
535 return err
536 }
537 return tx.Commit()
538}