internal/store/repos.go

0d12684707ba92a7a5dcf9aee6077df1f8c17c9c
gitbay/internal/store/repos.go history · blame · raw

299 lines · 9401 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
 85func (s *Store) SetRepoSettings(repoID int64, settings RepoSettings) error {
 86	raw, err := json.Marshal(settings)
 87	if err != nil {
 88		return err
 89	}
 90	_, err = s.DB.Exec("UPDATE repos SET settings_json = ? WHERE id = ?", string(raw), repoID)
 91	return err
 92}
 93
 94func (s *Store) SetForkOf(repoID, parentID int64) error {
 95	_, err := s.DB.Exec("UPDATE repos SET fork_of = ? WHERE id = ?", parentID, repoID)
 96	return err
 97}
 98
 99func (s *Store) DeleteRepo(repoID int64) error {
100	res, err := s.DB.Exec("DELETE FROM repos WHERE id = ?", repoID)
101	if err != nil {
102		return err
103	}
104	if n, _ := res.RowsAffected(); n == 0 {
105		return ErrNotFound
106	}
107	return nil
108}
109
110// ListReposForUser returns repos the user owns, reaches through an org
111// (unless the org scopes members to 'none'), has an explicit grant on, or
112// reaches through a team.
113func (s *Store) ListReposForUser(userID int64) ([]Repo, error) {
114	rows, err := s.DB.Query(repoSelect+`
115		LEFT JOIN repo_access a ON a.repo_id = r.id AND a.subject_kind = 'user' AND a.subject_id = ?
116		LEFT JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.user_id = ?
117		LEFT JOIN orgs og ON r.owner_kind = 'org' AND og.id = r.owner_id
118		WHERE (r.owner_kind = 'user' AND r.owner_id = ?)
119		   OR a.subject_id IS NOT NULL
120		   OR (m.user_id IS NOT NULL AND (m.role = 'admin' OR og.members_role <> 'none'))
121		   OR EXISTS (SELECT 1 FROM team_repos tr
122		              JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?
123		              WHERE tr.repo_id = r.id)
124		GROUP BY r.id
125		ORDER BY 4, r.name`, userID, userID, userID, userID)
126	if err != nil {
127		return nil, err
128	}
129	defer rows.Close()
130	var out []Repo
131	for rows.Next() {
132		r, err := scanRepo(rows)
133		if err != nil {
134			return nil, err
135		}
136		out = append(out, r)
137	}
138	return out, rows.Err()
139}
140
141// AccessRole returns the user's effective role on the repo ("" if none):
142// the strongest of any explicit grant, the role derived from org
143// membership (org admin -> admin; plain member -> the org's members_role,
144// 'write' by default so the pre-teams model is the degenerate case), and
145// any team grants on the repo.
146func (s *Store) AccessRole(repoID, userID int64) (string, error) {
147	rank := map[string]int{"": 0, "none": 0, "read": 1, "write": 2, "admin": 3}
148	best := ""
149	better := func(role string) {
150		if rank[role] > rank[best] {
151			best = role
152		}
153	}
154
155	var explicit string
156	err := s.DB.QueryRow(
157		"SELECT role FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
158		repoID, userID).Scan(&explicit)
159	if err != nil && !errors.Is(err, sql.ErrNoRows) {
160		return "", err
161	}
162	better(explicit)
163
164	var orgRole, membersRole string
165	err = s.DB.QueryRow(`
166		SELECT m.role, o.members_role FROM repos r
167		JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.user_id = ?
168		JOIN orgs o ON o.id = r.owner_id
169		WHERE r.id = ?`, userID, repoID).Scan(&orgRole, &membersRole)
170	if err != nil && !errors.Is(err, sql.ErrNoRows) {
171		return "", err
172	}
173	if orgRole == "admin" {
174		better("admin")
175	} else if orgRole == "member" {
176		better(membersRole) // write | read | none
177	}
178
179	var teamRole string
180	err = s.DB.QueryRow(`
181		SELECT tr.role FROM team_repos tr
182		JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?
183		WHERE tr.repo_id = ?
184		ORDER BY CASE tr.role WHEN 'admin' THEN 3 WHEN 'write' THEN 2 ELSE 1 END DESC
185		LIMIT 1`, userID, repoID).Scan(&teamRole)
186	if err != nil && !errors.Is(err, sql.ErrNoRows) {
187		return "", err
188	}
189	better(teamRole)
190	return best, nil
191}
192
193func (s *Store) GrantAccess(repoID, userID int64, role string) error {
194	_, err := s.DB.Exec(`
195		INSERT INTO repo_access (repo_id, subject_kind, subject_id, role) VALUES (?, 'user', ?, ?)
196		ON CONFLICT (repo_id, subject_kind, subject_id) DO UPDATE SET role = excluded.role`,
197		repoID, userID, role)
198	return err
199}
200
201func (s *Store) RevokeAccess(repoID, userID int64) error {
202	res, err := s.DB.Exec(
203		"DELETE FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
204		repoID, userID)
205	if err != nil {
206		return err
207	}
208	if n, _ := res.RowsAffected(); n == 0 {
209		return ErrNotFound
210	}
211	return nil
212}
213
214type AccessEntry struct {
215	Username string
216	Role     string
217}
218
219func (s *Store) ListAccess(repoID int64) ([]AccessEntry, error) {
220	rows, err := s.DB.Query(`
221		SELECT u.username, a.role FROM repo_access a
222		JOIN users u ON a.subject_kind = 'user' AND u.id = a.subject_id
223		WHERE a.repo_id = ? ORDER BY u.username`, repoID)
224	if err != nil {
225		return nil, err
226	}
227	defer rows.Close()
228	var out []AccessEntry
229	for rows.Next() {
230		var e AccessEntry
231		if err := rows.Scan(&e.Username, &e.Role); err != nil {
232			return nil, err
233		}
234		out = append(out, e)
235	}
236	return out, rows.Err()
237}
238
239func (s *Store) RepoByID(id int64) (Repo, error) {
240	r, err := scanRepo(s.DB.QueryRow(repoSelect+" WHERE r.id = ?", id))
241	if errors.Is(err, sql.ErrNoRows) {
242		return Repo{}, ErrNotFound
243	}
244	return r, err
245}
246
247// ListPublicRepos returns all public repositories, for the anonymous index.
248func (s *Store) ListPublicRepos() ([]Repo, error) {
249	rows, err := s.DB.Query(repoSelect + " WHERE r.visibility = 'public' ORDER BY 4, r.name")
250	if err != nil {
251		return nil, err
252	}
253	defer rows.Close()
254	var out []Repo
255	for rows.Next() {
256		r, err := scanRepo(rows)
257		if err != nil {
258			return nil, err
259		}
260		out = append(out, r)
261	}
262	return out, rows.Err()
263}
264
265func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error {
266	_, err := s.DB.Exec("UPDATE repos SET default_branch = ? WHERE id = ?", branch, repoID)
267	return err
268}
269
270// ListReposForOwner returns every repo owned by one user or org; the caller
271// filters by viewer visibility.
272func (s *Store) ListReposForOwner(ownerKind string, ownerID int64) ([]Repo, error) {
273	rows, err := s.DB.Query(repoSelect+" WHERE r.owner_kind = ? AND r.owner_id = ? ORDER BY r.name",
274		ownerKind, ownerID)
275	if err != nil {
276		return nil, err
277	}
278	defer rows.Close()
279	var out []Repo
280	for rows.Next() {
281		r, err := scanRepo(rows)
282		if err != nil {
283			return nil, err
284		}
285		out = append(out, r)
286	}
287	return out, rows.Err()
288}
289
290// TransferRepo moves a repository to a new owner. The unique index on
291// (owner_kind, owner_id, name) refuses collisions in the target namespace.
292func (s *Store) TransferRepo(repoID int64, newKind string, newOwnerID int64) error {
293	_, err := s.DB.Exec("UPDATE repos SET owner_kind = ?, owner_id = ? WHERE id = ?",
294		newKind, newOwnerID, repoID)
295	if isUniqueErr(err) {
296		return fmt.Errorf("the target owner already has a repository by that name")
297	}
298	return err
299}