internal/store/repos.go
566 lines · 19228 bytes
1package store
2
3import (
4 "context"
5 "database/sql"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "sort"
10 "strings"
11)
12
13type Repo struct {
14 ID int64
15 OwnerKind string // user | org
16 OwnerID int64
17 OwnerName string // resolved for display and disk paths
18 Name string
19 Visibility string // public | private
20 DefaultBranch string
21 ForkOf int64 // 0 when not a fork
22 Settings RepoSettings
23}
24
25type RepoSettings struct {
26 ProtectedBranches []string `json:"protected_branches,omitempty"`
27 ProtectedTags []string `json:"protected_tags,omitempty"` // path.Match globs
28 RequireSignedCommits bool `json:"require_signed_commits,omitempty"`
29 RequireChecks bool `json:"require_checks,omitempty"`
30 // RequiredContexts are statuses require_checks waits for whether or
31 // not they have reported; one that has not is pending. Setting a
32 // non-empty list turns RequireChecks on (#258).
33 RequiredContexts []string `json:"required_contexts,omitempty"`
34 RequireApprovals int `json:"require_approvals,omitempty"`
35 RequireResolved bool `json:"require_resolved,omitempty"`
36 RequireCodeowners bool `json:"require_codeowners,omitempty"`
37 RequireMR bool `json:"require_mr,omitempty"`
38 GitDaemon bool `json:"git_daemon,omitempty"`
39 Archived bool `json:"archived,omitempty"`
40 Website string `json:"website,omitempty"`
41 // SecretScan is off, warn or block; empty is warn (leaks.Mode).
42 SecretScan string `json:"secret_scan,omitempty"`
43 // SecretScanAllow are CI path globs whose findings are ignored.
44 SecretScanAllow []string `json:"secret_scan_allow,omitempty"`
45}
46
47// Path returns the canonical owner/name form.
48func (r Repo) Path() string { return r.OwnerName + "/" + r.Name }
49
50func (s *Store) CreateRepo(ownerKind string, ownerID int64, name, visibility string) (int64, error) {
51 res, err := s.DB.Exec(
52 "INSERT INTO repos (owner_kind, owner_id, name, visibility) VALUES (?, ?, ?, ?)",
53 ownerKind, ownerID, name, visibility)
54 if err != nil {
55 if isUniqueErr(err) {
56 return 0, fmt.Errorf("repository %q already exists", name)
57 }
58 return 0, err
59 }
60 return res.LastInsertId()
61}
62
63// repoSelect resolves the owner name from whichever table owns the repo.
64const repoSelect = `
65 SELECT r.id, r.owner_kind, r.owner_id, COALESCE(u.username, o.name),
66 r.name, r.visibility, r.default_branch, COALESCE(r.fork_of, 0), r.settings_json
67 FROM repos r
68 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
69 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id`
70
71func scanRepo(row interface{ Scan(...any) error }) (Repo, error) {
72 var r Repo
73 var settingsJSON string
74 err := row.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &r.OwnerName, &r.Name, &r.Visibility, &r.DefaultBranch, &r.ForkOf, &settingsJSON)
75 if err != nil {
76 return r, err
77 }
78 if err := json.Unmarshal([]byte(settingsJSON), &r.Settings); err != nil {
79 return r, fmt.Errorf("repo %d settings: %w", r.ID, err)
80 }
81 return r, nil
82}
83
84// RepoByPath resolves "owner/name"; the owner may be a user or an org.
85func (s *Store) RepoByPath(path string) (Repo, error) {
86 owner, name, ok := strings.Cut(strings.TrimSuffix(strings.TrimPrefix(path, "/"), ".git"), "/")
87 if !ok || owner == "" || name == "" || strings.Contains(name, "/") {
88 return Repo{}, fmt.Errorf("%w: repository path must be owner/name", ErrNotFound)
89 }
90 r, err := scanRepo(s.DB.QueryRow(
91 repoSelect+" WHERE COALESCE(u.username, o.name) = ? AND r.name = ?", owner, name))
92 if errors.Is(err, sql.ErrNoRows) {
93 return Repo{}, ErrNotFound
94 }
95 return r, err
96}
97
98// SetRepoVisibility switches a repository between public and private.
99func (s *Store) SetRepoVisibility(repoID int64, visibility string) error {
100 if visibility != "public" && visibility != "private" {
101 return fmt.Errorf("visibility must be public or private")
102 }
103 _, err := s.DB.Exec("UPDATE repos SET visibility = ? WHERE id = ?", visibility, repoID)
104 return err
105}
106
107// UpdateRepoSettings applies mutate to the repository's settings and
108// stores the result, returning what was stored.
109//
110// settings_json is one blob, so changing one field means writing all of
111// them. Callers used to read the struct off a Repo they had loaded
112// earlier, change a field and write the whole blob back, which loses the
113// other admin's change whenever two ran at once — last write wins over a
114// value it never read. The read and the write happen here instead, inside
115// one transaction, and BEGIN IMMEDIATE takes the write lock up front: a
116// second updater waits at the start rather than discovering the conflict
117// after it has already read a stale blob.
118func (s *Store) UpdateRepoSettings(repoID int64, mutate func(*RepoSettings)) (RepoSettings, error) {
119 ctx := context.Background()
120 var out RepoSettings
121 // The whole exchange must run on one connection for BEGIN to bracket
122 // it; the pool would otherwise be free to hand the statements out
123 // separately.
124 conn, err := s.DB.Conn(ctx)
125 if err != nil {
126 return out, err
127 }
128 defer conn.Close()
129 if _, err := conn.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil {
130 return out, err
131 }
132 committed := false
133 defer func() {
134 if !committed {
135 conn.ExecContext(ctx, "ROLLBACK")
136 }
137 }()
138 var raw string
139 if err := conn.QueryRowContext(ctx,
140 "SELECT settings_json FROM repos WHERE id = ?", repoID).Scan(&raw); err != nil {
141 if errors.Is(err, sql.ErrNoRows) {
142 return out, ErrNotFound
143 }
144 return out, err
145 }
146 if raw != "" {
147 if err := json.Unmarshal([]byte(raw), &out); err != nil {
148 return out, err
149 }
150 }
151 mutate(&out)
152 next, err := json.Marshal(out)
153 if err != nil {
154 return out, err
155 }
156 if _, err := conn.ExecContext(ctx,
157 "UPDATE repos SET settings_json = ? WHERE id = ?", string(next), repoID); err != nil {
158 return out, err
159 }
160 if _, err := conn.ExecContext(ctx, "COMMIT"); err != nil {
161 return out, err
162 }
163 committed = true
164 return out, nil
165}
166
167// CreateFork is CreateRepo with fork_of set in the same insert, so a fork
168// never exists for a moment as a plain repository (#108).
169func (s *Store) CreateFork(ownerKind string, ownerID int64, name, visibility string, forkOf int64) (int64, error) {
170 res, err := s.DB.Exec(
171 "INSERT INTO repos (owner_kind, owner_id, name, visibility, fork_of) VALUES (?, ?, ?, ?, ?)",
172 ownerKind, ownerID, name, visibility, forkOf)
173 if err != nil {
174 if isUniqueErr(err) {
175 return 0, fmt.Errorf("repository %q already exists", name)
176 }
177 return 0, err
178 }
179 return res.LastInsertId()
180}
181
182func (s *Store) SetForkOf(repoID, parentID int64) error {
183 _, err := s.DB.Exec("UPDATE repos SET fork_of = ? WHERE id = ?", parentID, repoID)
184 return err
185}
186
187// DeleteRepo removes the repository row, what cascades from it, and
188// the deploy keys scoped to it, which name it by id in their scope
189// rather than by a foreign key (#306).
190func (s *Store) DeleteRepo(repoID int64) error {
191 tx, err := s.DB.Begin()
192 if err != nil {
193 return err
194 }
195 defer tx.Rollback()
196 rows, err := tx.Query("DELETE FROM ssh_keys WHERE scope LIKE 'deploy:' || ? || ':%' RETURNING id", repoID)
197 if err != nil {
198 return err
199 }
200 var keyIDs []int64
201 for rows.Next() {
202 var id int64
203 if err := rows.Scan(&id); err != nil {
204 rows.Close()
205 return err
206 }
207 keyIDs = append(keyIDs, id)
208 }
209 rows.Close()
210 if err := rows.Err(); err != nil {
211 return err
212 }
213 res, err := tx.Exec("DELETE FROM repos WHERE id = ?", repoID)
214 if err != nil {
215 return err
216 }
217 if n, _ := res.RowsAffected(); n == 0 {
218 return ErrNotFound
219 }
220 if len(keyIDs) > 0 {
221 if err := bumpKeyEpoch(tx); err != nil {
222 return err
223 }
224 }
225 if err := tx.Commit(); err != nil {
226 return err
227 }
228 if len(keyIDs) > 0 {
229 s.announce(Revoked{KeyIDs: keyIDs})
230 }
231 return nil
232}
233
234// ListReposForUser returns repos the user owns, reaches through an org
235// (unless the org scopes members to 'none'), has an explicit grant on, or
236// reaches through a team. limit 0 means everything; after (an owner/name
237// path) starts the page strictly beyond it, matching the path-ascending
238// order.
239func (s *Store) ListReposForUser(userID int64, limit int, after string) ([]Repo, error) {
240 q := repoSelect + `
241 LEFT JOIN repo_access a ON a.repo_id = r.id AND a.subject_kind = 'user' AND a.subject_id = ?
242 LEFT JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.user_id = ?
243 LEFT JOIN orgs og ON r.owner_kind = 'org' AND og.id = r.owner_id
244 WHERE ((r.owner_kind = 'user' AND r.owner_id = ?)
245 OR a.subject_id IS NOT NULL
246 OR (m.user_id IS NOT NULL AND (m.role = 'admin' OR og.members_role <> 'none'))
247 OR EXISTS (SELECT 1 FROM team_repos tr
248 JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?
249 WHERE tr.repo_id = r.id))`
250 args := []any{userID, userID, userID, userID}
251 if after != "" {
252 owner, name, _ := strings.Cut(after, "/")
253 q += ` AND (COALESCE(u.username, o.name) > ?
254 OR (COALESCE(u.username, o.name) = ? AND r.name > ?))`
255 args = append(args, owner, owner, name)
256 }
257 q += `
258 GROUP BY r.id
259 ORDER BY 4, r.name`
260 if limit > 0 {
261 q += " LIMIT ?"
262 args = append(args, limit)
263 }
264 return queryAll(s.DB, scanRepo, q, args...)
265}
266
267// AccessRole returns the user's effective role on the repo ("" if none):
268// the strongest of any explicit grant, the role derived from org
269// membership (org admin -> admin; plain member -> the org's members_role,
270// 'write' by default so the pre-teams model is the degenerate case), and
271// any team grants on the repo.
272func (s *Store) AccessRole(repoID, userID int64) (string, error) {
273 rank := map[string]int{"": 0, "none": 0, "read": 1, "write": 2, "admin": 3}
274 best := ""
275 better := func(role string) {
276 if rank[role] > rank[best] {
277 best = role
278 }
279 }
280
281 var explicit string
282 err := s.DB.QueryRow(
283 "SELECT role FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
284 repoID, userID).Scan(&explicit)
285 if err != nil && !errors.Is(err, sql.ErrNoRows) {
286 return "", err
287 }
288 better(explicit)
289
290 var orgRole, membersRole string
291 err = s.DB.QueryRow(`
292 SELECT m.role, o.members_role FROM repos r
293 JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.user_id = ?
294 JOIN orgs o ON o.id = r.owner_id
295 WHERE r.id = ?`, userID, repoID).Scan(&orgRole, &membersRole)
296 if err != nil && !errors.Is(err, sql.ErrNoRows) {
297 return "", err
298 }
299 if orgRole == "admin" {
300 better("admin")
301 } else if orgRole == "member" {
302 better(membersRole) // write | read | none
303 }
304
305 var teamRole string
306 err = s.DB.QueryRow(`
307 SELECT tr.role FROM team_repos tr
308 JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?
309 WHERE tr.repo_id = ?
310 ORDER BY CASE tr.role WHEN 'admin' THEN 3 WHEN 'write' THEN 2 ELSE 1 END DESC
311 LIMIT 1`, userID, repoID).Scan(&teamRole)
312 if err != nil && !errors.Is(err, sql.ErrNoRows) {
313 return "", err
314 }
315 better(teamRole)
316 return best, nil
317}
318
319func (s *Store) GrantAccess(repoID, userID int64, role string) error {
320 _, err := s.DB.Exec(`
321 INSERT INTO repo_access (repo_id, subject_kind, subject_id, role) VALUES (?, 'user', ?, ?)
322 ON CONFLICT (repo_id, subject_kind, subject_id) DO UPDATE SET role = excluded.role`,
323 repoID, userID, role)
324 return err
325}
326
327func (s *Store) RevokeAccess(repoID, userID int64) error {
328 res, err := s.DB.Exec(
329 "DELETE FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
330 repoID, userID)
331 if err != nil {
332 return err
333 }
334 if n, _ := res.RowsAffected(); n == 0 {
335 return ErrNotFound
336 }
337 return nil
338}
339
340// EffectiveEntry is one account's effective role on a repository and the
341// grant it comes from: owner, direct, org admin, org member, or team
342// <name>.
343type EffectiveEntry struct {
344 Username string
345 Role string
346 Source string
347}
348
349// EffectiveAccess lists every account that can reach a repository with
350// the highest role it holds and where that role comes from. Direct
351// grants, org roles and team grants are folded together the way
352// AccessRole folds them for one account.
353func (s *Store) EffectiveAccess(repoID int64) ([]EffectiveEntry, error) {
354 rank := map[string]int{"read": 1, "write": 2, "admin": 3}
355 best := map[string]EffectiveEntry{}
356 var order []string
357 add := func(user, role, source string) {
358 if rank[role] == 0 {
359 return
360 }
361 cur, ok := best[user]
362 if !ok {
363 order = append(order, user)
364 }
365 if !ok || rank[role] > rank[cur.Role] {
366 best[user] = EffectiveEntry{user, role, source}
367 }
368 }
369 collect := func(query string, source func(extra string) string, args ...any) error {
370 rows, err := s.DB.Query(query, args...)
371 if err != nil {
372 return err
373 }
374 defer rows.Close()
375 for rows.Next() {
376 var user, role, extra string
377 if err := rows.Scan(&user, &role, &extra); err != nil {
378 return err
379 }
380 add(user, role, source(extra))
381 }
382 return rows.Err()
383 }
384 fixed := func(name string) func(string) string { return func(string) string { return name } }
385
386 // The owner: a user outright, or the org's admins and members.
387 if err := collect(`
388 SELECT u.username, 'admin', '' FROM repos r JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
389 WHERE r.id = ?`, fixed("owner"), repoID); err != nil {
390 return nil, err
391 }
392 if err := collect(`
393 SELECT u.username, 'admin', '' FROM repos r
394 JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.role = 'admin'
395 JOIN users u ON u.id = m.user_id WHERE r.id = ?`, fixed("org admin"), repoID); err != nil {
396 return nil, err
397 }
398 if err := collect(`
399 SELECT u.username, a.role, '' FROM repo_access a
400 JOIN users u ON a.subject_kind = 'user' AND u.id = a.subject_id WHERE a.repo_id = ?`,
401 fixed("direct"), repoID); err != nil {
402 return nil, err
403 }
404 if err := collect(`
405 SELECT u.username, tr.role, t.name FROM team_repos tr
406 JOIN teams t ON t.id = tr.team_id
407 JOIN team_members tm ON tm.team_id = tr.team_id
408 JOIN users u ON u.id = tm.user_id WHERE tr.repo_id = ?
409 ORDER BY CASE tr.role WHEN 'admin' THEN 3 WHEN 'write' THEN 2 ELSE 1 END DESC, t.name`,
410 func(team string) string { return "team " + team }, repoID); err != nil {
411 return nil, err
412 }
413 if err := collect(`
414 SELECT u.username, o.members_role, '' FROM repos r
415 JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
416 JOIN org_members m ON m.org_id = o.id AND m.role = 'member'
417 JOIN users u ON u.id = m.user_id WHERE r.id = ?`, fixed("org member"), repoID); err != nil {
418 return nil, err
419 }
420 sort.Strings(order)
421 out := make([]EffectiveEntry, 0, len(order))
422 for _, u := range order {
423 out = append(out, best[u])
424 }
425 return out, nil
426}
427
428func (s *Store) RepoByID(id int64) (Repo, error) {
429 r, err := scanRepo(s.DB.QueryRow(repoSelect+" WHERE r.id = ?", id))
430 if errors.Is(err, sql.ErrNoRows) {
431 return Repo{}, ErrNotFound
432 }
433 return r, err
434}
435
436// ListPublicRepos returns all public repositories, for the anonymous index.
437func (s *Store) ListPublicRepos() ([]Repo, error) {
438 return queryAll(s.DB, scanRepo, repoSelect+" WHERE r.visibility = 'public' ORDER BY 4, r.name")
439}
440
441// ListPublicReposByActivity returns all public repositories, the most
442// recent event first. Builds are not activity: a nightly job would keep
443// its repository on top. A repository with no events sorts last, newest
444// first.
445func (s *Store) ListPublicReposByActivity() ([]Repo, error) {
446 rows, err := s.DB.Query(repoSelect + ` WHERE r.visibility = 'public'
447 ORDER BY COALESCE((SELECT MAX(e.id) FROM events e
448 WHERE e.repo_id = r.id AND e.kind NOT LIKE 'build.%'), 0) DESC, r.id DESC`)
449 if err != nil {
450 return nil, err
451 }
452 defer rows.Close()
453 var out []Repo
454 for rows.Next() {
455 r, err := scanRepo(rows)
456 if err != nil {
457 return nil, err
458 }
459 out = append(out, r)
460 }
461 return out, rows.Err()
462}
463
464// ListForks returns the repositories forked from one repo. The caller
465// filters by what the viewer may see.
466func (s *Store) ListForks(repoID int64) ([]Repo, error) {
467 return queryAll(s.DB, scanRepo, repoSelect+" WHERE r.fork_of = ? ORDER BY 4, r.name", repoID)
468}
469
470func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error {
471 _, err := s.DB.Exec("UPDATE repos SET default_branch = ? WHERE id = ?", branch, repoID)
472 return err
473}
474
475// ListReposForOwner returns every repo owned by one user or org; the caller
476// filters by viewer visibility.
477func (s *Store) ListReposForOwner(ownerKind string, ownerID int64) ([]Repo, error) {
478 return queryAll(s.DB, scanRepo, repoSelect+" WHERE r.owner_kind = ? AND r.owner_id = ? ORDER BY r.name",
479 ownerKind, ownerID)
480}
481
482// RenameRepo changes a repository's name under the same owner. The unique
483// index on (owner_kind, owner_id, name) refuses collisions.
484func (s *Store) RenameRepo(repoID int64, newName string) error {
485 _, err := s.DB.Exec("UPDATE repos SET name = ? WHERE id = ?", newName, repoID)
486 if isUniqueErr(err) {
487 return fmt.Errorf("the owner already has a repository by that name")
488 }
489 return err
490}
491
492// TransferRepo moves a repository to a new owner. The unique index on
493// (owner_kind, owner_id, name) refuses collisions in the target namespace.
494// Moving into an org folds the repository's labels and milestones whose
495// names the org already holds into the org's rows, in the same
496// transaction, so the repository does not come out seeing two of each.
497// Moving out of an org needs no counterpart: the repository keeps what it
498// owns and stops seeing the org's rows.
499func (s *Store) TransferRepo(repoID int64, newKind string, newOwnerID int64) error {
500 tx, err := s.DB.Begin()
501 if err != nil {
502 return err
503 }
504 defer tx.Rollback()
505 if _, err := tx.Exec("UPDATE repos SET owner_kind = ?, owner_id = ? WHERE id = ?",
506 newKind, newOwnerID, repoID); err != nil {
507 if isUniqueErr(err) {
508 return fmt.Errorf("the target owner already has a repository by that name")
509 }
510 return err
511 }
512 if newKind == "org" {
513 if err := foldIntoOrg(tx, repoID, newOwnerID); err != nil {
514 return err
515 }
516 }
517 return tx.Commit()
518}
519
520// foldIntoOrg folds a repository's labels and milestones into the org's
521// rows of the same name, the way org label set and org milestone create
522// fold the repositories already under the org.
523func foldIntoOrg(tx *sql.Tx, repoID, orgID int64) error {
524 labels, err := sharedNameRows(tx, "labels", "name", repoID, orgID)
525 if err != nil {
526 return err
527 }
528 for _, p := range labels {
529 if err := foldLabelRow(tx, p.org, p.repo); err != nil {
530 return err
531 }
532 }
533 milestones, err := sharedNameRows(tx, "milestones", "title", repoID, orgID)
534 if err != nil {
535 return err
536 }
537 for _, p := range milestones {
538 if err := foldMilestoneRow(tx, p.org, p.repo); err != nil {
539 return err
540 }
541 }
542 return nil
543}
544
545// rowPair is one repository row and the org row it folds into.
546type rowPair struct{ repo, org int64 }
547
548// sharedNameRows pairs a repository's label or milestone rows with the
549// org's rows carrying the same name.
550func sharedNameRows(tx *sql.Tx, table, nameCol string, repoID, orgID int64) ([]rowPair, error) {
551 rows, err := tx.Query("SELECT t.id, o.id FROM "+table+" t JOIN "+table+" o"+
552 " ON o.org_id = ? AND o."+nameCol+" = t."+nameCol+" WHERE t.repo_id = ?", orgID, repoID)
553 if err != nil {
554 return nil, err
555 }
556 defer rows.Close()
557 var out []rowPair
558 for rows.Next() {
559 var p rowPair
560 if err := rows.Scan(&p.repo, &p.org); err != nil {
561 return nil, err
562 }
563 out = append(out, p)
564 }
565 return out, rows.Err()
566}