| 1 | package setup |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 5 | "amadan.net/oficina/equipo/internal/wire/forgekey" |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "net/url" |
| 12 | "sort" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | |
| 16 | "gorm.io/gorm" |
| 17 | ) |
| 18 | |
| 19 | type ProjectGroup = kernel.ProjectGroup |
| 20 | |
| 21 | type ProjectDetail = kernel.ProjectDetail |
| 22 | |
| 23 | func (s *ProjectsStore) SaveAccount(ctx context.Context, actor Actor, account Account) (Account, error) { |
| 24 | account.Label = strings.TrimSpace(account.Label) |
| 25 | if account.Label == "" || account.ID < 0 || account.Revision < 0 || (account.ID == 0 && account.Revision != 0) { |
| 26 | return Account{}, s.Invalid |
| 27 | } |
| 28 | err := s.Write(ctx, func(tx *gorm.DB) error { |
| 29 | if err := s.Owner(tx, actor); err != nil { |
| 30 | return err |
| 31 | } |
| 32 | if replay, err := s.Replay(tx, ctx, &account); err != nil || replay { |
| 33 | return err |
| 34 | } |
| 35 | if account.ID == 0 { |
| 36 | account.Revision = 1 |
| 37 | if err := tx.Create(&account).Error; err != nil { |
| 38 | return s.accountWriteError(err) |
| 39 | } |
| 40 | } else { |
| 41 | var old Account |
| 42 | if err := tx.First(&old, account.ID).Error; err != nil { |
| 43 | return s.Error(err) |
| 44 | } |
| 45 | if old.Revision != account.Revision { |
| 46 | return s.Conflict |
| 47 | } |
| 48 | account.Revision++ |
| 49 | result := tx.Model(&Account{}).Where("id = ? AND revision = ?", account.ID, old.Revision).Select("Label", "Revision").Updates(&account) |
| 50 | if result.Error != nil { |
| 51 | return s.accountWriteError(result.Error) |
| 52 | } |
| 53 | if result.RowsAffected != 1 { |
| 54 | return s.Conflict |
| 55 | } |
| 56 | } |
| 57 | if err := s.Audit(tx, actor, "account.save", strconv.FormatInt(account.ID, 10)); err != nil { |
| 58 | return err |
| 59 | } |
| 60 | return s.SaveResult(tx, ctx, account) |
| 61 | }) |
| 62 | if err != nil { |
| 63 | return Account{}, err |
| 64 | } |
| 65 | return account, nil |
| 66 | } |
| 67 | |
| 68 | func (s *ProjectsStore) accountWriteError(err error) error { |
| 69 | if errors.Is(err, gorm.ErrDuplicatedKey) { |
| 70 | return s.AccountLabelExists |
| 71 | } |
| 72 | return s.Error(err) |
| 73 | } |
| 74 | |
| 75 | func bindingSegment(value string) bool { |
| 76 | if value == "" || value == "." || value == ".." { |
| 77 | return false |
| 78 | } |
| 79 | for _, c := range value { |
| 80 | if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.') { |
| 81 | return false |
| 82 | } |
| 83 | } |
| 84 | return true |
| 85 | } |
| 86 | |
| 87 | func CanonicalRepository(value string, invalid error) (string, error) { |
| 88 | value = strings.TrimSpace(value) |
| 89 | // Reject escapes before parsing so encoded separators cannot change the target. |
| 90 | if strings.ContainsAny(value, "%?#\\") { |
| 91 | return "", invalid |
| 92 | } |
| 93 | if !strings.HasPrefix(value, "https://") { |
| 94 | value = "https://" + value |
| 95 | } |
| 96 | u, err := url.Parse(value) |
| 97 | if err != nil || u.Scheme != "https" || u.Host != forgekey.Hub || u.User != nil || u.Opaque != "" { |
| 98 | return "", invalid |
| 99 | } |
| 100 | key, err := forgekey.Parse(u.Host + u.Path) |
| 101 | if err != nil || key.String() != u.Host+u.Path { |
| 102 | return "", invalid |
| 103 | } |
| 104 | return key.String(), nil |
| 105 | } |
| 106 | |
| 107 | // CanonicalBranch validates the short branch spelling used by saved projects |
| 108 | // and target refs. Callers must not expand it to refs/heads before comparison. |
| 109 | func CanonicalBranch(value string, invalid error) (string, error) { |
| 110 | if value == "" || value == "@" || value == "HEAD" || strings.HasPrefix(value, "-") || strings.HasPrefix(value, "refs/") || strings.Contains(value, "..") || strings.Contains(value, "@{") || strings.HasSuffix(value, ".") { |
| 111 | return "", invalid |
| 112 | } |
| 113 | for _, c := range value { |
| 114 | if c <= ' ' || c == 127 || strings.ContainsRune("~^:?*[\\", c) { |
| 115 | return "", invalid |
| 116 | } |
| 117 | } |
| 118 | for _, part := range strings.Split(value, "/") { |
| 119 | if part == "" || strings.HasPrefix(part, ".") || strings.HasSuffix(part, ".lock") { |
| 120 | return "", invalid |
| 121 | } |
| 122 | } |
| 123 | return value, nil |
| 124 | } |
| 125 | |
| 126 | func (s *ProjectsStore) prepareProject(project Project, owners []DecisionOwner) (Project, []DecisionOwner, error) { |
| 127 | if project.ID < 0 || project.AccountID <= 0 || project.Revision < 0 || (project.ID == 0 && project.Revision != 0) { |
| 128 | return Project{}, nil, s.Invalid |
| 129 | } |
| 130 | project.Name = strings.TrimSpace(project.Name) |
| 131 | project.AppName = strings.TrimSpace(project.AppName) |
| 132 | if project.Name == "" || (project.AppName != "" && !bindingSegment(project.AppName)) { |
| 133 | return Project{}, nil, s.Invalid |
| 134 | } |
| 135 | switch project.Kind { |
| 136 | case kernel.ProjectApp: |
| 137 | if project.AppName == "" { |
| 138 | return Project{}, nil, s.Invalid |
| 139 | } |
| 140 | case kernel.ProjectRepository: |
| 141 | if project.AppName != "" { |
| 142 | return Project{}, nil, s.Invalid |
| 143 | } |
| 144 | case kernel.ProjectWebsite: |
| 145 | default: |
| 146 | return Project{}, nil, s.Invalid |
| 147 | } |
| 148 | var err error |
| 149 | project.Repository, err = CanonicalRepository(project.Repository, s.Invalid) |
| 150 | if err != nil { |
| 151 | return Project{}, nil, err |
| 152 | } |
| 153 | project.DefaultBranch, err = CanonicalBranch(project.DefaultBranch, s.Invalid) |
| 154 | if err != nil { |
| 155 | return Project{}, nil, err |
| 156 | } |
| 157 | normalized := make([]DecisionOwner, 0, len(owners)) |
| 158 | seen := map[string]bool{} |
| 159 | for _, owner := range owners { |
| 160 | if owner.ProjectID != 0 && owner.ProjectID != project.ID { |
| 161 | return Project{}, nil, s.Invalid |
| 162 | } |
| 163 | switch owner.Decision { |
| 164 | case "work", "merge", "copy", "design", "product": |
| 165 | default: |
| 166 | return Project{}, nil, s.Invalid |
| 167 | } |
| 168 | if seen[owner.Decision] { |
| 169 | return Project{}, nil, s.Invalid |
| 170 | } |
| 171 | seen[owner.Decision] = true |
| 172 | owner.Address = s.Normalize(owner.Address) |
| 173 | if !s.ValidAddress(owner.Address) { |
| 174 | return Project{}, nil, s.Invalid |
| 175 | } |
| 176 | // The containing project determines the association, including on create. |
| 177 | owner.ProjectID = project.ID |
| 178 | normalized = append(normalized, owner) |
| 179 | } |
| 180 | if !seen["work"] || !seen["merge"] { |
| 181 | return Project{}, nil, s.Invalid |
| 182 | } |
| 183 | sort.Slice(normalized, func(i, j int) bool { return normalized[i].Decision < normalized[j].Decision }) |
| 184 | return project, normalized, nil |
| 185 | } |
| 186 | |
| 187 | func (s *ProjectsStore) SaveProject(ctx context.Context, actor Actor, project Project, owners []DecisionOwner, requestID string) (Project, error) { |
| 188 | if strings.TrimSpace(requestID) == "" || len(requestID) > 256 { |
| 189 | return Project{}, s.Invalid |
| 190 | } |
| 191 | project, owners, err := s.prepareProject(project, owners) |
| 192 | if err != nil { |
| 193 | return Project{}, err |
| 194 | } |
| 195 | input, err := json.Marshal(ProjectDetail{Project: project, Owners: owners}) |
| 196 | if err != nil { |
| 197 | return Project{}, s.Error(err) |
| 198 | } |
| 199 | digest := sha256.Sum256(input) |
| 200 | request := ProjectRequest{Actor: s.Normalize(actor.Address), Operation: "project.save", RequestID: requestID, InputHash: hex.EncodeToString(digest[:])} |
| 201 | err = s.Write(ctx, func(tx *gorm.DB) error { |
| 202 | if err := s.Owner(tx, actor); err != nil { |
| 203 | return err |
| 204 | } |
| 205 | var prior ProjectRequest |
| 206 | err := tx.Where("actor = ? AND operation = ? AND request_id = ?", request.Actor, request.Operation, request.RequestID).First(&prior).Error |
| 207 | if err == nil { |
| 208 | if prior.InputHash != request.InputHash { |
| 209 | return s.Conflict |
| 210 | } |
| 211 | return s.Error(json.Unmarshal([]byte(prior.Result), &project)) |
| 212 | } |
| 213 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 214 | return s.Error(err) |
| 215 | } |
| 216 | var account Account |
| 217 | if err := tx.First(&account, project.AccountID).Error; err != nil { |
| 218 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 219 | return s.Invalid |
| 220 | } |
| 221 | return s.Error(err) |
| 222 | } |
| 223 | for _, owner := range owners { |
| 224 | member, err := s.Member(tx, owner.Address) |
| 225 | if errors.Is(err, s.NotFound) { |
| 226 | return s.Invalid |
| 227 | } |
| 228 | if err != nil { |
| 229 | return err |
| 230 | } |
| 231 | if !member.Active { |
| 232 | return s.Invalid |
| 233 | } |
| 234 | } |
| 235 | var old Project |
| 236 | if project.ID != 0 { |
| 237 | if err := tx.First(&old, project.ID).Error; err != nil { |
| 238 | return s.Error(err) |
| 239 | } |
| 240 | if old.Revision != project.Revision { |
| 241 | return s.Conflict |
| 242 | } |
| 243 | } |
| 244 | var duplicates int64 |
| 245 | if err := tx.Model(&Project{}).Where("repository = ? AND app_name = ? AND id <> ?", project.Repository, project.AppName, project.ID).Count(&duplicates).Error; err != nil { |
| 246 | return s.Error(err) |
| 247 | } |
| 248 | if duplicates != 0 { |
| 249 | return s.BindingInUse |
| 250 | } |
| 251 | changed := old.ID == 0 || old.Repository != project.Repository || old.AppName != project.AppName || old.DefaultBranch != project.DefaultBranch || old.Kind != project.Kind |
| 252 | if old.ID != 0 { |
| 253 | var priorWork DecisionOwner |
| 254 | if err := tx.Where("project_id = ? AND decision = ?", old.ID, "work").First(&priorWork).Error; err != nil { |
| 255 | return s.Error(err) |
| 256 | } |
| 257 | for _, owner := range owners { |
| 258 | if owner.Decision == "work" && owner.Address != priorWork.Address { |
| 259 | changed = true |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | project.GrantVersion = old.GrantVersion |
| 264 | if changed { |
| 265 | project.GrantVersion++ |
| 266 | } |
| 267 | project.Revision++ |
| 268 | if project.ID == 0 { |
| 269 | if err := tx.Create(&project).Error; err != nil { |
| 270 | return s.Error(err) |
| 271 | } |
| 272 | } else { |
| 273 | result := tx.Model(&Project{}).Where("id = ? AND revision = ?", project.ID, old.Revision).Select("AccountID", "Name", "Repository", "AppName", "DefaultBranch", "Kind", "Revision", "GrantVersion").Updates(&project) |
| 274 | if result.Error != nil { |
| 275 | return s.Error(result.Error) |
| 276 | } |
| 277 | if result.RowsAffected != 1 { |
| 278 | return s.Conflict |
| 279 | } |
| 280 | } |
| 281 | if err := tx.Where("project_id = ?", project.ID).Delete(&DecisionOwner{}).Error; err != nil { |
| 282 | return s.Error(err) |
| 283 | } |
| 284 | for i := range owners { |
| 285 | owners[i].ProjectID = project.ID |
| 286 | } |
| 287 | if err := tx.Create(&owners).Error; err != nil { |
| 288 | return s.Error(err) |
| 289 | } |
| 290 | if changed { |
| 291 | if err := s.Fence(ctx, tx, project.ID); err != nil { |
| 292 | return err |
| 293 | } |
| 294 | } |
| 295 | if err := s.Audit(tx, actor, "project.save", strconv.FormatInt(project.ID, 10)); err != nil { |
| 296 | return err |
| 297 | } |
| 298 | result, err := json.Marshal(project) |
| 299 | if err != nil { |
| 300 | return s.Error(err) |
| 301 | } |
| 302 | request.Result = string(result) |
| 303 | return s.Error(tx.Create(&request).Error) |
| 304 | }) |
| 305 | if err != nil { |
| 306 | return Project{}, err |
| 307 | } |
| 308 | return project, nil |
| 309 | } |
| 310 | |
| 311 | // Projects reads shared metadata. HTTP callers must pass RequireMember first. |
| 312 | // One read transaction keeps groups and assignments in the same snapshot. |
| 313 | func (s *ProjectsStore) Projects(ctx context.Context) ([]ProjectGroup, error) { |
| 314 | if s == nil || s.Read == nil { |
| 315 | return nil, s.Unavailable |
| 316 | } |
| 317 | groups := []ProjectGroup{} |
| 318 | err := s.Read(ctx, func(tx *gorm.DB) error { |
| 319 | var accounts []Account |
| 320 | if err := tx.Order("label").Order("id").Find(&accounts).Error; err != nil { |
| 321 | return err |
| 322 | } |
| 323 | var projects []Project |
| 324 | if err := tx.Order("name").Order("id").Find(&projects).Error; err != nil { |
| 325 | return err |
| 326 | } |
| 327 | var owners []DecisionOwner |
| 328 | if err := tx.Order("decision").Find(&owners).Error; err != nil { |
| 329 | return err |
| 330 | } |
| 331 | byProject := map[int64][]DecisionOwner{} |
| 332 | for _, owner := range owners { |
| 333 | byProject[owner.ProjectID] = append(byProject[owner.ProjectID], owner) |
| 334 | } |
| 335 | byAccount := map[int64][]ProjectDetail{} |
| 336 | for _, project := range projects { |
| 337 | byAccount[project.AccountID] = append(byAccount[project.AccountID], ProjectDetail{Project: project, Owners: byProject[project.ID]}) |
| 338 | } |
| 339 | for _, account := range accounts { |
| 340 | groups = append(groups, ProjectGroup{Account: account, Projects: byAccount[account.ID]}) |
| 341 | } |
| 342 | return nil |
| 343 | }) |
| 344 | if err != nil { |
| 345 | return nil, s.Error(err) |
| 346 | } |
| 347 | return groups, nil |
| 348 | } |
| 349 | |
| 350 | // Project has the same authenticated-caller requirement as Projects. |
| 351 | func (s *ProjectsStore) Project(ctx context.Context, id int64) (ProjectDetail, error) { |
| 352 | if s == nil || s.Read == nil { |
| 353 | return ProjectDetail{}, s.Unavailable |
| 354 | } |
| 355 | if id <= 0 { |
| 356 | return ProjectDetail{}, s.NotFound |
| 357 | } |
| 358 | var detail ProjectDetail |
| 359 | err := s.Read(ctx, func(tx *gorm.DB) error { |
| 360 | if err := tx.First(&detail.Project, id).Error; err != nil { |
| 361 | return err |
| 362 | } |
| 363 | return tx.Where("project_id = ?", id).Order("decision").Find(&detail.Owners).Error |
| 364 | }) |
| 365 | if err != nil { |
| 366 | return ProjectDetail{}, s.Error(err) |
| 367 | } |
| 368 | return detail, nil |
| 369 | } |
| 370 | |
| 371 | type Account = kernel.Account |
| 372 | type Project = kernel.Project |
| 373 | type DecisionOwner = kernel.DecisionOwner |
| 374 | type ProjectRequest struct { |
| 375 | Actor string `gorm:"primaryKey"` |
| 376 | Operation string `gorm:"primaryKey"` |
| 377 | RequestID string `gorm:"primaryKey"` |
| 378 | InputHash string |
| 379 | Result string |
| 380 | } |
| 381 | |
| 382 | func (ProjectRequest) TableName() string { return "project_requests" } |
| 383 | |
| 384 | type ProjectsStore struct { |
| 385 | Write, Read func(context.Context, func(*gorm.DB) error) error |
| 386 | Owner func(*gorm.DB, Actor) error |
| 387 | Member func(*gorm.DB, string) (Member, error) |
| 388 | Audit func(*gorm.DB, Actor, string, string) error |
| 389 | Fence func(context.Context, *gorm.DB, int64) error |
| 390 | Normalize func(string) string |
| 391 | ValidAddress func(string) bool |
| 392 | Replay func(*gorm.DB, context.Context, any) (bool, error) |
| 393 | SaveResult func(*gorm.DB, context.Context, any) error |
| 394 | Error func(error) error |
| 395 | Invalid, NotFound, Conflict, Unavailable, BindingInUse, AccountLabelExists error |
| 396 | } |
| 397 | |