BlueGit

timfa bluegit

Files

bluegit / internal / store / repos.go

repos.go

repos.go 33.2 KiB Download Raw
1package store
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "fmt"
8 "sort"
9 "strings"
10 "time"
11
12 "gitlab.com/Timfa/bluegit/internal/access"
13 "gitlab.com/Timfa/bluegit/internal/i18n"
14 "gitlab.com/Timfa/bluegit/internal/names"
15)
16
17// Group is een verzameling repositories en leden.
18type Group struct {
19 ID int64
20 Name string
21 Path string
22 Description string
23 Visibility string
24 DefaultRole access.Role
25 LogoMIME string
26 CreatedBy int64
27 OwnerID int64
28 CreatedAt time.Time
29}
30
31// HasLogo meldt of er een geüpload logo is.
32func (g Group) HasLogo() bool { return g.LogoMIME != "" }
33
34// LogoURL is het pad van het groepslogo, of leeg.
35func (g Group) LogoURL() string {
36 if !g.HasLogo() {
37 return ""
38 }
39 return "/groups/" + g.Path + "/logo"
40}
41
42// Repo is een git-repository van een gebruiker of een groep.
43type Repo struct {
44 ID int64
45 OwnerKind string
46 OwnerID int64
47 OwnerPath string
48 Name string
49 Description string
50 DefaultBranch string
51 Visibility string
52 LogoMIME string
53 CreatedAt time.Time
54 // ReleaseVisibility is "inherit" (zelfde als de repo), "private" of
55 // "public". Zie ReleasesPublic.
56 ReleaseVisibility string
57 // PushedAt is het moment van de laatste push. Nul: nog nooit gepusht.
58 PushedAt time.Time
59 // CIPaused: geen nieuwe pipelines in de wachtrij (push, MR, handmatig).
60 CIPaused bool
61}
62
63// ReleasesPublic meldt of releases (pagina, notities, assets) voor
64// niet-leden zichtbaar zijn. Broncode valt hier nooit onder.
65func (r Repo) ReleasesPublic() bool {
66 switch r.ReleaseVisibility {
67 case "public":
68 return true
69 case "private":
70 return false
71 default:
72 return r.Visibility == "public"
73 }
74}
75
76// ValidReleaseVisibility kent inherit, private en public.
77func ValidReleaseVisibility(v string) bool {
78 return v == "inherit" || v == "private" || v == "public"
79}
80
81// SetReleaseVisibility zet de zichtbaarheid van releases.
82func (s *Store) SetReleaseVisibility(ctx context.Context, id int64, v string) error {
83 if !ValidReleaseVisibility(v) {
84 return i18n.E("err.releaseVisibility")
85 }
86 _, err := s.db.ExecContext(ctx, `UPDATE repos SET release_visibility = ? WHERE id = ?`, v, id)
87 return err
88}
89
90// ListReleaseOnlyRepoIDs geeft privé repositories met publieke releases
91// waar deze gebruiker geen lid van is (0 = anoniem). Alleen naam, korte
92// beschrijving en de Releases-pagina zijn voor hen zichtbaar.
93func (s *Store) ListReleaseOnlyRepoIDs(ctx context.Context, userID int64) ([]int64, error) {
94 rows, err := s.db.QueryContext(ctx, `SELECT id FROM repos WHERE visibility = 'private' AND release_visibility = 'public' ORDER BY id DESC`)
95 if err != nil {
96 return nil, err
97 }
98 var ids []int64
99 for rows.Next() {
100 var id int64
101 if err := rows.Scan(&id); err != nil {
102 rows.Close()
103 return nil, err
104 }
105 ids = append(ids, id)
106 }
107 rows.Close()
108 if err := rows.Err(); err != nil {
109 return nil, err
110 }
111 var out []int64
112 for _, id := range ids {
113 role, err := s.EffectiveRole(ctx, userID, id)
114 if err != nil {
115 return nil, err
116 }
117 if !role.CanRead() {
118 out = append(out, id)
119 }
120 }
121 return out, nil
122}
123
124// HasLogo meldt of er een geüpload logo is.
125func (r Repo) HasLogo() bool { return r.LogoMIME != "" }
126
127// LogoURL is het pad van het repologo, of leeg.
128func (r Repo) LogoURL() string {
129 if !r.HasLogo() {
130 return ""
131 }
132 return "/" + r.FullPath() + "/-/logo"
133}
134
135// FullPath is owner/naam.
136func (r Repo) FullPath() string { return r.OwnerPath + "/" + r.Name }
137
138// CreateGroup maakt een groep. De maker wordt beheerder.
139// defaultRole is de rol die leden krijgen op een repository die daarna ontstaat.
140func (s *Store) CreateGroup(ctx context.Context, creator int64, name, path, description string, defaultRole access.Role) (Group, error) {
141 name = strings.TrimSpace(name)
142 path = strings.ToLower(strings.TrimSpace(path))
143 if name == "" {
144 return Group{}, i18n.E("err.groupNeedsName")
145 }
146 if defaultRole == "" {
147 defaultRole = access.RoleDeveloper
148 }
149 if _, err := access.ParseRole(string(defaultRole)); err != nil {
150 return Group{}, err
151 }
152 if err := names.ValidGroupPath(path); err != nil {
153 return Group{}, err
154 }
155 if err := s.ensurePathFree(ctx, path); err != nil {
156 return Group{}, err
157 }
158 res, err := s.db.ExecContext(ctx, `INSERT INTO groups (name, path, description, visibility, default_role, created_by, owner_id, created_at) VALUES (?, ?, ?, 'private', ?, ?, ?, ?)`,
159 name, path, strings.TrimSpace(description), string(defaultRole), creator, creator, now())
160 if err != nil {
161 return Group{}, err
162 }
163 id, _ := res.LastInsertId()
164 if _, err := s.db.ExecContext(ctx, `INSERT INTO group_members (group_id, user_id, role) VALUES (?, ?, ?)`, id, creator, string(access.RoleMaintainer)); err != nil {
165 return Group{}, err
166 }
167 return s.GroupByID(ctx, id)
168}
169
170func (s *Store) ensurePathFree(ctx context.Context, path string) error {
171 var n int
172 if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE username = ?`, path).Scan(&n); err != nil {
173 return err
174 }
175 if n > 0 {
176 return i18n.E("err.pathUser", path)
177 }
178 if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM groups WHERE path = ?`, path).Scan(&n); err != nil {
179 return err
180 }
181 if n > 0 {
182 return i18n.E("err.pathGroup", path)
183 }
184 return nil
185}
186
187// GroupByPath leest een groep.
188func (s *Store) GroupByPath(ctx context.Context, path string) (Group, error) {
189 row := s.db.QueryRowContext(ctx, `SELECT `+groupCols+` FROM groups WHERE path = ?`, path)
190 return scanGroup(row)
191}
192
193// GroupByID leest een groep.
194func (s *Store) GroupByID(ctx context.Context, id int64) (Group, error) {
195 row := s.db.QueryRowContext(ctx, `SELECT `+groupCols+` FROM groups WHERE id = ?`, id)
196 return scanGroup(row)
197}
198
199const groupCols = `id, name, path, description, created_by, created_at, visibility, default_role, logo_mime, owner_id`
200
201func scanGroup(row scanner) (Group, error) {
202 var g Group
203 var created, role string
204 if err := row.Scan(&g.ID, &g.Name, &g.Path, &g.Description, &g.CreatedBy, &created, &g.Visibility, &role, &g.LogoMIME, &g.OwnerID); err != nil {
205 if errors.Is(err, sql.ErrNoRows) {
206 return Group{}, errNotFound
207 }
208 return Group{}, err
209 }
210 g.DefaultRole = access.Role(role)
211 g.CreatedAt = parseTime(created)
212 if g.OwnerID == 0 {
213 g.OwnerID = g.CreatedBy
214 }
215 return g, nil
216}
217
218// GroupRole is de rol van een gebruiker in een groep.
219// Installatiebeheer geeft geen lidmaatschap.
220func (s *Store) GroupRole(ctx context.Context, groupID, userID int64) (access.Role, error) {
221 if userID == 0 {
222 return access.RoleNone, nil
223 }
224 g, err := s.GroupByID(ctx, groupID)
225 if err != nil {
226 return access.RoleNone, err
227 }
228 if userID == g.OwnerID {
229 return access.RoleMaintainer, nil
230 }
231 var role string
232 err = s.db.QueryRowContext(ctx, `SELECT role FROM group_members WHERE group_id = ? AND user_id = ?`, groupID, userID).Scan(&role)
233 if errors.Is(err, sql.ErrNoRows) {
234 return access.RoleNone, nil
235 }
236 if err != nil {
237 return access.RoleNone, err
238 }
239 return access.Role(role), nil
240}
241
242// ListGroups geeft de groepen waarvan deze gebruiker lid is.
243func (s *Store) ListGroups(ctx context.Context, userID int64) ([]Group, error) {
244 q := `SELECT ` + groupCols + ` FROM groups WHERE id IN (SELECT group_id FROM group_members WHERE user_id = ?) ORDER BY path`
245 args := []any{userID}
246 rows, err := s.db.QueryContext(ctx, q, args...)
247 if err != nil {
248 return nil, err
249 }
250 defer rows.Close()
251 var out []Group
252 for rows.Next() {
253 g, err := scanGroup(rows)
254 if err != nil {
255 return nil, err
256 }
257 out = append(out, g)
258 }
259 return out, rows.Err()
260}
261
262// CreateRepo maakt de metadata. De schijfmap maakt de aanroeper.
263func (s *Store) CreateRepo(ctx context.Context, ownerKind string, ownerID int64, name, description, defaultBranch, visibility string) (Repo, error) {
264 if ownerKind != "user" && ownerKind != "group" {
265 return Repo{}, i18n.E("err.ownerKind")
266 }
267 if err := names.ValidRepoName(name); err != nil {
268 return Repo{}, err
269 }
270 if visibility != "public" && visibility != "private" {
271 return Repo{}, i18n.E("err.visibility")
272 }
273 if defaultBranch == "" {
274 defaultBranch = "master"
275 }
276 if ownerKind == "user" {
277 u, err := s.UserByID(ctx, ownerID)
278 if err != nil {
279 return Repo{}, err
280 }
281 var n int
282 if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM groups WHERE path = ?`, u.Username).Scan(&n); err != nil {
283 return Repo{}, err
284 }
285 if n > 0 {
286 return Repo{}, i18n.E("err.userGroupClash", u.Username)
287 }
288 }
289 res, err := s.db.ExecContext(ctx, `INSERT INTO repos (owner_kind, owner_id, name, description, default_branch, visibility, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
290 ownerKind, ownerID, name, strings.TrimSpace(description), defaultBranch, visibility, now())
291 if err != nil {
292 if strings.Contains(err.Error(), "UNIQUE") {
293 return Repo{}, i18n.E("err.repoExists", name)
294 }
295 return Repo{}, err
296 }
297 id, _ := res.LastInsertId()
298 if err := s.AddProtected(ctx, id, defaultBranch); err != nil {
299 return Repo{}, err
300 }
301 if ownerKind == "group" {
302 if err := s.GrantDefaultRoles(ctx, ownerID, id); err != nil {
303 return Repo{}, err
304 }
305 }
306 return s.RepoByID(ctx, id)
307}
308
309// RepoByID leest een repository.
310func (s *Store) RepoByID(ctx context.Context, id int64) (Repo, error) {
311 row := s.db.QueryRowContext(ctx, repoSelect+` WHERE r.id = ?`, id)
312 return scanRepo(row)
313}
314
315// RepoByPath leest owner/naam.
316func (s *Store) RepoByPath(ctx context.Context, owner, name string) (Repo, error) {
317 row := s.db.QueryRowContext(ctx, repoSelect+`
318 WHERE r.name = ? AND (
319 (r.owner_kind = 'user' AND r.owner_id = (SELECT id FROM users WHERE username = ?))
320 OR (r.owner_kind = 'group' AND r.owner_id = (SELECT id FROM groups WHERE path = ?))
321 )`, name, owner, owner)
322 return scanRepo(row)
323}
324
325const repoSelect = `
326SELECT r.id, r.owner_kind, r.owner_id,
327 CASE r.owner_kind WHEN 'user' THEN (SELECT username FROM users WHERE id = r.owner_id) ELSE (SELECT path FROM groups WHERE id = r.owner_id) END,
328 r.name, r.description, r.default_branch, r.visibility, r.created_at, r.logo_mime, r.release_visibility, r.pushed_at, r.ci_paused
329FROM repos r`
330
331func scanRepo(row *sql.Row) (Repo, error) {
332 var r Repo
333 var created, pushed string
334 var owner sql.NullString
335 var paused int
336 if err := row.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &owner, &r.Name, &r.Description, &r.DefaultBranch, &r.Visibility, &created, &r.LogoMIME, &r.ReleaseVisibility, &pushed, &paused); err != nil {
337 if errors.Is(err, sql.ErrNoRows) {
338 return Repo{}, errNotFound
339 }
340 return Repo{}, err
341 }
342 r.OwnerPath = owner.String
343 r.CreatedAt = parseTime(created)
344 if pushed != "" {
345 r.PushedAt = parseTime(pushed)
346 }
347 r.CIPaused = paused == 1
348 return r, nil
349}
350
351// UpdateRepo wijzigt beschrijving en zichtbaarheid.
352func (s *Store) UpdateRepo(ctx context.Context, id int64, description, visibility string) error {
353 if visibility != "public" && visibility != "private" {
354 return i18n.E("err.visibility")
355 }
356 _, err := s.db.ExecContext(ctx, `UPDATE repos SET description = ?, visibility = ? WHERE id = ?`, strings.TrimSpace(description), visibility, id)
357 return err
358}
359
360// SetDefaultBranch zet de standaardbranch in de metadata. De aanroeper
361// zet HEAD in de bare repository.
362func (s *Store) SetDefaultBranch(ctx context.Context, id int64, branch string) error {
363 branch = strings.TrimSpace(branch)
364 if branch == "" {
365 return i18n.E("err.branchMissing")
366 }
367 _, err := s.db.ExecContext(ctx, `UPDATE repos SET default_branch = ? WHERE id = ?`, branch, id)
368 return err
369}
370
371// SetRepoCIPaused zet of er nieuwe pipelines mogen worden ingepland.
372func (s *Store) SetRepoCIPaused(ctx context.Context, id int64, paused bool) error {
373 _, err := s.db.ExecContext(ctx, `UPDATE repos SET ci_paused = ? WHERE id = ?`, boolInt(paused), id)
374 return err
375}
376
377// DeleteRepo verwijdert de metadata. Bestanden verwijdert de aanroeper.
378func (s *Store) DeleteRepo(ctx context.Context, id int64) error {
379 // Forks blijven bestaan als zelfstandige repositories.
380 if _, err := s.db.ExecContext(ctx, `UPDATE repos SET fork_of = 0 WHERE fork_of = ?`, id); err != nil {
381 return err
382 }
383 _, err := s.db.ExecContext(ctx, `DELETE FROM repos WHERE id = ?`, id)
384 return err
385}
386
387// ListRepoIDs geeft repositories die deze gebruiker mag zien:
388// openbare repositories, eigen repositories, repositories van een groep
389// waarvan hij lid is, en repositories met een rechtstreeks lidmaatschap.
390// Installatiebeheer voegt daar niets aan toe.
391func (s *Store) ListRepoIDs(ctx context.Context, userID int64) ([]int64, error) {
392 q := `SELECT id FROM repos WHERE visibility = 'public'`
393 args := []any{}
394 if userID != 0 {
395 q = `SELECT DISTINCT id FROM repos WHERE visibility = 'public'
396 OR (owner_kind = 'user' AND owner_id = ?)
397 OR (owner_kind = 'group' AND owner_id IN (SELECT group_id FROM group_members WHERE user_id = ?))
398 OR id IN (SELECT repo_id FROM repo_members WHERE user_id = ?)`
399 args = []any{userID, userID, userID}
400 }
401 q += ` ORDER BY id DESC`
402 rows, err := s.db.QueryContext(ctx, q, args...)
403 if err != nil {
404 return nil, err
405 }
406 defer rows.Close()
407 var ids []int64
408 for rows.Next() {
409 var id int64
410 if err := rows.Scan(&id); err != nil {
411 return nil, err
412 }
413 ids = append(ids, id)
414 }
415 return ids, rows.Err()
416}
417
418// pushOrder: laatste push bovenaan, repos zonder push onderaan, daarna op naam.
419const pushOrder = `(r.pushed_at = ''), r.pushed_at DESC, r.name COLLATE NOCASE, r.id`
420
421// ReposByOwner geeft de repositories van een gebruiker, laatste push eerst.
422func (s *Store) ReposByOwner(ctx context.Context, userID int64) ([]Repo, error) {
423 rows, err := s.db.QueryContext(ctx, repoSelect+` WHERE r.owner_kind = 'user' AND r.owner_id = ? ORDER BY `+pushOrder, userID)
424 if err != nil {
425 return nil, err
426 }
427 defer rows.Close()
428 return scanRepos(rows)
429}
430
431// CountRepos telt repositories van een eigenaar. publicOnly slaat privé over.
432func (s *Store) CountRepos(ctx context.Context, ownerKind string, ownerID int64, publicOnly bool) (int, error) {
433 q := `SELECT COUNT(*) FROM repos WHERE owner_kind = ? AND owner_id = ?`
434 if publicOnly {
435 q += ` AND visibility = 'public'`
436 }
437 var n int
438 err := s.db.QueryRowContext(ctx, q, ownerKind, ownerID).Scan(&n)
439 return n, err
440}
441
442// ReposByGroup geeft de repositories van een groep.
443func (s *Store) ReposByGroup(ctx context.Context, groupID int64) ([]Repo, error) {
444 rows, err := s.db.QueryContext(ctx, repoSelect+` WHERE r.owner_kind = 'group' AND r.owner_id = ? ORDER BY `+pushOrder, groupID)
445 if err != nil {
446 return nil, err
447 }
448 defer rows.Close()
449 return scanRepos(rows)
450}
451
452// ReposByIDs laadt een lijst.
453func (s *Store) ReposByIDs(ctx context.Context, ids []int64) ([]Repo, error) {
454 var out []Repo
455 for _, id := range ids {
456 r, err := s.RepoByID(ctx, id)
457 if err != nil {
458 return nil, err
459 }
460 out = append(out, r)
461 }
462 return out, nil
463}
464
465func scanRepos(rows *sql.Rows) ([]Repo, error) {
466 var out []Repo
467 for rows.Next() {
468 var r Repo
469 var created, pushed string
470 var owner sql.NullString
471 var paused int
472 if err := rows.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &owner, &r.Name, &r.Description, &r.DefaultBranch, &r.Visibility, &created, &r.LogoMIME, &r.ReleaseVisibility, &pushed, &paused); err != nil {
473 return nil, err
474 }
475 r.OwnerPath = owner.String
476 r.CreatedAt = parseTime(created)
477 if pushed != "" {
478 r.PushedAt = parseTime(pushed)
479 }
480 r.CIPaused = paused == 1
481 out = append(out, r)
482 }
483 return out, rows.Err()
484}
485
486// AllRepos is voor het verversen van hooks bij het starten.
487func (s *Store) AllRepos(ctx context.Context) ([]Repo, error) {
488 rows, err := s.db.QueryContext(ctx, repoSelect+` ORDER BY r.id`)
489 if err != nil {
490 return nil, err
491 }
492 defer rows.Close()
493 return scanRepos(rows)
494}
495
496// EffectiveRole past de rolregels toe op een repository.
497func (s *Store) EffectiveRole(ctx context.Context, userID, repoID int64) (access.Role, error) {
498 if userID == 0 {
499 return access.RoleNone, nil
500 }
501 if _, err := s.UserByID(ctx, userID); err != nil {
502 return access.RoleNone, err
503 }
504 repo, err := s.RepoByID(ctx, repoID)
505 if err != nil {
506 return access.RoleNone, err
507 }
508 in := access.Input{}
509 if repo.OwnerKind == "user" && repo.OwnerID == userID {
510 in.UserOwner = true
511 }
512 if repo.OwnerKind == "group" {
513 role, err := s.GroupRole(ctx, repo.OwnerID, userID)
514 if err != nil {
515 return access.RoleNone, err
516 }
517 in.GroupRole = role
518 }
519 var role string
520 err = s.db.QueryRowContext(ctx, `SELECT role FROM repo_members WHERE repo_id = ? AND user_id = ?`, repoID, userID).Scan(&role)
521 if err != nil && !errors.Is(err, sql.ErrNoRows) {
522 return access.RoleNone, err
523 }
524 if err == nil {
525 in.RepoRole = access.Role(role)
526 }
527 return access.Resolve(in), nil
528}
529
530// Member is een lid of een uitnodiging op gebruikersnaam.
531type Member struct {
532 UserID int64
533 Username string
534 AvatarURL string
535 Role access.Role
536 Pending bool
537}
538
539// SetMember zet een lidmaatschap. Een onbekende naam blijft wachten tot de eerste login.
540func (s *Store) SetMember(ctx context.Context, scopeKind string, scopeID int64, username string, role access.Role) error {
541 if scopeKind != "repo" && scopeKind != "group" {
542 return i18n.E("err.scope")
543 }
544 if _, err := access.ParseRole(string(role)); err != nil {
545 return err
546 }
547 username = strings.ToLower(strings.TrimSpace(username))
548 if err := names.ValidUsername(username); err != nil {
549 return err
550 }
551 if scopeKind == "group" && role != access.RoleMaintainer {
552 g, err := s.GroupByID(ctx, scopeID)
553 if err != nil {
554 return err
555 }
556 owner, err := s.UserByID(ctx, g.OwnerID)
557 if err == nil && owner.Username == username {
558 return i18n.E("err.ownerRole")
559 }
560 }
561 u, err := s.UserByUsername(ctx, username)
562 if IsNotFound(err) {
563 _, err = s.db.ExecContext(ctx, `INSERT INTO pending_members (scope_kind, scope_id, username, role) VALUES (?, ?, ?, ?)
564 ON CONFLICT(scope_kind, scope_id, username) DO UPDATE SET role = excluded.role`, scopeKind, scopeID, username, string(role))
565 return err
566 }
567 if err != nil {
568 return err
569 }
570 table, col := "repo_members", "repo_id"
571 if scopeKind == "group" {
572 table, col = "group_members", "group_id"
573 }
574 _, err = s.db.ExecContext(ctx, `INSERT INTO `+table+` (`+col+`, user_id, role) VALUES (?, ?, ?)
575 ON CONFLICT(`+col+`, user_id) DO UPDATE SET role = excluded.role`, scopeID, u.ID, string(role))
576 return err
577}
578
579// RemoveMember haalt een lid of een uitnodiging weg.
580func (s *Store) RemoveMember(ctx context.Context, scopeKind string, scopeID int64, username string) error {
581 username = strings.ToLower(strings.TrimSpace(username))
582 _, err := s.db.ExecContext(ctx, `DELETE FROM pending_members WHERE scope_kind = ? AND scope_id = ? AND username = ?`, scopeKind, scopeID, username)
583 if err != nil {
584 return err
585 }
586 u, err := s.UserByUsername(ctx, username)
587 if IsNotFound(err) {
588 return nil
589 }
590 if err != nil {
591 return err
592 }
593 if scopeKind == "group" {
594 g, err := s.GroupByID(ctx, scopeID)
595 if err != nil {
596 return err
597 }
598 if u.ID == g.OwnerID {
599 return i18n.E("err.ownerRole")
600 }
601 _, err = s.db.ExecContext(ctx, `DELETE FROM group_members WHERE group_id = ? AND user_id = ?`, scopeID, u.ID)
602 return err
603 }
604 _, err = s.db.ExecContext(ctx, `DELETE FROM repo_members WHERE repo_id = ? AND user_id = ?`, scopeID, u.ID)
605 return err
606}
607
608// ListMembers geeft leden van een repository of groep, plus open uitnodigingen.
609func (s *Store) ListMembers(ctx context.Context, scopeKind string, scopeID int64) ([]Member, error) {
610 var q string
611 if scopeKind == "group" {
612 q = `SELECT u.id, u.username, u.avatar_url, m.role FROM group_members m JOIN users u ON u.id = m.user_id WHERE m.group_id = ? ORDER BY u.username`
613 } else {
614 q = `SELECT u.id, u.username, u.avatar_url, m.role FROM repo_members m JOIN users u ON u.id = m.user_id WHERE m.repo_id = ? ORDER BY u.username`
615 }
616 rows, err := s.db.QueryContext(ctx, q, scopeID)
617 if err != nil {
618 return nil, err
619 }
620 defer rows.Close()
621 var out []Member
622 for rows.Next() {
623 var m Member
624 var role string
625 if err := rows.Scan(&m.UserID, &m.Username, &m.AvatarURL, &role); err != nil {
626 return nil, err
627 }
628 m.Role = access.Role(role)
629 out = append(out, m)
630 }
631 if err := rows.Err(); err != nil {
632 return nil, err
633 }
634 prows, err := s.db.QueryContext(ctx, `SELECT username, role FROM pending_members WHERE scope_kind = ? AND scope_id = ? ORDER BY username`, scopeKind, scopeID)
635 if err != nil {
636 return nil, err
637 }
638 defer prows.Close()
639 for prows.Next() {
640 var m Member
641 var role string
642 if err := prows.Scan(&m.Username, &role); err != nil {
643 return nil, err
644 }
645 m.Role = access.Role(role)
646 m.Pending = true
647 out = append(out, m)
648 }
649 return out, prows.Err()
650}
651
652// ProtectedPatterns geeft de beschermde branchpatronen.
653func (s *Store) ProtectedPatterns(ctx context.Context, repoID int64) ([]string, error) {
654 rows, err := s.db.QueryContext(ctx, `SELECT pattern FROM protected_branches WHERE repo_id = ? ORDER BY pattern`, repoID)
655 if err != nil {
656 return nil, err
657 }
658 defer rows.Close()
659 var out []string
660 for rows.Next() {
661 var p string
662 if err := rows.Scan(&p); err != nil {
663 return nil, err
664 }
665 out = append(out, p)
666 }
667 return out, rows.Err()
668}
669
670// AddProtected voegt een patroon toe.
671func (s *Store) AddProtected(ctx context.Context, repoID int64, pattern string) error {
672 pattern = strings.TrimSpace(pattern)
673 if pattern == "" || strings.Contains(pattern, " ") || strings.Contains(pattern, "..") {
674 return i18n.E("err.pattern", pattern)
675 }
676 _, err := s.db.ExecContext(ctx, `INSERT INTO protected_branches (repo_id, pattern) VALUES (?, ?)`, repoID, pattern)
677 if err != nil && strings.Contains(err.Error(), "UNIQUE") {
678 return nil
679 }
680 return err
681}
682
683// RemoveProtected haalt een patroon weg.
684func (s *Store) RemoveProtected(ctx context.Context, repoID int64, pattern string) error {
685 _, err := s.db.ExecContext(ctx, `DELETE FROM protected_branches WHERE repo_id = ? AND pattern = ?`, repoID, pattern)
686 return err
687}
688
689// ProtectedTagPatterns geeft de beschermde tagpatronen.
690func (s *Store) ProtectedTagPatterns(ctx context.Context, repoID int64) ([]string, error) {
691 rows, err := s.db.QueryContext(ctx, `SELECT pattern FROM protected_tags WHERE repo_id = ? ORDER BY pattern`, repoID)
692 if err != nil {
693 return nil, err
694 }
695 defer rows.Close()
696 var out []string
697 for rows.Next() {
698 var p string
699 if err := rows.Scan(&p); err != nil {
700 return nil, err
701 }
702 out = append(out, p)
703 }
704 return out, rows.Err()
705}
706
707// AddProtectedTag voegt een tagpatroon toe.
708func (s *Store) AddProtectedTag(ctx context.Context, repoID int64, pattern string) error {
709 pattern = strings.TrimSpace(pattern)
710 if pattern == "" || strings.Contains(pattern, " ") || strings.Contains(pattern, "..") {
711 return i18n.E("err.pattern", pattern)
712 }
713 _, err := s.db.ExecContext(ctx, `INSERT INTO protected_tags (repo_id, pattern) VALUES (?, ?)`, repoID, pattern)
714 if err != nil && strings.Contains(err.Error(), "UNIQUE") {
715 return nil
716 }
717 return err
718}
719
720// RemoveProtectedTag haalt een tagpatroon weg.
721func (s *Store) RemoveProtectedTag(ctx context.Context, repoID int64, pattern string) error {
722 _, err := s.db.ExecContext(ctx, `DELETE FROM protected_tags WHERE repo_id = ? AND pattern = ?`, repoID, pattern)
723 return err
724}
725
726// SecretMeta is een geheim zonder de waarde.
727type SecretMeta struct {
728 Name string
729 Protected bool
730 Invisible bool
731 // Expand: $NAAM en ${NAAM} in de waarde worden in de runner vervangen.
732 Expand bool
733 CreatedAt time.Time
734}
735
736// PutSecret bewaart een versleutelde waarde. De naam is een omgevingsvariabele.
737// Bij een bestaande naam blijven waarde en protected bijgewerkt; invisible wordt nooit gewist.
738func (s *Store) PutSecret(ctx context.Context, scopeKind string, scopeID int64, name, value string, protected bool) error {
739 if scopeKind != "repo" && scopeKind != "group" {
740 return i18n.E("err.scope")
741 }
742 if err := access.ValidSecretName(name); err != nil {
743 return err
744 }
745 if strings.TrimSpace(value) == "" {
746 return i18n.E("err.emptyValue")
747 }
748 nonce, ct, err := s.encrypt(value)
749 if err != nil {
750 return err
751 }
752 _, err = s.db.ExecContext(ctx, `INSERT INTO secrets (scope_kind, scope_id, name, ciphertext, nonce, protected, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)
753 ON CONFLICT(scope_kind, scope_id, name) DO UPDATE SET ciphertext = excluded.ciphertext, nonce = excluded.nonce, protected = excluded.protected`,
754 scopeKind, scopeID, name, ct, nonce, boolInt(protected), now())
755 return err
756}
757
758// DeleteSecret verwijdert een geheim.
759func (s *Store) DeleteSecret(ctx context.Context, scopeKind string, scopeID int64, name string) error {
760 res, err := s.db.ExecContext(ctx, `DELETE FROM secrets WHERE scope_kind = ? AND scope_id = ? AND name = ?`, scopeKind, scopeID, name)
761 if err != nil {
762 return err
763 }
764 n, _ := res.RowsAffected()
765 if n == 0 {
766 return errNotFound
767 }
768 return nil
769}
770
771// CreateSecret voegt een geheim toe. Een bestaande naam wordt niet overschreven.
772func (s *Store) CreateSecret(ctx context.Context, scopeKind string, scopeID int64, name, value string, protected, invisible bool) error {
773 nonce, ct, err := s.secretCipher(scopeKind, name, value)
774 if err != nil {
775 return err
776 }
777 _, err = s.db.ExecContext(ctx, `INSERT INTO secrets (scope_kind, scope_id, name, ciphertext, nonce, protected, invisible, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
778 scopeKind, scopeID, name, ct, nonce, boolInt(protected), boolInt(invisible), now())
779 if err != nil && strings.Contains(err.Error(), "UNIQUE") {
780 return i18n.E("err.secretExists", name)
781 }
782 return err
783}
784
785// UpdateSecret wijzigt waarde en protected van een zichtbaar geheim.
786func (s *Store) UpdateSecret(ctx context.Context, scopeKind string, scopeID int64, name, value string, protected bool) error {
787 return s.writeSecret(ctx, scopeKind, scopeID, name, value, protected, false)
788}
789
790// ReplaceSecret zet een nieuwe waarde op een onzichtbaar geheim. De vlag blijft aan.
791func (s *Store) ReplaceSecret(ctx context.Context, scopeKind string, scopeID int64, name, value string, protected bool) error {
792 return s.writeSecret(ctx, scopeKind, scopeID, name, value, protected, true)
793}
794
795func (s *Store) writeSecret(ctx context.Context, scopeKind string, scopeID int64, name, value string, protected, invisible bool) error {
796 nonce, ct, err := s.secretCipher(scopeKind, name, value)
797 if err != nil {
798 return err
799 }
800 res, err := s.db.ExecContext(ctx, `UPDATE secrets SET ciphertext = ?, nonce = ?, protected = ? WHERE scope_kind = ? AND scope_id = ? AND name = ? AND invisible = ?`,
801 ct, nonce, boolInt(protected), scopeKind, scopeID, name, boolInt(invisible))
802 if err != nil {
803 return err
804 }
805 n, _ := res.RowsAffected()
806 if n == 1 {
807 return nil
808 }
809 return s.secretMiss(ctx, scopeKind, scopeID, name, invisible)
810}
811
812func (s *Store) secretCipher(scopeKind, name, value string) (nonce, ct []byte, err error) {
813 if scopeKind != "repo" && scopeKind != "group" {
814 return nil, nil, i18n.E("err.scope")
815 }
816 if err := access.ValidSecretName(name); err != nil {
817 return nil, nil, err
818 }
819 if strings.TrimSpace(value) == "" {
820 return nil, nil, i18n.E("err.emptyValue")
821 }
822 return s.encrypt(value)
823}
824
825func (s *Store) secretMiss(ctx context.Context, scopeKind string, scopeID int64, name string, wantInvisible bool) error {
826 var inv int
827 err := s.db.QueryRowContext(ctx, `SELECT invisible FROM secrets WHERE scope_kind = ? AND scope_id = ? AND name = ?`, scopeKind, scopeID, name).Scan(&inv)
828 if errors.Is(err, sql.ErrNoRows) {
829 return errNotFound
830 }
831 if err != nil {
832 return err
833 }
834 if wantInvisible && inv == 0 {
835 return i18n.E("err.secretVisible", name)
836 }
837 if !wantInvisible && inv == 1 {
838 return i18n.E("err.secretHidden", name)
839 }
840 return errNotFound
841}
842
843// RevealSecret geeft de waarde van een zichtbaar geheim.
844func (s *Store) RevealSecret(ctx context.Context, scopeKind string, scopeID int64, name string) (string, error) {
845 if scopeKind != "repo" && scopeKind != "group" {
846 return "", i18n.E("err.scope")
847 }
848 var ct, nonce []byte
849 var inv int
850 err := s.db.QueryRowContext(ctx, `SELECT ciphertext, nonce, invisible FROM secrets WHERE scope_kind = ? AND scope_id = ? AND name = ?`, scopeKind, scopeID, name).Scan(&ct, &nonce, &inv)
851 if errors.Is(err, sql.ErrNoRows) {
852 return "", errNotFound
853 }
854 if err != nil {
855 return "", err
856 }
857 if inv == 1 {
858 return "", i18n.E("err.secretHidden", name)
859 }
860 return s.decrypt(nonce, ct)
861}
862
863// ListSecrets geeft namen, niet de waarden.
864func (s *Store) ListSecrets(ctx context.Context, scopeKind string, scopeID int64) ([]SecretMeta, error) {
865 rows, err := s.db.QueryContext(ctx, `SELECT name, protected, invisible, expand, created_at FROM secrets WHERE scope_kind = ? AND scope_id = ? ORDER BY name`, scopeKind, scopeID)
866 if err != nil {
867 return nil, err
868 }
869 defer rows.Close()
870 var out []SecretMeta
871 for rows.Next() {
872 var m SecretMeta
873 var p, inv, exp int
874 var created string
875 if err := rows.Scan(&m.Name, &p, &inv, &exp, &created); err != nil {
876 return nil, err
877 }
878 m.Protected = p == 1
879 m.Invisible = inv == 1
880 m.Expand = exp == 1
881 m.CreatedAt = parseTime(created)
882 out = append(out, m)
883 }
884 return out, rows.Err()
885}
886
887// SecretValues ontcijfert geheimen voor een job of webhook.
888// refProtected bepaalt of beschermde geheimen meegaan.
889func (s *Store) SecretValues(ctx context.Context, scopeKind string, scopeID int64, refProtected bool) (map[string]string, error) {
890 rows, err := s.db.QueryContext(ctx, `SELECT name, ciphertext, nonce, protected FROM secrets WHERE scope_kind = ? AND scope_id = ?`, scopeKind, scopeID)
891 if err != nil {
892 return nil, err
893 }
894 defer rows.Close()
895 out := map[string]string{}
896 for rows.Next() {
897 var name string
898 var ct, nonce []byte
899 var p int
900 if err := rows.Scan(&name, &ct, &nonce, &p); err != nil {
901 return nil, err
902 }
903 if !access.InjectSecret(p == 1, refProtected) {
904 continue
905 }
906 val, err := s.decrypt(nonce, ct)
907 if err != nil {
908 return nil, err
909 }
910 out[name] = val
911 }
912 return out, rows.Err()
913}
914
915// TouchPushed zet het moment van de laatste push.
916func (s *Store) TouchPushed(ctx context.Context, repoID int64, at time.Time) error {
917 _, err := s.db.ExecContext(ctx, `UPDATE repos SET pushed_at = ? WHERE id = ? AND (pushed_at = '' OR pushed_at < ?)`,
918 at.UTC().Format(time.RFC3339), repoID, at.UTC().Format(time.RFC3339))
919 return err
920}
921
922// SortReposByPush sorteert zoals pushOrder: laatste push eerst, zonder push
923// onderaan, daarna op naam.
924func SortReposByPush(list []Repo) {
925 sort.SliceStable(list, func(i, j int) bool {
926 a, b := list[i], list[j]
927 if a.PushedAt.IsZero() != b.PushedAt.IsZero() {
928 return !a.PushedAt.IsZero()
929 }
930 if !a.PushedAt.Equal(b.PushedAt) {
931 return a.PushedAt.After(b.PushedAt)
932 }
933 if x, y := strings.ToLower(a.FullPath()), strings.ToLower(b.FullPath()); x != y {
934 return x < y
935 }
936 return a.ID < b.ID
937 })
938}
939
940// GroupPushTimes geeft per groep de laatste push in een van haar repos.
941// Groepen zonder push ontbreken in de map.
942func (s *Store) GroupPushTimes(ctx context.Context) (map[int64]time.Time, error) {
943 rows, err := s.db.QueryContext(ctx, `SELECT owner_id, MAX(pushed_at) FROM repos WHERE owner_kind = 'group' AND pushed_at <> '' GROUP BY owner_id`)
944 if err != nil {
945 return nil, err
946 }
947 defer rows.Close()
948 out := map[int64]time.Time{}
949 for rows.Next() {
950 var id int64
951 var at string
952 if err := rows.Scan(&id, &at); err != nil {
953 return nil, err
954 }
955 out[id] = parseTime(at)
956 }
957 return out, rows.Err()
958}
959
960// SortGroupsByPush: laatste push eerst, groepen zonder push onderaan, dan op naam.
961func SortGroupsByPush(list []Group, at map[int64]time.Time) {
962 sort.SliceStable(list, func(i, j int) bool {
963 a, b := at[list[i].ID], at[list[j].ID]
964 if a.IsZero() != b.IsZero() {
965 return !a.IsZero()
966 }
967 if !a.Equal(b) {
968 return a.After(b)
969 }
970 return strings.ToLower(list[i].Name) < strings.ToLower(list[j].Name)
971 })
972}
973
974// SetSecretExpand zet of de waarde variabelen uitbreidt.
975func (s *Store) SetSecretExpand(ctx context.Context, scopeKind string, scopeID int64, name string, on bool) error {
976 _, err := s.db.ExecContext(ctx, `UPDATE secrets SET expand = ? WHERE scope_kind = ? AND scope_id = ? AND name = ?`, boolInt(on), scopeKind, scopeID, name)
977 return err
978}
979
980// SecretExpandFlags geeft per geheimnaam of expand aan staat.
981func (s *Store) SecretExpandFlags(ctx context.Context, scopeKind string, scopeID int64) (map[string]bool, error) {
982 rows, err := s.db.QueryContext(ctx, `SELECT name, expand FROM secrets WHERE scope_kind = ? AND scope_id = ?`, scopeKind, scopeID)
983 if err != nil {
984 return nil, err
985 }
986 defer rows.Close()
987 out := map[string]bool{}
988 for rows.Next() {
989 var name string
990 var e int
991 if err := rows.Scan(&name, &e); err != nil {
992 return nil, err
993 }
994 out[name] = e == 1
995 }
996 return out, rows.Err()
997}
998
999// ErrGroupNotEmpty: een groep met repositories kan niet weg.
1000type ErrGroupNotEmpty struct{ Repos int }
1001
1002func (e ErrGroupNotEmpty) Error() string {
1003 return fmt.Sprintf("group still has %d repositories", e.Repos)
1004}
1005
1006// DeleteGroup verwijdert een lege groep met leden, uitnodigingen, geheimen,
1007// webhooks, goedkeuringsregels en groepsrunners. Een groep met repositories
1008// geeft ErrGroupNotEmpty; er is geen force.
1009func (s *Store) DeleteGroup(ctx context.Context, id int64) error {
1010 tx, err := s.db.BeginTx(ctx, nil)
1011 if err != nil {
1012 return err
1013 }
1014 defer tx.Rollback()
1015 var n int
1016 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM repos WHERE owner_kind = 'group' AND owner_id = ?`, id).Scan(&n); err != nil {
1017 return err
1018 }
1019 if n > 0 {
1020 return ErrGroupNotEmpty{Repos: n}
1021 }
1022 for _, q := range []string{
1023 `DELETE FROM group_members WHERE group_id = ?`,
1024 `DELETE FROM group_runner_optin WHERE group_id = ?`,
1025 `DELETE FROM pending_members WHERE scope_kind = 'group' AND scope_id = ?`,
1026 `DELETE FROM secrets WHERE scope_kind = 'group' AND scope_id = ?`,
1027 `DELETE FROM webhooks WHERE scope_kind = 'group' AND scope_id = ?`,
1028 `DELETE FROM approval_rules WHERE scope_kind = 'group' AND scope_id = ?`,
1029 `DELETE FROM runner_reg_tokens WHERE owner_kind = 'group' AND owner_id = ?`,
1030 `UPDATE runners SET revoked = 1 WHERE owner_kind = 'group' AND owner_id = ?`,
1031 `DELETE FROM groups WHERE id = ?`,
1032 } {
1033 if _, err := tx.ExecContext(ctx, q, id); err != nil {
1034 return err
1035 }
1036 }
1037 return tx.Commit()
1038}