BlueGit

timfa bluegit

Files

bluegit / internal / store / repos.go

repos.go

repos.go 32.4 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 // Forks blijven bestaan als zelfstandige repositories.
359 if _, err := s.db.ExecContext(ctx, `UPDATE repos SET fork_of = 0 WHERE fork_of = ?`, id); err != nil {
360 return err
361 }
362 _, err := s.db.ExecContext(ctx, `DELETE FROM repos WHERE id = ?`, id)
363 return err
364}
365
366// ListRepoIDs geeft repositories die deze gebruiker mag zien:
367// openbare repositories, eigen repositories, repositories van een groep
368// waarvan hij lid is, en repositories met een rechtstreeks lidmaatschap.
369// Installatiebeheer voegt daar niets aan toe.
370func (s *Store) ListRepoIDs(ctx context.Context, userID int64) ([]int64, error) {
371 q := `SELECT id FROM repos WHERE visibility = 'public'`
372 args := []any{}
373 if userID != 0 {
374 q = `SELECT DISTINCT id FROM repos WHERE visibility = 'public'
375 OR (owner_kind = 'user' AND owner_id = ?)
376 OR (owner_kind = 'group' AND owner_id IN (SELECT group_id FROM group_members WHERE user_id = ?))
377 OR id IN (SELECT repo_id FROM repo_members WHERE user_id = ?)`
378 args = []any{userID, userID, userID}
379 }
380 q += ` ORDER BY id DESC`
381 rows, err := s.db.QueryContext(ctx, q, args...)
382 if err != nil {
383 return nil, err
384 }
385 defer rows.Close()
386 var ids []int64
387 for rows.Next() {
388 var id int64
389 if err := rows.Scan(&id); err != nil {
390 return nil, err
391 }
392 ids = append(ids, id)
393 }
394 return ids, rows.Err()
395}
396
397// pushOrder: laatste push bovenaan, repos zonder push onderaan, daarna op naam.
398const pushOrder = `(r.pushed_at = ''), r.pushed_at DESC, r.name COLLATE NOCASE, r.id`
399
400// ReposByOwner geeft de repositories van een gebruiker, laatste push eerst.
401func (s *Store) ReposByOwner(ctx context.Context, userID int64) ([]Repo, error) {
402 rows, err := s.db.QueryContext(ctx, repoSelect+` WHERE r.owner_kind = 'user' AND r.owner_id = ? ORDER BY `+pushOrder, userID)
403 if err != nil {
404 return nil, err
405 }
406 defer rows.Close()
407 return scanRepos(rows)
408}
409
410// CountRepos telt repositories van een eigenaar. publicOnly slaat privé over.
411func (s *Store) CountRepos(ctx context.Context, ownerKind string, ownerID int64, publicOnly bool) (int, error) {
412 q := `SELECT COUNT(*) FROM repos WHERE owner_kind = ? AND owner_id = ?`
413 if publicOnly {
414 q += ` AND visibility = 'public'`
415 }
416 var n int
417 err := s.db.QueryRowContext(ctx, q, ownerKind, ownerID).Scan(&n)
418 return n, err
419}
420
421// ReposByGroup geeft de repositories van een groep.
422func (s *Store) ReposByGroup(ctx context.Context, groupID int64) ([]Repo, error) {
423 rows, err := s.db.QueryContext(ctx, repoSelect+` WHERE r.owner_kind = 'group' AND r.owner_id = ? ORDER BY `+pushOrder, groupID)
424 if err != nil {
425 return nil, err
426 }
427 defer rows.Close()
428 return scanRepos(rows)
429}
430
431// ReposByIDs laadt een lijst.
432func (s *Store) ReposByIDs(ctx context.Context, ids []int64) ([]Repo, error) {
433 var out []Repo
434 for _, id := range ids {
435 r, err := s.RepoByID(ctx, id)
436 if err != nil {
437 return nil, err
438 }
439 out = append(out, r)
440 }
441 return out, nil
442}
443
444func scanRepos(rows *sql.Rows) ([]Repo, error) {
445 var out []Repo
446 for rows.Next() {
447 var r Repo
448 var created, pushed string
449 var owner sql.NullString
450 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 {
451 return nil, err
452 }
453 r.OwnerPath = owner.String
454 r.CreatedAt = parseTime(created)
455 if pushed != "" {
456 r.PushedAt = parseTime(pushed)
457 }
458 if pushed != "" {
459 r.PushedAt = parseTime(pushed)
460 }
461 out = append(out, r)
462 }
463 return out, rows.Err()
464}
465
466// AllRepos is voor het verversen van hooks bij het starten.
467func (s *Store) AllRepos(ctx context.Context) ([]Repo, error) {
468 rows, err := s.db.QueryContext(ctx, repoSelect+` ORDER BY r.id`)
469 if err != nil {
470 return nil, err
471 }
472 defer rows.Close()
473 return scanRepos(rows)
474}
475
476// EffectiveRole past de rolregels toe op een repository.
477func (s *Store) EffectiveRole(ctx context.Context, userID, repoID int64) (access.Role, error) {
478 if userID == 0 {
479 return access.RoleNone, nil
480 }
481 if _, err := s.UserByID(ctx, userID); err != nil {
482 return access.RoleNone, err
483 }
484 repo, err := s.RepoByID(ctx, repoID)
485 if err != nil {
486 return access.RoleNone, err
487 }
488 in := access.Input{}
489 if repo.OwnerKind == "user" && repo.OwnerID == userID {
490 in.UserOwner = true
491 }
492 if repo.OwnerKind == "group" {
493 role, err := s.GroupRole(ctx, repo.OwnerID, userID)
494 if err != nil {
495 return access.RoleNone, err
496 }
497 in.GroupRole = role
498 }
499 var role string
500 err = s.db.QueryRowContext(ctx, `SELECT role FROM repo_members WHERE repo_id = ? AND user_id = ?`, repoID, userID).Scan(&role)
501 if err != nil && !errors.Is(err, sql.ErrNoRows) {
502 return access.RoleNone, err
503 }
504 if err == nil {
505 in.RepoRole = access.Role(role)
506 }
507 return access.Resolve(in), nil
508}
509
510// Member is een lid of een uitnodiging op gebruikersnaam.
511type Member struct {
512 UserID int64
513 Username string
514 AvatarURL string
515 Role access.Role
516 Pending bool
517}
518
519// SetMember zet een lidmaatschap. Een onbekende naam blijft wachten tot de eerste login.
520func (s *Store) SetMember(ctx context.Context, scopeKind string, scopeID int64, username string, role access.Role) error {
521 if scopeKind != "repo" && scopeKind != "group" {
522 return i18n.E("err.scope")
523 }
524 if _, err := access.ParseRole(string(role)); err != nil {
525 return err
526 }
527 username = strings.ToLower(strings.TrimSpace(username))
528 if err := names.ValidUsername(username); err != nil {
529 return err
530 }
531 if scopeKind == "group" && role != access.RoleMaintainer {
532 g, err := s.GroupByID(ctx, scopeID)
533 if err != nil {
534 return err
535 }
536 owner, err := s.UserByID(ctx, g.OwnerID)
537 if err == nil && owner.Username == username {
538 return i18n.E("err.ownerRole")
539 }
540 }
541 u, err := s.UserByUsername(ctx, username)
542 if IsNotFound(err) {
543 _, err = s.db.ExecContext(ctx, `INSERT INTO pending_members (scope_kind, scope_id, username, role) VALUES (?, ?, ?, ?)
544 ON CONFLICT(scope_kind, scope_id, username) DO UPDATE SET role = excluded.role`, scopeKind, scopeID, username, string(role))
545 return err
546 }
547 if err != nil {
548 return err
549 }
550 table, col := "repo_members", "repo_id"
551 if scopeKind == "group" {
552 table, col = "group_members", "group_id"
553 }
554 _, err = s.db.ExecContext(ctx, `INSERT INTO `+table+` (`+col+`, user_id, role) VALUES (?, ?, ?)
555 ON CONFLICT(`+col+`, user_id) DO UPDATE SET role = excluded.role`, scopeID, u.ID, string(role))
556 return err
557}
558
559// RemoveMember haalt een lid of een uitnodiging weg.
560func (s *Store) RemoveMember(ctx context.Context, scopeKind string, scopeID int64, username string) error {
561 username = strings.ToLower(strings.TrimSpace(username))
562 _, err := s.db.ExecContext(ctx, `DELETE FROM pending_members WHERE scope_kind = ? AND scope_id = ? AND username = ?`, scopeKind, scopeID, username)
563 if err != nil {
564 return err
565 }
566 u, err := s.UserByUsername(ctx, username)
567 if IsNotFound(err) {
568 return nil
569 }
570 if err != nil {
571 return err
572 }
573 if scopeKind == "group" {
574 g, err := s.GroupByID(ctx, scopeID)
575 if err != nil {
576 return err
577 }
578 if u.ID == g.OwnerID {
579 return i18n.E("err.ownerRole")
580 }
581 _, err = s.db.ExecContext(ctx, `DELETE FROM group_members WHERE group_id = ? AND user_id = ?`, scopeID, u.ID)
582 return err
583 }
584 _, err = s.db.ExecContext(ctx, `DELETE FROM repo_members WHERE repo_id = ? AND user_id = ?`, scopeID, u.ID)
585 return err
586}
587
588// ListMembers geeft leden van een repository of groep, plus open uitnodigingen.
589func (s *Store) ListMembers(ctx context.Context, scopeKind string, scopeID int64) ([]Member, error) {
590 var q string
591 if scopeKind == "group" {
592 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`
593 } else {
594 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`
595 }
596 rows, err := s.db.QueryContext(ctx, q, scopeID)
597 if err != nil {
598 return nil, err
599 }
600 defer rows.Close()
601 var out []Member
602 for rows.Next() {
603 var m Member
604 var role string
605 if err := rows.Scan(&m.UserID, &m.Username, &m.AvatarURL, &role); err != nil {
606 return nil, err
607 }
608 m.Role = access.Role(role)
609 out = append(out, m)
610 }
611 if err := rows.Err(); err != nil {
612 return nil, err
613 }
614 prows, err := s.db.QueryContext(ctx, `SELECT username, role FROM pending_members WHERE scope_kind = ? AND scope_id = ? ORDER BY username`, scopeKind, scopeID)
615 if err != nil {
616 return nil, err
617 }
618 defer prows.Close()
619 for prows.Next() {
620 var m Member
621 var role string
622 if err := prows.Scan(&m.Username, &role); err != nil {
623 return nil, err
624 }
625 m.Role = access.Role(role)
626 m.Pending = true
627 out = append(out, m)
628 }
629 return out, prows.Err()
630}
631
632// ProtectedPatterns geeft de beschermde branchpatronen.
633func (s *Store) ProtectedPatterns(ctx context.Context, repoID int64) ([]string, error) {
634 rows, err := s.db.QueryContext(ctx, `SELECT pattern FROM protected_branches WHERE repo_id = ? ORDER BY pattern`, repoID)
635 if err != nil {
636 return nil, err
637 }
638 defer rows.Close()
639 var out []string
640 for rows.Next() {
641 var p string
642 if err := rows.Scan(&p); err != nil {
643 return nil, err
644 }
645 out = append(out, p)
646 }
647 return out, rows.Err()
648}
649
650// AddProtected voegt een patroon toe.
651func (s *Store) AddProtected(ctx context.Context, repoID int64, pattern string) error {
652 pattern = strings.TrimSpace(pattern)
653 if pattern == "" || strings.Contains(pattern, " ") || strings.Contains(pattern, "..") {
654 return i18n.E("err.pattern", pattern)
655 }
656 _, err := s.db.ExecContext(ctx, `INSERT INTO protected_branches (repo_id, pattern) VALUES (?, ?)`, repoID, pattern)
657 if err != nil && strings.Contains(err.Error(), "UNIQUE") {
658 return nil
659 }
660 return err
661}
662
663// RemoveProtected haalt een patroon weg.
664func (s *Store) RemoveProtected(ctx context.Context, repoID int64, pattern string) error {
665 _, err := s.db.ExecContext(ctx, `DELETE FROM protected_branches WHERE repo_id = ? AND pattern = ?`, repoID, pattern)
666 return err
667}
668
669// ProtectedTagPatterns geeft de beschermde tagpatronen.
670func (s *Store) ProtectedTagPatterns(ctx context.Context, repoID int64) ([]string, error) {
671 rows, err := s.db.QueryContext(ctx, `SELECT pattern FROM protected_tags WHERE repo_id = ? ORDER BY pattern`, repoID)
672 if err != nil {
673 return nil, err
674 }
675 defer rows.Close()
676 var out []string
677 for rows.Next() {
678 var p string
679 if err := rows.Scan(&p); err != nil {
680 return nil, err
681 }
682 out = append(out, p)
683 }
684 return out, rows.Err()
685}
686
687// AddProtectedTag voegt een tagpatroon toe.
688func (s *Store) AddProtectedTag(ctx context.Context, repoID int64, pattern string) error {
689 pattern = strings.TrimSpace(pattern)
690 if pattern == "" || strings.Contains(pattern, " ") || strings.Contains(pattern, "..") {
691 return i18n.E("err.pattern", pattern)
692 }
693 _, err := s.db.ExecContext(ctx, `INSERT INTO protected_tags (repo_id, pattern) VALUES (?, ?)`, repoID, pattern)
694 if err != nil && strings.Contains(err.Error(), "UNIQUE") {
695 return nil
696 }
697 return err
698}
699
700// RemoveProtectedTag haalt een tagpatroon weg.
701func (s *Store) RemoveProtectedTag(ctx context.Context, repoID int64, pattern string) error {
702 _, err := s.db.ExecContext(ctx, `DELETE FROM protected_tags WHERE repo_id = ? AND pattern = ?`, repoID, pattern)
703 return err
704}
705
706// SecretMeta is een geheim zonder de waarde.
707type SecretMeta struct {
708 Name string
709 Protected bool
710 Invisible bool
711 // Expand: $NAAM en ${NAAM} in de waarde worden in de runner vervangen.
712 Expand bool
713 CreatedAt time.Time
714}
715
716// PutSecret bewaart een versleutelde waarde. De naam is een omgevingsvariabele.
717// Bij een bestaande naam blijven waarde en protected bijgewerkt; invisible wordt nooit gewist.
718func (s *Store) PutSecret(ctx context.Context, scopeKind string, scopeID int64, name, value string, protected bool) error {
719 if scopeKind != "repo" && scopeKind != "group" {
720 return i18n.E("err.scope")
721 }
722 if err := access.ValidSecretName(name); err != nil {
723 return err
724 }
725 if strings.TrimSpace(value) == "" {
726 return i18n.E("err.emptyValue")
727 }
728 nonce, ct, err := s.encrypt(value)
729 if err != nil {
730 return err
731 }
732 _, err = s.db.ExecContext(ctx, `INSERT INTO secrets (scope_kind, scope_id, name, ciphertext, nonce, protected, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)
733 ON CONFLICT(scope_kind, scope_id, name) DO UPDATE SET ciphertext = excluded.ciphertext, nonce = excluded.nonce, protected = excluded.protected`,
734 scopeKind, scopeID, name, ct, nonce, boolInt(protected), now())
735 return err
736}
737
738// DeleteSecret verwijdert een geheim.
739func (s *Store) DeleteSecret(ctx context.Context, scopeKind string, scopeID int64, name string) error {
740 res, err := s.db.ExecContext(ctx, `DELETE FROM secrets WHERE scope_kind = ? AND scope_id = ? AND name = ?`, scopeKind, scopeID, name)
741 if err != nil {
742 return err
743 }
744 n, _ := res.RowsAffected()
745 if n == 0 {
746 return errNotFound
747 }
748 return nil
749}
750
751// CreateSecret voegt een geheim toe. Een bestaande naam wordt niet overschreven.
752func (s *Store) CreateSecret(ctx context.Context, scopeKind string, scopeID int64, name, value string, protected, invisible bool) error {
753 nonce, ct, err := s.secretCipher(scopeKind, name, value)
754 if err != nil {
755 return err
756 }
757 _, err = s.db.ExecContext(ctx, `INSERT INTO secrets (scope_kind, scope_id, name, ciphertext, nonce, protected, invisible, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
758 scopeKind, scopeID, name, ct, nonce, boolInt(protected), boolInt(invisible), now())
759 if err != nil && strings.Contains(err.Error(), "UNIQUE") {
760 return i18n.E("err.secretExists", name)
761 }
762 return err
763}
764
765// UpdateSecret wijzigt waarde en protected van een zichtbaar geheim.
766func (s *Store) UpdateSecret(ctx context.Context, scopeKind string, scopeID int64, name, value string, protected bool) error {
767 return s.writeSecret(ctx, scopeKind, scopeID, name, value, protected, false)
768}
769
770// ReplaceSecret zet een nieuwe waarde op een onzichtbaar geheim. De vlag blijft aan.
771func (s *Store) ReplaceSecret(ctx context.Context, scopeKind string, scopeID int64, name, value string, protected bool) error {
772 return s.writeSecret(ctx, scopeKind, scopeID, name, value, protected, true)
773}
774
775func (s *Store) writeSecret(ctx context.Context, scopeKind string, scopeID int64, name, value string, protected, invisible bool) error {
776 nonce, ct, err := s.secretCipher(scopeKind, name, value)
777 if err != nil {
778 return err
779 }
780 res, err := s.db.ExecContext(ctx, `UPDATE secrets SET ciphertext = ?, nonce = ?, protected = ? WHERE scope_kind = ? AND scope_id = ? AND name = ? AND invisible = ?`,
781 ct, nonce, boolInt(protected), scopeKind, scopeID, name, boolInt(invisible))
782 if err != nil {
783 return err
784 }
785 n, _ := res.RowsAffected()
786 if n == 1 {
787 return nil
788 }
789 return s.secretMiss(ctx, scopeKind, scopeID, name, invisible)
790}
791
792func (s *Store) secretCipher(scopeKind, name, value string) (nonce, ct []byte, err error) {
793 if scopeKind != "repo" && scopeKind != "group" {
794 return nil, nil, i18n.E("err.scope")
795 }
796 if err := access.ValidSecretName(name); err != nil {
797 return nil, nil, err
798 }
799 if strings.TrimSpace(value) == "" {
800 return nil, nil, i18n.E("err.emptyValue")
801 }
802 return s.encrypt(value)
803}
804
805func (s *Store) secretMiss(ctx context.Context, scopeKind string, scopeID int64, name string, wantInvisible bool) error {
806 var inv int
807 err := s.db.QueryRowContext(ctx, `SELECT invisible FROM secrets WHERE scope_kind = ? AND scope_id = ? AND name = ?`, scopeKind, scopeID, name).Scan(&inv)
808 if errors.Is(err, sql.ErrNoRows) {
809 return errNotFound
810 }
811 if err != nil {
812 return err
813 }
814 if wantInvisible && inv == 0 {
815 return i18n.E("err.secretVisible", name)
816 }
817 if !wantInvisible && inv == 1 {
818 return i18n.E("err.secretHidden", name)
819 }
820 return errNotFound
821}
822
823// RevealSecret geeft de waarde van een zichtbaar geheim.
824func (s *Store) RevealSecret(ctx context.Context, scopeKind string, scopeID int64, name string) (string, error) {
825 if scopeKind != "repo" && scopeKind != "group" {
826 return "", i18n.E("err.scope")
827 }
828 var ct, nonce []byte
829 var inv int
830 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)
831 if errors.Is(err, sql.ErrNoRows) {
832 return "", errNotFound
833 }
834 if err != nil {
835 return "", err
836 }
837 if inv == 1 {
838 return "", i18n.E("err.secretHidden", name)
839 }
840 return s.decrypt(nonce, ct)
841}
842
843// ListSecrets geeft namen, niet de waarden.
844func (s *Store) ListSecrets(ctx context.Context, scopeKind string, scopeID int64) ([]SecretMeta, error) {
845 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)
846 if err != nil {
847 return nil, err
848 }
849 defer rows.Close()
850 var out []SecretMeta
851 for rows.Next() {
852 var m SecretMeta
853 var p, inv, exp int
854 var created string
855 if err := rows.Scan(&m.Name, &p, &inv, &exp, &created); err != nil {
856 return nil, err
857 }
858 m.Protected = p == 1
859 m.Invisible = inv == 1
860 m.Expand = exp == 1
861 m.CreatedAt = parseTime(created)
862 out = append(out, m)
863 }
864 return out, rows.Err()
865}
866
867// SecretValues ontcijfert geheimen voor een job of webhook.
868// refProtected bepaalt of beschermde geheimen meegaan.
869func (s *Store) SecretValues(ctx context.Context, scopeKind string, scopeID int64, refProtected bool) (map[string]string, error) {
870 rows, err := s.db.QueryContext(ctx, `SELECT name, ciphertext, nonce, protected FROM secrets WHERE scope_kind = ? AND scope_id = ?`, scopeKind, scopeID)
871 if err != nil {
872 return nil, err
873 }
874 defer rows.Close()
875 out := map[string]string{}
876 for rows.Next() {
877 var name string
878 var ct, nonce []byte
879 var p int
880 if err := rows.Scan(&name, &ct, &nonce, &p); err != nil {
881 return nil, err
882 }
883 if !access.InjectSecret(p == 1, refProtected) {
884 continue
885 }
886 val, err := s.decrypt(nonce, ct)
887 if err != nil {
888 return nil, err
889 }
890 out[name] = val
891 }
892 return out, rows.Err()
893}
894
895// TouchPushed zet het moment van de laatste push.
896func (s *Store) TouchPushed(ctx context.Context, repoID int64, at time.Time) error {
897 _, err := s.db.ExecContext(ctx, `UPDATE repos SET pushed_at = ? WHERE id = ? AND (pushed_at = '' OR pushed_at < ?)`,
898 at.UTC().Format(time.RFC3339), repoID, at.UTC().Format(time.RFC3339))
899 return err
900}
901
902// SortReposByPush sorteert zoals pushOrder: laatste push eerst, zonder push
903// onderaan, daarna op naam.
904func SortReposByPush(list []Repo) {
905 sort.SliceStable(list, func(i, j int) bool {
906 a, b := list[i], list[j]
907 if a.PushedAt.IsZero() != b.PushedAt.IsZero() {
908 return !a.PushedAt.IsZero()
909 }
910 if !a.PushedAt.Equal(b.PushedAt) {
911 return a.PushedAt.After(b.PushedAt)
912 }
913 if x, y := strings.ToLower(a.FullPath()), strings.ToLower(b.FullPath()); x != y {
914 return x < y
915 }
916 return a.ID < b.ID
917 })
918}
919
920// GroupPushTimes geeft per groep de laatste push in een van haar repos.
921// Groepen zonder push ontbreken in de map.
922func (s *Store) GroupPushTimes(ctx context.Context) (map[int64]time.Time, error) {
923 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`)
924 if err != nil {
925 return nil, err
926 }
927 defer rows.Close()
928 out := map[int64]time.Time{}
929 for rows.Next() {
930 var id int64
931 var at string
932 if err := rows.Scan(&id, &at); err != nil {
933 return nil, err
934 }
935 out[id] = parseTime(at)
936 }
937 return out, rows.Err()
938}
939
940// SortGroupsByPush: laatste push eerst, groepen zonder push onderaan, dan op naam.
941func SortGroupsByPush(list []Group, at map[int64]time.Time) {
942 sort.SliceStable(list, func(i, j int) bool {
943 a, b := at[list[i].ID], at[list[j].ID]
944 if a.IsZero() != b.IsZero() {
945 return !a.IsZero()
946 }
947 if !a.Equal(b) {
948 return a.After(b)
949 }
950 return strings.ToLower(list[i].Name) < strings.ToLower(list[j].Name)
951 })
952}
953
954// SetSecretExpand zet of de waarde variabelen uitbreidt.
955func (s *Store) SetSecretExpand(ctx context.Context, scopeKind string, scopeID int64, name string, on bool) error {
956 _, err := s.db.ExecContext(ctx, `UPDATE secrets SET expand = ? WHERE scope_kind = ? AND scope_id = ? AND name = ?`, boolInt(on), scopeKind, scopeID, name)
957 return err
958}
959
960// SecretExpandFlags geeft per geheimnaam of expand aan staat.
961func (s *Store) SecretExpandFlags(ctx context.Context, scopeKind string, scopeID int64) (map[string]bool, error) {
962 rows, err := s.db.QueryContext(ctx, `SELECT name, expand FROM secrets WHERE scope_kind = ? AND scope_id = ?`, scopeKind, scopeID)
963 if err != nil {
964 return nil, err
965 }
966 defer rows.Close()
967 out := map[string]bool{}
968 for rows.Next() {
969 var name string
970 var e int
971 if err := rows.Scan(&name, &e); err != nil {
972 return nil, err
973 }
974 out[name] = e == 1
975 }
976 return out, rows.Err()
977}
978
979// ErrGroupNotEmpty: een groep met repositories kan niet weg.
980type ErrGroupNotEmpty struct{ Repos int }
981
982func (e ErrGroupNotEmpty) Error() string {
983 return fmt.Sprintf("group still has %d repositories", e.Repos)
984}
985
986// DeleteGroup verwijdert een lege groep met leden, uitnodigingen, geheimen,
987// webhooks, goedkeuringsregels en groepsrunners. Een groep met repositories
988// geeft ErrGroupNotEmpty; er is geen force.
989func (s *Store) DeleteGroup(ctx context.Context, id int64) error {
990 tx, err := s.db.BeginTx(ctx, nil)
991 if err != nil {
992 return err
993 }
994 defer tx.Rollback()
995 var n int
996 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM repos WHERE owner_kind = 'group' AND owner_id = ?`, id).Scan(&n); err != nil {
997 return err
998 }
999 if n > 0 {
1000 return ErrGroupNotEmpty{Repos: n}
1001 }
1002 for _, q := range []string{
1003 `DELETE FROM group_members WHERE group_id = ?`,
1004 `DELETE FROM group_runner_optin WHERE group_id = ?`,
1005 `DELETE FROM pending_members WHERE scope_kind = 'group' AND scope_id = ?`,
1006 `DELETE FROM secrets WHERE scope_kind = 'group' AND scope_id = ?`,
1007 `DELETE FROM webhooks WHERE scope_kind = 'group' AND scope_id = ?`,
1008 `DELETE FROM approval_rules WHERE scope_kind = 'group' AND scope_id = ?`,
1009 `DELETE FROM runner_reg_tokens WHERE owner_kind = 'group' AND owner_id = ?`,
1010 `UPDATE runners SET revoked = 1 WHERE owner_kind = 'group' AND owner_id = ?`,
1011 `DELETE FROM groups WHERE id = ?`,
1012 } {
1013 if _, err := tx.ExecContext(ctx, q, id); err != nil {
1014 return err
1015 }
1016 }
1017 return tx.Commit()
1018}