internal/store/repos.go

8e64f8208b18dc40fb5c27c873802282e722255e
gitbay/internal/store/repos.go history · blame · raw

308 lines · 9770 bytes

  1package store
  2
  3import (
  4	"database/sql"
  5	"encoding/json"
  6	"errors"
  7	"fmt"
  8	"strings"
  9)
 10
 11type Repo struct {
 12	ID            int64
 13	OwnerKind     string // user | org
 14	OwnerID       int64
 15	OwnerName     string // resolved for display and disk paths
 16	Name          string
 17	Visibility    string // public | private
 18	DefaultBranch string
 19	ForkOf        int64 // 0 when not a fork
 20	Settings      RepoSettings
 21}
 22
 23type RepoSettings struct {
 24	ProtectedBranches    []string `json:"protected_branches,omitempty"`
 25	RequireSignedCommits bool     `json:"require_signed_commits,omitempty"`
 26	RequireChecks        bool     `json:"require_checks,omitempty"`
 27	RequireApprovals     int      `json:"require_approvals,omitempty"`
 28	RequireResolved      bool     `json:"require_resolved,omitempty"`
 29	GitDaemon            bool     `json:"git_daemon,omitempty"`
 30	Archived             bool     `json:"archived,omitempty"`
 31	Website              string   `json:"website,omitempty"`
 32}
 33
 34// Path returns the canonical owner/name form.
 35func (r Repo) Path() string { return r.OwnerName + "/" + r.Name }
 36
 37func (s *Store) CreateRepo(ownerKind string, ownerID int64, name, visibility string) (int64, error) {
 38	res, err := s.DB.Exec(
 39		"INSERT INTO repos (owner_kind, owner_id, name, visibility) VALUES (?, ?, ?, ?)",
 40		ownerKind, ownerID, name, visibility)
 41	if err != nil {
 42		if isUniqueErr(err) {
 43			return 0, fmt.Errorf("repository %q already exists", name)
 44		}
 45		return 0, err
 46	}
 47	return res.LastInsertId()
 48}
 49
 50// repoSelect resolves the owner name from whichever table owns the repo.
 51const repoSelect = `
 52	SELECT r.id, r.owner_kind, r.owner_id, COALESCE(u.username, o.name),
 53	       r.name, r.visibility, r.default_branch, COALESCE(r.fork_of, 0), r.settings_json
 54	FROM repos r
 55	LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
 56	LEFT JOIN orgs o  ON r.owner_kind = 'org'  AND o.id = r.owner_id`
 57
 58func scanRepo(row interface{ Scan(...any) error }) (Repo, error) {
 59	var r Repo
 60	var settingsJSON string
 61	err := row.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &r.OwnerName, &r.Name, &r.Visibility, &r.DefaultBranch, &r.ForkOf, &settingsJSON)
 62	if err != nil {
 63		return r, err
 64	}
 65	if err := json.Unmarshal([]byte(settingsJSON), &r.Settings); err != nil {
 66		return r, fmt.Errorf("repo %d settings: %w", r.ID, err)
 67	}
 68	return r, nil
 69}
 70
 71// RepoByPath resolves "owner/name"; the owner may be a user or an org.
 72func (s *Store) RepoByPath(path string) (Repo, error) {
 73	owner, name, ok := strings.Cut(strings.TrimSuffix(strings.TrimPrefix(path, "/"), ".git"), "/")
 74	if !ok || owner == "" || name == "" || strings.Contains(name, "/") {
 75		return Repo{}, fmt.Errorf("%w: repository path must be owner/name", ErrNotFound)
 76	}
 77	r, err := scanRepo(s.DB.QueryRow(
 78		repoSelect+" WHERE COALESCE(u.username, o.name) = ? AND r.name = ?", owner, name))
 79	if errors.Is(err, sql.ErrNoRows) {
 80		return Repo{}, ErrNotFound
 81	}
 82	return r, err
 83}
 84
 85// SetRepoVisibility switches a repository between public and private.
 86func (s *Store) SetRepoVisibility(repoID int64, visibility string) error {
 87	if visibility != "public" && visibility != "private" {
 88		return fmt.Errorf("visibility must be public or private")
 89	}
 90	_, err := s.DB.Exec("UPDATE repos SET visibility = ? WHERE id = ?", visibility, repoID)
 91	return err
 92}
 93
 94func (s *Store) SetRepoSettings(repoID int64, settings RepoSettings) error {
 95	raw, err := json.Marshal(settings)
 96	if err != nil {
 97		return err
 98	}
 99	_, err = s.DB.Exec("UPDATE repos SET settings_json = ? WHERE id = ?", string(raw), repoID)
100	return err
101}
102
103func (s *Store) SetForkOf(repoID, parentID int64) error {
104	_, err := s.DB.Exec("UPDATE repos SET fork_of = ? WHERE id = ?", parentID, repoID)
105	return err
106}
107
108func (s *Store) DeleteRepo(repoID int64) error {
109	res, err := s.DB.Exec("DELETE FROM repos WHERE id = ?", repoID)
110	if err != nil {
111		return err
112	}
113	if n, _ := res.RowsAffected(); n == 0 {
114		return ErrNotFound
115	}
116	return nil
117}
118
119// ListReposForUser returns repos the user owns, reaches through an org
120// (unless the org scopes members to 'none'), has an explicit grant on, or
121// reaches through a team.
122func (s *Store) ListReposForUser(userID int64) ([]Repo, error) {
123	rows, err := s.DB.Query(repoSelect+`
124		LEFT JOIN repo_access a ON a.repo_id = r.id AND a.subject_kind = 'user' AND a.subject_id = ?
125		LEFT JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.user_id = ?
126		LEFT JOIN orgs og ON r.owner_kind = 'org' AND og.id = r.owner_id
127		WHERE (r.owner_kind = 'user' AND r.owner_id = ?)
128		   OR a.subject_id IS NOT NULL
129		   OR (m.user_id IS NOT NULL AND (m.role = 'admin' OR og.members_role <> 'none'))
130		   OR EXISTS (SELECT 1 FROM team_repos tr
131		              JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?
132		              WHERE tr.repo_id = r.id)
133		GROUP BY r.id
134		ORDER BY 4, r.name`, userID, userID, userID, userID)
135	if err != nil {
136		return nil, err
137	}
138	defer rows.Close()
139	var out []Repo
140	for rows.Next() {
141		r, err := scanRepo(rows)
142		if err != nil {
143			return nil, err
144		}
145		out = append(out, r)
146	}
147	return out, rows.Err()
148}
149
150// AccessRole returns the user's effective role on the repo ("" if none):
151// the strongest of any explicit grant, the role derived from org
152// membership (org admin -> admin; plain member -> the org's members_role,
153// 'write' by default so the pre-teams model is the degenerate case), and
154// any team grants on the repo.
155func (s *Store) AccessRole(repoID, userID int64) (string, error) {
156	rank := map[string]int{"": 0, "none": 0, "read": 1, "write": 2, "admin": 3}
157	best := ""
158	better := func(role string) {
159		if rank[role] > rank[best] {
160			best = role
161		}
162	}
163
164	var explicit string
165	err := s.DB.QueryRow(
166		"SELECT role FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
167		repoID, userID).Scan(&explicit)
168	if err != nil && !errors.Is(err, sql.ErrNoRows) {
169		return "", err
170	}
171	better(explicit)
172
173	var orgRole, membersRole string
174	err = s.DB.QueryRow(`
175		SELECT m.role, o.members_role FROM repos r
176		JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.user_id = ?
177		JOIN orgs o ON o.id = r.owner_id
178		WHERE r.id = ?`, userID, repoID).Scan(&orgRole, &membersRole)
179	if err != nil && !errors.Is(err, sql.ErrNoRows) {
180		return "", err
181	}
182	if orgRole == "admin" {
183		better("admin")
184	} else if orgRole == "member" {
185		better(membersRole) // write | read | none
186	}
187
188	var teamRole string
189	err = s.DB.QueryRow(`
190		SELECT tr.role FROM team_repos tr
191		JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?
192		WHERE tr.repo_id = ?
193		ORDER BY CASE tr.role WHEN 'admin' THEN 3 WHEN 'write' THEN 2 ELSE 1 END DESC
194		LIMIT 1`, userID, repoID).Scan(&teamRole)
195	if err != nil && !errors.Is(err, sql.ErrNoRows) {
196		return "", err
197	}
198	better(teamRole)
199	return best, nil
200}
201
202func (s *Store) GrantAccess(repoID, userID int64, role string) error {
203	_, err := s.DB.Exec(`
204		INSERT INTO repo_access (repo_id, subject_kind, subject_id, role) VALUES (?, 'user', ?, ?)
205		ON CONFLICT (repo_id, subject_kind, subject_id) DO UPDATE SET role = excluded.role`,
206		repoID, userID, role)
207	return err
208}
209
210func (s *Store) RevokeAccess(repoID, userID int64) error {
211	res, err := s.DB.Exec(
212		"DELETE FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
213		repoID, userID)
214	if err != nil {
215		return err
216	}
217	if n, _ := res.RowsAffected(); n == 0 {
218		return ErrNotFound
219	}
220	return nil
221}
222
223type AccessEntry struct {
224	Username string
225	Role     string
226}
227
228func (s *Store) ListAccess(repoID int64) ([]AccessEntry, error) {
229	rows, err := s.DB.Query(`
230		SELECT u.username, a.role FROM repo_access a
231		JOIN users u ON a.subject_kind = 'user' AND u.id = a.subject_id
232		WHERE a.repo_id = ? ORDER BY u.username`, repoID)
233	if err != nil {
234		return nil, err
235	}
236	defer rows.Close()
237	var out []AccessEntry
238	for rows.Next() {
239		var e AccessEntry
240		if err := rows.Scan(&e.Username, &e.Role); err != nil {
241			return nil, err
242		}
243		out = append(out, e)
244	}
245	return out, rows.Err()
246}
247
248func (s *Store) RepoByID(id int64) (Repo, error) {
249	r, err := scanRepo(s.DB.QueryRow(repoSelect+" WHERE r.id = ?", id))
250	if errors.Is(err, sql.ErrNoRows) {
251		return Repo{}, ErrNotFound
252	}
253	return r, err
254}
255
256// ListPublicRepos returns all public repositories, for the anonymous index.
257func (s *Store) ListPublicRepos() ([]Repo, error) {
258	rows, err := s.DB.Query(repoSelect + " WHERE r.visibility = 'public' ORDER BY 4, r.name")
259	if err != nil {
260		return nil, err
261	}
262	defer rows.Close()
263	var out []Repo
264	for rows.Next() {
265		r, err := scanRepo(rows)
266		if err != nil {
267			return nil, err
268		}
269		out = append(out, r)
270	}
271	return out, rows.Err()
272}
273
274func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error {
275	_, err := s.DB.Exec("UPDATE repos SET default_branch = ? WHERE id = ?", branch, repoID)
276	return err
277}
278
279// ListReposForOwner returns every repo owned by one user or org; the caller
280// filters by viewer visibility.
281func (s *Store) ListReposForOwner(ownerKind string, ownerID int64) ([]Repo, error) {
282	rows, err := s.DB.Query(repoSelect+" WHERE r.owner_kind = ? AND r.owner_id = ? ORDER BY r.name",
283		ownerKind, ownerID)
284	if err != nil {
285		return nil, err
286	}
287	defer rows.Close()
288	var out []Repo
289	for rows.Next() {
290		r, err := scanRepo(rows)
291		if err != nil {
292			return nil, err
293		}
294		out = append(out, r)
295	}
296	return out, rows.Err()
297}
298
299// TransferRepo moves a repository to a new owner. The unique index on
300// (owner_kind, owner_id, name) refuses collisions in the target namespace.
301func (s *Store) TransferRepo(repoID int64, newKind string, newOwnerID int64) error {
302	_, err := s.DB.Exec("UPDATE repos SET owner_kind = ?, owner_id = ? WHERE id = ?",
303		newKind, newOwnerID, repoID)
304	if isUniqueErr(err) {
305		return fmt.Errorf("the target owner already has a repository by that name")
306	}
307	return err
308}