internal/store/users.go

c000478e0378e2282fcdc6af384481c608d4fed2
gitbay/internal/store/users.go history · blame · raw

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