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