BlueGit

timfa bluegit

Files

bluegit / internal / store / repos.go

repos.go

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