internal/store/repos.go

060109696d0bb87d89790f986d682c447249f802
gitbay/internal/store/repos.go

422 lines · 13603 bytes

  1package store
  2
  3import (
  4	"context"
  5	"database/sql"
  6	"encoding/json"
  7	"errors"
  8	"fmt"
  9	"strings"
 10)
 11
 12type Repo struct {
 13	ID            int64
 14	OwnerKind     string // user | org
 15	OwnerID       int64
 16	OwnerName     string // resolved for display and disk paths
 17	Name          string
 18	Visibility    string // public | private
 19	DefaultBranch string
 20	ForkOf        int64 // 0 when not a fork
 21	Settings      RepoSettings
 22}
 23
 24type RepoSettings struct {
 25	ProtectedBranches    []string `json:"protected_branches,omitempty"`
 26	ProtectedTags        []string `json:"protected_tags,omitempty"` // path.Match globs
 27	RequireSignedCommits bool     `json:"require_signed_commits,omitempty"`
 28	RequireChecks        bool     `json:"require_checks,omitempty"`
 29	RequireApprovals     int      `json:"require_approvals,omitempty"`
 30	RequireResolved      bool     `json:"require_resolved,omitempty"`
 31	RequireCodeowners    bool     `json:"require_codeowners,omitempty"`
 32	RequireMR            bool     `json:"require_mr,omitempty"`
 33	GitDaemon            bool     `json:"git_daemon,omitempty"`
 34	Archived             bool     `json:"archived,omitempty"`
 35	Website              string   `json:"website,omitempty"`
 36}
 37
 38// Path returns the canonical owner/name form.
 39func (r Repo) Path() string { return r.OwnerName + "/" + r.Name }
 40
 41func (s *Store) CreateRepo(ownerKind string, ownerID int64, name, visibility string) (int64, error) {
 42	res, err := s.DB.Exec(
 43		"INSERT INTO repos (owner_kind, owner_id, name, visibility) VALUES (?, ?, ?, ?)",
 44		ownerKind, ownerID, name, visibility)
 45	if err != nil {
 46		if isUniqueErr(err) {
 47			return 0, fmt.Errorf("repository %q already exists", name)
 48		}
 49		return 0, err
 50	}
 51	return res.LastInsertId()
 52}
 53
 54// repoSelect resolves the owner name from whichever table owns the repo.
 55const repoSelect = `
 56	SELECT r.id, r.owner_kind, r.owner_id, COALESCE(u.username, o.name),
 57	       r.name, r.visibility, r.default_branch, COALESCE(r.fork_of, 0), r.settings_json
 58	FROM repos r
 59	LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
 60	LEFT JOIN orgs o  ON r.owner_kind = 'org'  AND o.id = r.owner_id`
 61
 62func scanRepo(row interface{ Scan(...any) error }) (Repo, error) {
 63	var r Repo
 64	var settingsJSON string
 65	err := row.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &r.OwnerName, &r.Name, &r.Visibility, &r.DefaultBranch, &r.ForkOf, &settingsJSON)
 66	if err != nil {
 67		return r, err
 68	}
 69	if err := json.Unmarshal([]byte(settingsJSON), &r.Settings); err != nil {
 70		return r, fmt.Errorf("repo %d settings: %w", r.ID, err)
 71	}
 72	return r, nil
 73}
 74
 75// RepoByPath resolves "owner/name"; the owner may be a user or an org.
 76func (s *Store) RepoByPath(path string) (Repo, error) {
 77	owner, name, ok := strings.Cut(strings.TrimSuffix(strings.TrimPrefix(path, "/"), ".git"), "/")
 78	if !ok || owner == "" || name == "" || strings.Contains(name, "/") {
 79		return Repo{}, fmt.Errorf("%w: repository path must be owner/name", ErrNotFound)
 80	}
 81	r, err := scanRepo(s.DB.QueryRow(
 82		repoSelect+" WHERE COALESCE(u.username, o.name) = ? AND r.name = ?", owner, name))
 83	if errors.Is(err, sql.ErrNoRows) {
 84		return Repo{}, ErrNotFound
 85	}
 86	return r, err
 87}
 88
 89// SetRepoVisibility switches a repository between public and private.
 90func (s *Store) SetRepoVisibility(repoID int64, visibility string) error {
 91	if visibility != "public" && visibility != "private" {
 92		return fmt.Errorf("visibility must be public or private")
 93	}
 94	_, err := s.DB.Exec("UPDATE repos SET visibility = ? WHERE id = ?", visibility, repoID)
 95	return err
 96}
 97
 98// UpdateRepoSettings applies mutate to the repository's settings and
 99// stores the result, returning what was stored.
