BlueGit

timfa bluegit

Files

bluegit / internal / store / repos.go

repos.go

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