internal/store/users.go
651 lines · 20692 bytes
48 symbols in this file
UserSSHKeySSHKey.ExpiredErrDuplicateKeyErrNotFoundStore.CreateUserStore.DeleteUserStore.OwnerExistsStore.UserByUsernameStore.UserEmailAddressesEmailStore.ListEmailsStore.SetUserDisabledStore.MailEnabledStore.SetMailEnabledStore.ReplyEnabledStore.SetReplyEnabledStore.WatchEnabledStore.SetWatchEnabledStore.ThemeStore.SetThemeStore.DiffLayoutStore.SetDiffLayoutStore.UserByIDStore.userByKeyOriginStore.AddSSHKeyStore.AddSSHKeyFromStore.RemoveSSHKeyStore.removeKeyStore.SetSSHKeyLabelStore.SSHKeyByFingerprintStore.ListSSHKeysStore.TouchSSHKeyStore.AddEmailErrPrimaryEmailErrLastVerifiedEmailErrUnverifiedEmailStore.RemoveEmailStore.SetPrimaryEmailStore.KeyEpochexecerbumpKeyEpochboolIntisUniqueErrStore.SSHKeyByIDStore.ListDeployKeysStore.RemoveDeployKey
1package store
2
3import (
4 "database/sql"
5 "errors"
6 "fmt"
7 "strings"
8 "time"
9)
10
11type User struct {
12 ID int64
13 Username string
14 IsAdmin bool
15 Pending bool // self-registered, email not yet verified
16 Disabled bool // administratively suspended, or scheduled for deletion
17 // DeleteAfter is when a scheduled deletion purges the account, ""
18 // when none is scheduled. A scheduled account is also Disabled.
19 DeleteAfter string
20 Ghost bool // stands in as the author of deleted accounts' content
21 // SignedInAt is when the browser session this user came from was
22 // created by a login. Set by WebSessionUser only; zero elsewhere.
23 SignedInAt time.Time
24}
25
26type SSHKey struct {
27 ID int64
28 UserID int64
29 Fingerprint string
30 Algo string
31 Blob []byte
32 Scope string
33 Label string // "" when the key was added with no name
34 CreatedAt string
35 LastUsedAt string // "" when the key has never authenticated
36 CreatedBy string // name of the API token that added the key; "" for none. ListSSHKeys only.
37 ExpiresAt *time.Time // nil when the key never expires
38}
39
40// Expired reports whether the key has lapsed at now.
41func (k SSHKey) Expired(now time.Time) bool {
42 return k.ExpiresAt != nil && !k.ExpiresAt.After(now)
43}
44
45// ErrDuplicateKey carries the exact user-facing message from the spec. It
46// deliberately does not name the owning account (enumeration oracle).
47var ErrDuplicateKey = errors.New("that key is already registered to another account; remove it there first or use a different key")
48
49var ErrNotFound = errors.New("not found")
50
51func (s *Store) CreateUser(username string, isAdmin bool) (int64, error) {
52 if taken, err := ownerNameTaken(s.DB, username); err != nil {
53 return 0, err
54 } else if taken {
55 return 0, fmt.Errorf("username %q is taken", username)
56 }
57 res, err := s.DB.Exec("INSERT INTO users (username, is_admin) VALUES (?, ?)", username, boolInt(isAdmin))
58 if err != nil {
59 if isUniqueErr(err) {
60 return 0, fmt.Errorf("username %q is taken", username)
61 }
62 return 0, err
63 }
64 return res.LastInsertId()
65}
66
67// DeleteUser removes an account whose removal orphans nothing: no owned
68// repositories, no authored issues, MRs, comments, or reviews, and not the
69// only admin of an org. Everything else (keys, emails, sessions, tokens,
70// pins, memberships, activity) cascades. Blockers come back as an error
71// naming what stands in the way, so the operator can transfer, delete, or
72// disable instead.
73func (s *Store) DeleteUser(id int64) error {
74 var blockers []string
75 var checkErr error
76 count := func(q string, what string) {
77 var n int
78 if err := s.DB.QueryRow(q, id).Scan(&n); err != nil {
79 if checkErr == nil {
80 checkErr = fmt.Errorf("checking %s: %w", what, err)
81 }
82 return
83 }
84 if n > 0 {
85 blockers = append(blockers, fmt.Sprintf("%d %s", n, what))
86 }
87 }
88 count("SELECT COUNT(*) FROM repos WHERE owner_kind = 'user' AND owner_id = ?", "owned repositories")
89 count("SELECT COUNT(*) FROM issues WHERE author_id = ?", "authored issues")
90 count("SELECT COUNT(*) FROM merge_requests WHERE author_id = ?", "authored merge requests")
91 count("SELECT COUNT(*) FROM issue_comments WHERE author_id = ?", "issue comments")
92 count("SELECT COUNT(*) FROM mr_comments WHERE author_id = ?", "MR comments")
93 count("SELECT COUNT(*) FROM mr_diff_comments WHERE author_id = ?", "diff comments")
94 count("SELECT COUNT(*) FROM mr_reviews WHERE reviewer_id = ?", "reviews")
95 count(`SELECT COUNT(*) FROM org_members m WHERE m.user_id = ? AND m.role = 'admin'
96 AND NOT EXISTS (SELECT 1 FROM org_members o
97 WHERE o.org_id = m.org_id AND o.role = 'admin' AND o.user_id != m.user_id)`,
98 "organizations with no other admin")
99 if checkErr != nil {
100 return checkErr
101 }
102 if len(blockers) > 0 {
103 return fmt.Errorf("account still anchors: %s — transfer or delete those first, or disable the account instead",
104 strings.Join(blockers, ", "))
105 }
106 // Grants and a parked about text name the account by id with no
107 // foreign key, so they go in the same transaction (#306).
108 tx, err := s.DB.Begin()
109 if err != nil {
110 return err
111 }
112 defer tx.Rollback()
113 if _, err := tx.Exec("DELETE FROM repo_access WHERE subject_kind = 'user' AND subject_id = ?", id); err != nil {
114 return err
115 }
116 if _, err := tx.Exec("DELETE FROM profile_about_backfill WHERE owner_kind = 'user' AND owner_id = ?", id); err != nil {
117 return err
118 }
119 res, err := tx.Exec("DELETE FROM users WHERE id = ?", id)
120 if err != nil {
121 return err
122 }
123 if n, _ := res.RowsAffected(); n == 0 {
124 return ErrNotFound
125 }
126 if err := tx.Commit(); err != nil {
127 return err
128 }
129 s.announce(Revoked{UserID: id})
130 return nil
131}
132
133// OwnerExists reports whether a user or org owns the name — the ACME host
134// policy check for pages subdomains.
135func (s *Store) OwnerExists(name string) bool {
136 var n int
137 s.DB.QueryRow(`SELECT (SELECT COUNT(*) FROM users WHERE username = ?1)
138 + (SELECT COUNT(*) FROM orgs WHERE name = ?1)`, name).Scan(&n)
139 return n > 0
140}
141
142func (s *Store) UserByUsername(name string) (User, error) {
143 return s.userBy("username", name)
144}
145
146// UserEmailAddresses returns every address on the account, verified or not.
147func (s *Store) UserEmailAddresses(userID int64) ([]string, error) {
148 rows, err := s.DB.Query("SELECT address FROM emails WHERE user_id = ? ORDER BY is_primary DESC, address", userID)
149 if err != nil {
150 return nil, err
151 }
152 defer rows.Close()
153 var out []string
154 for rows.Next() {
155 var a string
156 if err := rows.Scan(&a); err != nil {
157 return nil, err
158 }
159 out = append(out, a)
160 }
161 return out, rows.Err()
162}
163
164// Email is one address on an account, with the state the signature rules
165// and notification routing depend on.
166type Email struct {
167 Address string
168 Verified bool
169 VerifiedBy string // smtp | admin, empty when unverified
170 Primary bool
171}
172
173// ListEmails returns every address on the account with its state.
174func (s *Store) ListEmails(userID int64) ([]Email, error) {
175 rows, err := s.DB.Query(`SELECT address, verified_at IS NOT NULL,
176 COALESCE(verified_by, ''), is_primary
177 FROM emails WHERE user_id = ? ORDER BY is_primary DESC, address`, userID)
178 if err != nil {
179 return nil, err
180 }
181 defer rows.Close()
182 var out []Email
183 for rows.Next() {
184 var e Email
185 if err := rows.Scan(&e.Address, &e.Verified, &e.VerifiedBy, &e.Primary); err != nil {
186 return nil, err
187 }
188 out = append(out, e)
189 }
190 return out, rows.Err()
191}
192
193// SetUserDisabled suspends or restores an account. Disabling drops every
194// credential that would grant a session on its own — web sessions, API
195// tokens, unclaimed login links — and leaves the SSH keys registered but
196// refused at every entry point until re-enabled; connections they opened
197// are closed.
198func (s *Store) SetUserDisabled(userID int64, disabled bool) error {
199 v := 0
200 if _, err := s.DB.Exec("DELETE FROM account_deletions WHERE user_id = ?", userID); err != nil {
201 return err
202 }
203 if disabled {
204 v = 1
205 }
206 // An admin's decision replaces a scheduled or requested deletion
207 // either way: a disabled account stays disabled and is not purged,
208 // an enabled one is back in use. A purge already under way finishes.
209 res, err := s.DB.Exec("UPDATE users SET disabled = ?, delete_after = CASE WHEN delete_after = ? THEN delete_after END WHERE id = ?", v, Purging, userID)
210 if err != nil {
211 return err
212 }
213 if n, _ := res.RowsAffected(); n == 0 {
214 return ErrNotFound
215 }
216 if disabled {
217 // A pending login link is a session in waiting, so it goes with
218 // the sessions and API tokens. Re-enabling means minting again.
219 for _, table := range []string{"web_sessions", "api_tokens", "login_tokens"} {
220 if _, err = s.DB.Exec("DELETE FROM "+table+" WHERE user_id = ?", userID); err != nil {
221 return err
222 }
223 }
224 s.announce(Revoked{UserID: userID})
225 }
226 return err
227}
228
229// MailEnabled reports whether activity notifications reach the account
230// by mail as well as the inbox.
231func (s *Store) MailEnabled(userID int64) (bool, error) {
232 var on int
233 err := s.DB.QueryRow("SELECT notify_mail FROM users WHERE id = ?", userID).Scan(&on)
234 if errors.Is(err, sql.ErrNoRows) {
235 return false, ErrNotFound
236 }
237 return on != 0, err
238}
239
240func (s *Store) SetMailEnabled(userID int64, on bool) error {
241 v := 0
242 if on {
243 v = 1
244 }
245 _, err := s.DB.Exec("UPDATE users SET notify_mail = ? WHERE id = ?", v, userID)
246 return err
247}
248
249// ReplyEnabled reports whether the account's issue and merge request
250// mail carries a reply address (#295).
251func (s *Store) ReplyEnabled(userID int64) (bool, error) {
252 var on int
253 err := s.DB.QueryRow("SELECT notify_reply FROM users WHERE id = ?", userID).Scan(&on)
254 if errors.Is(err, sql.ErrNoRows) {
255 return false, ErrNotFound
256 }
257 return on != 0, err
258}
259
260func (s *Store) SetReplyEnabled(userID int64, on bool) error {
261 v := 0
262 if on {
263 v = 1
264 }
265 _, err := s.DB.Exec("UPDATE users SET notify_reply = ? WHERE id = ?", v, userID)
266 return err
267}
268
269// WatchEnabled reports whether the account hears about every issue and
270// merge request on the repositories it can write to, without a
271// repo_watchers row on each (#194).
272func (s *Store) WatchEnabled(userID int64) (bool, error) {
273 var on int
274 err := s.DB.QueryRow("SELECT notify_watch FROM users WHERE id = ?", userID).Scan(&on)
275 if errors.Is(err, sql.ErrNoRows) {
276 return false, ErrNotFound
277 }
278 return on != 0, err
279}
280
281func (s *Store) SetWatchEnabled(userID int64, on bool) error {
282 v := 0
283 if on {
284 v = 1
285 }
286 _, err := s.DB.Exec("UPDATE users SET notify_watch = ? WHERE id = ?", v, userID)
287 return err
288}
289
290// Theme is the web colour scheme the account chose: system, light or
291// dark (#232).
292func (s *Store) Theme(userID int64) (string, error) {
293 var theme string
294 err := s.DB.QueryRow("SELECT theme FROM users WHERE id = ?", userID).Scan(&theme)
295 if errors.Is(err, sql.ErrNoRows) {
296 return "", ErrNotFound
297 }
298 return theme, err
299}
300
301func (s *Store) SetTheme(userID int64, theme string) error {
302 _, err := s.DB.Exec("UPDATE users SET theme = ? WHERE id = ?", theme, userID)
303 return err
304}
305
306// DiffLayout is how the account wants diffs drawn on the web: unified or
307// split (#290).
308func (s *Store) DiffLayout(userID int64) (string, error) {
309 var l string
310 err := s.DB.QueryRow("SELECT diff_layout FROM users WHERE id = ?", userID).Scan(&l)
311 if errors.Is(err, sql.ErrNoRows) {
312 return "", ErrNotFound
313 }
314 return l, err
315}
316
317func (s *Store) SetDiffLayout(userID int64, layout string) error {
318 _, err := s.DB.Exec("UPDATE users SET diff_layout = ? WHERE id = ?", layout, userID)
319 return err
320}
321
322func (s *Store) UserByID(id int64) (User, error) {
323 return s.userBy("id", id)
324}
325
326// userBy reads the account whose column equals v.
327func (s *Store) userBy(column string, v any) (User, error) {
328 var u User
329 var admin, pending, disabled, ghost int
330 var deleteAfter sql.NullString
331 err := s.DB.QueryRow("SELECT id, username, is_admin, pending, disabled, delete_after, ghost FROM users WHERE "+column+" = ?", v).
332 Scan(&u.ID, &u.Username, &admin, &pending, &disabled, &deleteAfter, &ghost)
333 if errors.Is(err, sql.ErrNoRows) {
334 return u, ErrNotFound
335 }
336 u.IsAdmin = admin != 0
337 u.Pending = pending != 0
338 u.Disabled = disabled != 0
339 u.DeleteAfter = deleteAfter.String
340 u.Ghost = ghost != 0
341 return u, err
342}
343
344// KeyOrigin is how a key came to be.
345type KeyOrigin struct {
346 CreatedByToken int64 // the API token that added it; 0 for none
347 ExpiresAt *time.Time // when it stops authenticating; nil for never
348}
349
350// AddSSHKey registers a key and bumps the key epoch in one transaction.
351func (s *Store) AddSSHKey(userID int64, fingerprint, algo string, blob []byte, scope, label string) error {
352 return s.AddSSHKeyFrom(userID, fingerprint, algo, blob, scope, label, KeyOrigin{})
353}
354
355// AddSSHKeyFrom is AddSSHKey recording where the key came from.
356func (s *Store) AddSSHKeyFrom(userID int64, fingerprint, algo string, blob []byte, scope, label string, o KeyOrigin) error {
357 tx, err := s.DB.Begin()
358 if err != nil {
359 return err
360 }
361 defer tx.Rollback()
362 var exp any
363 if o.ExpiresAt != nil {
364 exp = fmtTime(*o.ExpiresAt)
365 }
366 if _, err := tx.Exec(
367 "INSERT INTO ssh_keys (user_id, fingerprint, algo, blob, scope, label, created_by_token, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
368 userID, fingerprint, algo, blob, scope, label, nullID(o.CreatedByToken), exp); err != nil {
369 if isUniqueErr(err) {
370 return ErrDuplicateKey
371 }
372 return err
373 }
374 if err := bumpKeyEpoch(tx); err != nil {
375 return err
376 }
377 return tx.Commit()
378}
379
380// RemoveSSHKey removes a key owned by userID, bumps the key epoch, and
381// announces the revocation.
382func (s *Store) RemoveSSHKey(userID int64, fingerprint string) error {
383 return s.removeKey("DELETE FROM ssh_keys WHERE user_id = ? AND fingerprint = ? RETURNING id", userID, fingerprint)
384}
385
386// removeKey deletes the key that query (a DELETE ... RETURNING id)
387// matches, bumps the key epoch, and announces the revocation.
388func (s *Store) removeKey(query string, args ...any) error {
389 tx, err := s.DB.Begin()
390 if err != nil {
391 return err
392 }
393 defer tx.Rollback()
394 var id int64
395 err = tx.QueryRow(query, args...).Scan(&id)
396 if errors.Is(err, sql.ErrNoRows) {
397 return ErrNotFound
398 }
399 if err != nil {
400 return err
401 }
402 if err := bumpKeyEpoch(tx); err != nil {
403 return err
404 }
405 if err := tx.Commit(); err != nil {
406 return err
407 }
408 s.announce(Revoked{KeyIDs: []int64{id}})
409 return nil
410}
411
412// SetSSHKeyLabel renames a key owned by userID. Labels do not touch the
413// key epoch: nothing about authentication changes.
414func (s *Store) SetSSHKeyLabel(userID int64, fingerprint, label string) error {
415 res, err := s.DB.Exec("UPDATE ssh_keys SET label = ? WHERE user_id = ? AND fingerprint = ?", label, userID, fingerprint)
416 if err != nil {
417 return err
418 }
419 if n, _ := res.RowsAffected(); n == 0 {
420 return ErrNotFound
421 }
422 return nil
423}
424
425func (s *Store) SSHKeyByFingerprint(fingerprint string) (SSHKey, error) {
426 var k SSHKey
427 var exp sql.NullString
428 err := s.DB.QueryRow(
429 "SELECT id, user_id, fingerprint, algo, blob, scope, label, expires_at FROM ssh_keys WHERE fingerprint = ?",
430 fingerprint).Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label, &exp)
431 if errors.Is(err, sql.ErrNoRows) {
432 return k, ErrNotFound
433 }
434 k.ExpiresAt = parseTime(exp)
435 return k, err
436}
437
438func (s *Store) ListSSHKeys(userID int64) ([]SSHKey, error) {
439 rows, err := s.DB.Query(
440 `SELECT k.id, k.user_id, k.fingerprint, k.algo, k.blob, k.scope, k.label, k.created_at,
441 COALESCE(k.last_used_at, ''), COALESCE(t.name, ''), k.expires_at
442 FROM ssh_keys k LEFT JOIN api_tokens t ON t.id = k.created_by_token
443 WHERE k.user_id = ? ORDER BY k.id`,
444 userID)
445 if err != nil {
446 return nil, err
447 }
448 defer rows.Close()
449 var keys []SSHKey
450 for rows.Next() {
451 var k SSHKey
452 var exp sql.NullString
453 if err := rows.Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label, &k.CreatedAt, &k.LastUsedAt, &k.CreatedBy, &exp); err != nil {
454 return nil, err
455 }
456 k.ExpiresAt = parseTime(exp)
457 keys = append(keys, k)
458 }
459 return keys, rows.Err()
460}
461
462// TouchSSHKey records key use; best-effort, callers ignore the error.
463func (s *Store) TouchSSHKey(id int64) error {
464 _, err := s.DB.Exec(
465 "UPDATE ssh_keys SET last_used_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?", id)
466 return err
467}
468
469// AddEmail adds an address; verifiedBy is "" (unverified), "smtp", or "admin".
470// Adding an already-verified address bumps the key epoch: it is a trust input
471// for signature states.
472func (s *Store) AddEmail(userID int64, address, verifiedBy string, primary bool) error {
473 tx, err := s.DB.Begin()
474 if err != nil {
475 return err
476 }
477 defer tx.Rollback()
478 var vAt, vBy any
479 if verifiedBy != "" {
480 vAt = "now"
481 vBy = verifiedBy
482 }
483 _, err = tx.Exec(
484 `INSERT INTO emails (user_id, address, verified_at, verified_by, is_primary)
485 VALUES (?, ?, CASE WHEN ? IS NULL THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%fZ','now') END, ?, ?)`,
486 userID, address, vAt, vBy, boolInt(primary))
487 if isUniqueErr(err) {
488 return fmt.Errorf("address %q is already in use", address)
489 }
490 if err != nil {
491 return err
492 }
493 if verifiedBy != "" {
494 if err := bumpKeyEpoch(tx); err != nil {
495 return err
496 }
497 }
498 return tx.Commit()
499}
500
501var (
502 ErrPrimaryEmail = errors.New("that is the primary address; make another address primary first")
503 ErrLastVerifiedEmail = errors.New("that is the only verified address on the account; verify another first")
504 ErrUnverifiedEmail = errors.New("that address is not verified")
505)
506
507// RemoveEmail drops an address from the account, and any verification
508// code pending for it. The primary and the last verified address stay:
509// activation, login links and commit identity all resolve through
510// verified addresses. Removing a verified address bumps the key epoch,
511// since the signature cache keys on verified addresses too.
512func (s *Store) RemoveEmail(userID int64, address string) error {
513 tx, err := s.DB.Begin()
514 if err != nil {
515 return err
516 }
517 defer tx.Rollback()
518 var primary, verified bool
519 err = tx.QueryRow("SELECT is_primary, verified_at IS NOT NULL FROM emails WHERE user_id = ? AND address = ?",
520 userID, address).Scan(&primary, &verified)
521 if errors.Is(err, sql.ErrNoRows) {
522 return ErrNotFound
523 }
524 if err != nil {
525 return err
526 }
527 if primary {
528 return ErrPrimaryEmail
529 }
530 if verified {
531 var others int
532 if err := tx.QueryRow("SELECT count(*) FROM emails WHERE user_id = ? AND verified_at IS NOT NULL AND address != ?",
533 userID, address).Scan(&others); err != nil {
534 return err
535 }
536 if others == 0 {
537 return ErrLastVerifiedEmail
538 }
539 }
540 if _, err := tx.Exec("DELETE FROM email_tokens WHERE user_id = ? AND address = ?", userID, address); err != nil {
541 return err
542 }
543 if _, err := tx.Exec("DELETE FROM emails WHERE user_id = ? AND address = ?", userID, address); err != nil {
544 return err
545 }
546 if verified {
547 if err := bumpKeyEpoch(tx); err != nil {
548 return err
549 }
550 }
551 return tx.Commit()
552}
553
554// SetPrimaryEmail makes a verified address the account's primary. The
555// verified set is unchanged, so the key epoch is not.
556func (s *Store) SetPrimaryEmail(userID int64, address string) error {
557 tx, err := s.DB.Begin()
558 if err != nil {
559 return err
560 }
561 defer tx.Rollback()
562 var verified bool
563 err = tx.QueryRow("SELECT verified_at IS NOT NULL FROM emails WHERE user_id = ? AND address = ?",
564 userID, address).Scan(&verified)
565 if errors.Is(err, sql.ErrNoRows) {
566 return ErrNotFound
567 }
568 if err != nil {
569 return err
570 }
571 if !verified {
572 return ErrUnverifiedEmail
573 }
574 if _, err := tx.Exec("UPDATE emails SET is_primary = 0 WHERE user_id = ?", userID); err != nil {
575 return err
576 }
577 if _, err := tx.Exec("UPDATE emails SET is_primary = 1 WHERE user_id = ? AND address = ?", userID, address); err != nil {
578 return err
579 }
580 return tx.Commit()
581}
582
583func (s *Store) KeyEpoch() (int64, error) {
584 var v int64
585 err := s.DB.QueryRow("SELECT value FROM settings WHERE key = 'key_epoch'").Scan(&v)
586 return v, err
587}
588
589type execer interface {
590 Exec(query string, args ...any) (sql.Result, error)
591}
592
593func bumpKeyEpoch(tx execer) error {
594 _, err := tx.Exec("UPDATE settings SET value = value + 1 WHERE key = 'key_epoch'")
595 return err
596}
597
598func boolInt(b bool) int {
599 if b {
600 return 1
601 }
602 return 0
603}
604
605func isUniqueErr(err error) bool {
606 return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed")
607}
608
609func (s *Store) SSHKeyByID(id int64) (SSHKey, error) {
610 var k SSHKey
611 var exp sql.NullString
612 err := s.DB.QueryRow(
613 "SELECT id, user_id, fingerprint, algo, blob, scope, label, expires_at FROM ssh_keys WHERE id = ?",
614 id).Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label, &exp)
615 if errors.Is(err, sql.ErrNoRows) {
616 return k, ErrNotFound
617 }
618 k.ExpiresAt = parseTime(exp)
619 return k, err
620}
621
622// ListDeployKeys returns the deploy keys bound to a repository.
623func (s *Store) ListDeployKeys(repoID int64) ([]SSHKey, error) {
624 rows, err := s.DB.Query(
625 `SELECT id, user_id, fingerprint, algo, blob, scope, label, COALESCE(last_used_at, ''), expires_at
626 FROM ssh_keys WHERE scope LIKE 'deploy:' || ? || ':%' ORDER BY id`,
627 repoID)
628 if err != nil {
629 return nil, err
630 }
631 defer rows.Close()
632 var keys []SSHKey
633 for rows.Next() {
634 var k SSHKey
635 var exp sql.NullString
636 if err := rows.Scan(&k.ID, &k.UserID, &k.Fingerprint, &k.Algo, &k.Blob, &k.Scope, &k.Label, &k.LastUsedAt, &exp); err != nil {
637 return nil, err
638 }
639 k.ExpiresAt = parseTime(exp)
640 keys = append(keys, k)
641 }
642 return keys, rows.Err()
643}
644
645// RemoveDeployKey removes a deploy key from a repository by fingerprint;
646// any repo admin may remove it regardless of who added it.
647func (s *Store) RemoveDeployKey(repoID int64, fingerprint string) error {
648 return s.removeKey(
649 "DELETE FROM ssh_keys WHERE fingerprint = ? AND scope LIKE 'deploy:' || ? || ':%' RETURNING id",
650 fingerprint, repoID)
651}