| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "strconv" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 10 | "gorm.io/gorm" |
| 11 | ) |
| 12 | |
| 13 | // ProjectSource is the instance-observed public project material supplied to |
| 14 | // research. Its digest covers only the explicit projection returned here. |
| 15 | type ProjectSource struct { |
| 16 | ID, Revision int64 |
| 17 | Name, Repository, AppName, DefaultBranch string |
| 18 | } |
| 19 | |
| 20 | func projectSourceAt(tx *gorm.DB, id int64) (ProjectSource, team.SourceRef, error) { |
| 21 | var p Project |
| 22 | if err := tx.First(&p, id).Error; err != nil { |
| 23 | return ProjectSource{}, team.SourceRef{}, storeError(err) |
| 24 | } |
| 25 | v := ProjectSource{p.ID, p.Revision, p.Name, p.Repository, p.AppName, p.DefaultBranch} |
| 26 | b, err := json.Marshal(v) |
| 27 | if err != nil { |
| 28 | return v, team.SourceRef{}, err |
| 29 | } |
| 30 | return v, team.SourceRef{Kind: "project", ID: strconv.FormatInt(p.ID, 10), Revision: p.Revision, Hash: team.ContentDigest(b)}, nil |
| 31 | } |
| 32 | func (s *Store) ReadProjectSource(ctx context.Context, actor Actor, id int64) (ProjectSource, team.SourceRef, error) { |
| 33 | var v ProjectSource |
| 34 | var ref team.SourceRef |
| 35 | err := s.write(ctx, func(tx *gorm.DB) error { |
| 36 | if _, err := currentRunnerMember(tx, normalizeAddress(actor.Address)); err != nil { |
| 37 | return err |
| 38 | } |
| 39 | var err error |
| 40 | v, ref, err = projectSourceAt(tx, id) |
| 41 | return err |
| 42 | }) |
| 43 | return v, ref, err |
| 44 | } |
| 45 | func (s *Store) validateSourceReference(ctx context.Context, raw *sql.Tx, scope team.Scope, ref team.SourceRef) error { |
| 46 | if s.execution == nil || ref.Kind != "project" { |
| 47 | return ErrForbidden |
| 48 | } |
| 49 | var project int64 |
| 50 | if err := raw.QueryRowContext(ctx, "SELECT project_id FROM jobs WHERE id=? AND account=?", scope.Job, scope.Account).Scan(&project); err != nil { |
| 51 | return err |
| 52 | } |
| 53 | if ref.ID != strconv.FormatInt(project, 10) { |
| 54 | return ErrForbidden |
| 55 | } |
| 56 | _, observed, err := projectSourceAt(s.execution.gormTx(ctx, raw), project) |
| 57 | if err != nil { |
| 58 | return err |
| 59 | } |
| 60 | if ref != observed { |
| 61 | return ErrConflict |
| 62 | } |
| 63 | return nil |
| 64 | } |
| 65 | |