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