100//
101// settings_json is one blob, so changing one field means writing all of
102// them. Callers used to read the struct off a Repo they had loaded
103// earlier, change a field and write the whole blob back, which loses the
104// other admin's change whenever two ran at once — last write wins over a
105// value it never read. The read and the write happen here instead, inside
106// one transaction, and BEGIN IMMEDIATE takes the write lock up front: a
107// second updater waits at the start rather than discovering the conflict
108// after it has already read a stale blob.
109func (s *Store) UpdateRepoSettings(repoID int64, mutate func(*RepoSettings)) (RepoSettings, error) {
110	ctx := context.Background()
111	var out RepoSettings
112	// The whole exchange must run on one connection for BEGIN to bracket
113	// it; the pool would otherwise be free to hand the statements out
114	// separately.
115	conn, err := s.DB.Conn(ctx)
116	if err != nil {
117		return out, err
118	}
119	defer conn.Close()
120	if _, err := conn.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil {
121		return out, err
122	}
123	committed := false
124	defer func() {
125		if !committed {
126			conn.ExecContext(ctx, "ROLLBACK")
127		}
128	}()
129	var raw string
130	if err := conn.QueryRowContext(ctx,
131		"SELECT settings_json FROM repos WHERE id = ?", repoID).Scan(&raw); err != nil {
132		if errors.Is(err, sql.ErrNoRows) {
133			return out, ErrNotFound
134		}
135		return out, err
136	}
137	if raw != "" {
138		if err := json.Unmarshal([]byte(raw), &out); err != nil {
139			return out, err
140		}
141	}
142	mutate(&out)
143	next, err := json.Marshal(out)
144	if err != nil {
145		return out, err
146	}
147	if _, err := conn.ExecContext(ctx,
148		"UPDATE repos SET settings_json = ? WHERE id = ?", string(next), repoID); err != nil {
149		return out, err
150	}
151	if _, err := conn.ExecContext(ctx, "COMMIT"); err != nil {
152		return out, err
153	}
154	committed = true
155	return out, nil
156}
157
158// CreateFork is CreateRepo with fork_of set in the same insert, so a fork
159// never exists for a moment as a plain repository (#108).
160func (s *Store) CreateFork(ownerKind string, ownerID int64, name, visibility string, forkOf int64) (int64, error) {
161	res, err := s.DB.Exec(
162		"INSERT INTO repos (owner_kind, owner_id, name, visibility, fork_of) VALUES (?, ?, ?, ?, ?)",
163		ownerKind, ownerID, name, visibility, forkOf)
164	if err != nil {
165		if isUniqueErr(err) {
166			return 0, fmt.Errorf("repository %q already exists", name)
167		}
168		return 0, err
169	}
170	return res.LastInsertId()
171}
172
173func (s *Store) SetForkOf(repoID, parentID int64) error {
174	_, err := s.DB.Exec("UPDATE repos SET fork_of = ? WHERE id = ?", parentID, repoID)
175	return err
176}
177
178func (s *Store) DeleteRepo(repoID int64) error {
179	res, err := s.DB.Exec("DELETE FROM repos WHERE id = ?", repoID)
180	if err != nil {
181		return err
182	}
183	if n, _ := res.RowsAffected(); n == 0 {
184		return ErrNotFound
185	}
186	return nil
187}
188
189// ListReposForUser returns repos the user owns, reaches through an org
190// (unless the org scopes members to 'none'), has an explicit grant on, or
191// reaches through a team. limit 0 means everything; after (an owner/name
192// path) starts the page strictly beyond it, matching the path-ascending
193// order.
194func (s *Store) ListReposForUser(userID int64, limit int, after string) ([]Repo, error) {
195	q := repoSelect + `
196		LEFT JOIN repo_access a ON a.repo_id = r.id AND a.subject_kind = 'user' AND a.subject_id = ?
197		LEFT JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.user_id = ?
198		LEFT JOIN orgs og ON r.owner_kind = 'org' AND og.id = r.owner_id
199		WHERE ((r.owner_kind = 'user' AND r.owner_id = ?)
200		   OR a.subject_id IS NOT NULL
201		   OR (m.user_id IS NOT NULL AND (m.role = 'admin' OR og.members_role <> 'none'))
202		   OR EXISTS (SELECT 1 FROM team_repos tr
203		              JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?
204		              WHERE tr.repo_id = r.id))`
205	args := []any{userID, userID, userID, userID}
206	if after != "" {
207		owner, name, _ := strings.Cut(after, "/")
208		q += ` AND (COALESCE(u.username, o.name) > ?
209		         OR (COALESCE(u.username, o.name) = ? AND r.name > ?))`
210		args = append(args, owner, owner, name)
211	}
212	q += `
213		GROUP BY r.id
214		ORDER BY 4, r.name`
215	if limit > 0 {
216		q += " LIMIT ?"
217		args = append(args, limit)
218	}
219	rows, err := s.DB.Query(q, args...)
220	if err != nil {
221		return nil, err
222	}
223	defer rows.Close()
224	var out []Repo
225	for rows.Next() {
226		r, err := scanRepo(rows)
227		if err != nil {
228			return nil, err
229		}
230		out = append(out, r)
231	}
232	return out, rows.Err()
233}
234
235// AccessRole returns the user's effective role on the repo ("" if none):
236// the strongest of any explicit grant, the role derived from org
237// membership (org admin -> admin; plain member -> the org's members_role,
238// 'write' by default so the pre-teams model is the degenerate case), and
239// any team grants on the repo.
240func (s *Store) AccessRole(repoID, userID int64) (string, error) {
241	rank := map[string]int{"": 0, "none": 0, "read": 1, "write": 2, "admin": 3}
242	best := ""
243	better := func(role string) {
244		if rank[role] > rank[best] {
245			best = role
246		}
247	}
248
249	var explicit string
250	err := s.DB.QueryRow(
251		"SELECT role FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
252		repoID, userID).Scan(&explicit)
253	if err != nil && !errors.Is(err, sql.ErrNoRows) {
254		return "", err
255	}
256	better(explicit)
257
258	var orgRole, membersRole string
259	err = s.DB.QueryRow(`
260		SELECT m.role, o.members_role FROM repos r
261		JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.user_id = ?
262		JOIN orgs o ON o.id = r.owner_id
263		WHERE r.id = ?`, userID, repoID).Scan(&orgRole, &membersRole)
264	if err != nil && !errors.Is(err, sql.ErrNoRows) {
265		return "", err
266	}
267	if orgRole == "admin" {
268		better("admin")
269	} else if orgRole == "member" {
270		better(membersRole) // write | read | none
271	}
272
273	var teamRole string
274	err = s.DB.QueryRow(`
275		SELECT tr.role FROM team_repos tr
276		JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?
277		WHERE tr.repo_id = ?
278		ORDER BY CASE tr.role WHEN 'admin' THEN 3 WHEN 'write' THEN 2 ELSE 1 END DESC
279		LIMIT 1`, userID, repoID).Scan(&teamRole)
280	if err != nil && !errors.Is(err, sql.ErrNoRows) {
281		return "", err
282	}
283	better(teamRole)
284	return best, nil
285}
286
287func (s *Store) GrantAccess(repoID, userID int64, role string) error {
288	_, err := s.DB.Exec(`
289		INSERT INTO repo_access (repo_id, subject_kind, subject_id, role) VALUES (?, 'user', ?, ?)
290		ON CONFLICT (repo_id, subject_kind, subject_id) DO UPDATE SET role = excluded.role`,
291		repoID, userID, role)
292	return err
293}
294
295func (s *Store) RevokeAccess(repoID, userID int64) error {
296	res, err := s.DB.Exec(
297		"DELETE FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
298		repoID, userID)
299	if err != nil {
300		return err
301	}
302	if n, _ := res.RowsAffected(); n == 0 {
303		return ErrNotFound
304	}
305	return nil
306}
307
308type AccessEntry struct {
309	Username string
310	Role     string
311}
312
313func (s *Store) ListAccess(repoID int64) ([]AccessEntry, error) {
314	rows, err := s.DB.Query(`
315		SELECT u.username, a.role FROM repo_access a
316		JOIN users u ON a.subject_kind = 'user' AND u.id = a.subject_id
317		WHERE a.repo_id = ? ORDER BY u.username`, repoID)
318	if err != nil {
319		return nil, err
320	}
321	defer rows.Close()
322	var out []AccessEntry
323	for rows.Next() {
324		var e AccessEntry
325		if err := rows.Scan(&e.Username, &e.Role); err != nil {
326			return nil, err
327		}
328		out = append(out, e)
329	}
330	return out, rows.Err()
331}
332
333func (s *Store) RepoByID(id int64) (Repo, error) {
334	r, err := scanRepo(s.DB.QueryRow(repoSelect+" WHERE r.id = ?", id))
335	if errors.Is(err, sql.ErrNoRows) {
336		return Repo{}, ErrNotFound
337	}
338	return r, err
339}
340
341// ListPublicRepos returns all public repositories, for the anonymous index.
342func (s *Store) ListPublicRepos() ([]Repo, error) {
343	rows, err := s.DB.Query(repoSelect + " WHERE r.visibility = 'public' ORDER BY 4, r.name")
344	if err != nil {
345		return nil, err
346	}
347	defer rows.Close()
348	var out []Repo
349	for rows.Next() {
350		r, err := scanRepo(rows)
351		if err != nil {
352			return nil, err
353		}
354		out = append(out, r)
355	}
356	return out, rows.Err()
357}
358
359// ListForks returns the repositories forked from one repo. The caller
360// filters by what the viewer may see.
361func (s *Store) ListForks(repoID int64) ([]Repo, error) {
362	rows, err := s.DB.Query(repoSelect+" WHERE r.fork_of = ? ORDER BY 4, r.name", repoID)
363	if err != nil {
364		return nil, err
365	}
366	defer rows.Close()
367	var out []Repo
368	for rows.Next() {
369		r, err := scanRepo(rows)
370		if err != nil {
371			return nil, err
372		}
373		out = append(out, r)
374	}
375	return out, rows.Err()
376}
377
378func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error {
379	_, err := s.DB.Exec("UPDATE repos SET default_branch = ? WHERE id = ?", branch, repoID)
380	return err
381}
382
383// ListReposForOwner returns every repo owned by one user or org; the caller
384// filters by viewer visibility.
385func (s *Store) ListReposForOwner(ownerKind string, ownerID int64) ([]Repo, error) {
386	rows, err := s.DB.Query(repoSelect+" WHERE r.owner_kind = ? AND r.owner_id = ? ORDER BY r.name",
387		ownerKind, ownerID)
388	if err != nil {
389		return nil, err
390	}
391	defer rows.Close()
392	var out []Repo
393	for rows.Next() {
394		r, err := scanRepo(rows)
395		if err != nil {
396			return nil, err
397		}
398		out = append(out, r)
399	}
400	return out, rows.Err()
401}
402
403// RenameRepo changes a repository's name under the same owner. The unique
404// index on (owner_kind, owner_id, name) refuses collisions.
405func (s *Store) RenameRepo(repoID int64, newName string) error {
406	_, err := s.DB.Exec("UPDATE repos SET name = ? WHERE id = ?", newName, repoID)
407	if isUniqueErr(err) {
408		return fmt.Errorf("the owner already has a repository by that name")
409	}
410	return err
411}
412
413// TransferRepo moves a repository to a new owner. The unique index on
414// (owner_kind, owner_id, name) refuses collisions in the target namespace.
415func (s *Store) TransferRepo(repoID int64, newKind string, newOwnerID int64) error {
416	_, err := s.DB.Exec("UPDATE repos SET owner_kind = ?, owner_id = ? WHERE id = ?",
417		newKind, newOwnerID, repoID)
418	if isUniqueErr(err) {
419		return fmt.Errorf("the target owner already has a repository by that name")
420	}
421	return err
422}