BlueGit

timfa bluegit

Files

bluegit / internal / store / repos.go

repos.go

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