package forge import ( "amadan.net/oficina/equipo/internal/wire/forgekey" "bytes" "context" "encoding/json" "errors" "net/url" "os" "path/filepath" "reflect" "regexp" "strconv" "strings" "syscall" "time" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/runnerproto" ) type Authorization = runnerproto.PublicationAuthorization type Credential struct{ Remote, Agent, Bearer, GitPassword string } type Description struct { Repository, Ref, Agent, Body, Digest string At int64 AgentMetadata json.RawMessage Channels DescriptionChannels ContentHash string } // DescriptionTransport must confirm the stored body and its attributed agent. type DescriptionTransport interface { BeforePush() bool Set(context.Context, Credential, Description) error Read(context.Context, Credential, string, string) (Description, error) } type Config struct { Root, GitPath, Runner string Incarnation int64 Clock func() time.Time Authorize func(context.Context, team.Dispatch) (Authorization, error) Revalidate func(context.Context, Authorization) error Export func(context.Context, team.GitCandidate, string) error Credential func(context.Context, string) (Credential, error) Description DescriptionTransport } type Publisher struct { cfg Config localRemote func(string) string localReceivePack string beforePush func() } var _ team.Adapter = (*Publisher)(nil) var object = regexp.MustCompile(`^(?:[0-9a-f]{40}|[0-9a-f]{64})$`) func New(cfg Config) (*Publisher, error) { return newPublisher(cfg, nil) } func newPublisher(cfg Config, local func(string) string) (*Publisher, error) { if cfg.Authorize == nil || cfg.Revalidate == nil || cfg.Export == nil || cfg.Credential == nil || cfg.Description == nil || cfg.Clock == nil || cfg.Runner == "" || cfg.Incarnation <= 0 || !filepath.IsAbs(cfg.GitPath) || !filepath.IsAbs(cfg.Root) || filepath.Clean(cfg.Root) != cfg.Root { return nil, team.ErrInvalid } if err := os.MkdirAll(cfg.Root, 0700); err != nil { return nil, team.ErrUncertain } actual, err := filepath.EvalSymlinks(cfg.Root) if err != nil || actual != cfg.Root { return nil, team.ErrInvalid } info, err := os.Stat(cfg.Root) if err != nil || info.Mode().Perm()&0077 != 0 { return nil, team.ErrInvalid } if _, err := os.Lstat(filepath.Join(cfg.Root, ".git")); !os.IsNotExist(err) { return nil, team.ErrInvalid } return &Publisher{cfg: cfg, localRemote: local}, nil } func (*Publisher) Classify(op team.Operation) (team.ReplayClass, error) { if op != team.OpForgePublish { return "", team.ErrUnknownKind } return team.ReplayReconcilable, nil } func Digest(b []byte) string { return team.ContentDigest(b) } func Canonical(raw []byte) ([]byte, string, error) { return team.CanonicalJSON(raw) } func CanonicalHash(v any) string { raw, _ := json.Marshal(v); _, h, _ := Canonical(raw); return h } func validRef(ref string) bool { if ref == "" || ref == "HEAD" || ref == "@" || strings.HasPrefix(ref, "-") || strings.HasPrefix(ref, "refs/") || strings.ContainsAny(ref, " ~^:?*[\\\x00\r\n\t") || strings.Contains(ref, "..") || strings.Contains(ref, "@{") || strings.HasSuffix(ref, ".") { return false } for _, s := range strings.Split(ref, "/") { if s == "" || strings.HasPrefix(s, ".") || strings.HasSuffix(s, ".lock") { return false } for _, c := range s { if c < 32 || c == 127 { return false } } } return true } func validateDispatch(d team.Dispatch) error { b, h, err := Canonical(d.Payload) if err != nil || !bytes.Equal(b, d.Payload) || h != d.Hash || d.Action <= 0 || d.Key == "" || d.Operation != team.OpForgePublish { return team.ErrInvalid } return nil } func (p *Publisher) validate(a Authorization, d team.Dispatch) error { t := a.Ticket c := a.Candidate v := a.Publication target := a.Target now := p.cfg.Clock() if validateDispatch(d) != nil || !reflect.DeepEqual(t.Dispatch, d) || t.Scope.Account == "" || t.Scope.Job <= 0 || t.Handle.Runner != p.cfg.Runner || t.Handle.Attempt <= 0 || t.Handle.Fence <= 0 || t.Incarnation != p.cfg.Incarnation || !now.Before(t.ExpiresAt) || t.ExpiresAt.Sub(now) > 5*time.Second { return team.ErrFence } if target.Kind != team.TargetRepository || !validRepository(target.Repository) || !validRef(target.Ref) || !validRef(target.DefaultRef) || target.Ref == target.DefaultRef || v.Repository != target.Repository || v.Ref != target.Ref || c.Repository != target.Repository || c.BaseCommit != target.BaseRevision || v.Head != c.Commit || !object.MatchString(c.Commit) || !object.MatchString(c.Tree) || !object.MatchString(c.BaseCommit) || len(c.Commit) != len(c.Tree) || len(c.Commit) != len(c.BaseCommit) || v.CandidateHash != CanonicalHash(c) { return team.ErrEvidence } var saved team.Publication dec := json.NewDecoder(bytes.NewReader(d.Payload)) dec.DisallowUnknownFields() if dec.Decode(&saved) != nil || !reflect.DeepEqual(saved, v) || v.Description == "" || v.DescriptionHash != Digest([]byte(v.Description)) { return team.ErrEvidence } iso := v.Isolation if len(iso.ProfileApprovals) > 0 { var description team.PublicationDescription if json.Unmarshal([]byte(v.Description), &description) != nil || description.Version != 1 || !reflect.DeepEqual(description.Isolation.ProfileApprovals, iso.ProfileApprovals) { return team.ErrEvidence } } if !iso.Valid() || (iso.Trial != nil && !strings.Contains(v.Description, "supervised trial")) || ((iso.RunnerTainted || iso.Status == "unconfined") && !strings.Contains(v.Description, "unconfined")) { return team.ErrEvidence } return nil } func (p *Publisher) credential(ctx context.Context, repository string) (Credential, error) { c, err := p.cfg.Credential(ctx, repository) if err != nil { return Credential{}, team.ErrUncertain } u, e := url.Parse(c.Remote) if e != nil || !team.ValidPublicationAgent(c.Agent) || c.Bearer == "" || strings.ContainsAny(c.Bearer+c.GitPassword+c.Remote, "\r\n\x00") || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.RawPath != "" || c.Remote != "https://"+repository || u.String() != c.Remote { return Credential{}, team.ErrInvalid } if c.GitPassword == "" { return Credential{}, workspace.ErrGitPassword } return c, nil } type record struct { Authorization Authorization Description Description Remote string DescriptionAttempted bool // An empty phase is a legacy journal and cannot prove no dispatch. Phase string } func (p *Publisher) path(d team.Dispatch) string { return filepath.Join(p.cfg.Root, "publish-"+strconv.FormatInt(int64(d.Action), 10)+".json") } func (p *Publisher) lock(d team.Dispatch) (func(), error) { f, e := os.OpenFile(p.path(d)+".lock", os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600) if e != nil { return nil, team.ErrUncertain } if syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) != nil { f.Close() return nil, team.ErrUncertain } return func() { _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN); _ = f.Close() }, nil } func (p *Publisher) load(d team.Dispatch) (record, error) { var r record b, e := os.ReadFile(p.path(d)) if e != nil { return r, e } if json.Unmarshal(b, &r) != nil || !reflect.DeepEqual(r.Authorization.Ticket.Dispatch, d) { return r, team.ErrConflict } return r, nil } func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (receipt team.Receipt, resultErr error) { if validateDispatch(d) != nil { return team.Receipt{}, team.ErrInvalid } unlock, e := p.lock(d) if e != nil { return team.Receipt{}, e } defer unlock() if r, err := p.load(d); err == nil { return p.reconcile(ctx, r) } else if !os.IsNotExist(err) { return team.Receipt{}, err } // Only a fresh action under its lock can prove a preparation failure. mayPublish := false defer func() { if resultErr != nil && !mayPublish && !errors.Is(resultErr, team.ErrConflict) { resultErr = team.ErrNotDispatched } else if resultErr != nil && mayPublish && !errors.Is(resultErr, team.ErrConflict) { resultErr = team.ErrUncertain } }() a, e := p.cfg.Authorize(ctx, d) if e != nil { return team.Receipt{}, e } if e = p.validate(a, d); e != nil { return team.Receipt{}, e } if e = p.cfg.Revalidate(ctx, a); e != nil { return team.Receipt{}, e } cred, e := p.credential(ctx, a.Publication.Repository) if e != nil { return team.Receipt{}, e } dir, e := os.MkdirTemp(p.cfg.Root, "objects-") if e != nil { return team.Receipt{}, team.ErrUncertain } defer os.RemoveAll(dir) repo, e := p.stage(ctx, dir, a.Candidate) if e != nil { return team.Receipt{}, e } if e = p.validate(a, d); e != nil { return team.Receipt{}, e } desc := Description{Repository: a.Publication.Repository, Ref: a.Publication.Ref, Agent: cred.Agent, Body: a.Publication.Description, Digest: a.Publication.DescriptionHash} r := record{Authorization: a, Description: desc, Remote: cred.Remote, Phase: "prepared"} if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { return team.Receipt{}, team.ErrUncertain } head, err := p.remoteHead(ctx, cred, a.Publication.Ref) if err != nil { return team.Receipt{}, err } if head != "" && head != a.Candidate.Commit { return team.Receipt{}, team.ErrConflict } ready := func() error { if err := ctx.Err(); err != nil { return err } if err := p.verifyObjects(ctx, repo, a.Candidate); err != nil { return err } if err := p.validate(a, d); err != nil { return err } return p.cfg.Revalidate(ctx, a) } if e = ready(); e != nil { return team.Receipt{}, e } if head == a.Candidate.Commit { r.Phase = "observed" if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { return team.Receipt{}, e } mayPublish = true return p.reconcile(ctx, r) } if p.cfg.Description.BeforePush() { r.Phase = "description_started" if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { return team.Receipt{}, e } mayPublish = true if e = p.confirmDescription(ctx, cred, &r); e != nil { return team.Receipt{}, team.ErrUncertain } } if e = ready(); e != nil { return team.Receipt{}, e } r.Phase = "push_started" if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { return team.Receipt{}, e } mayPublish = true if p.beforePush != nil { p.beforePush() } _, e = p.git(ctx, repo, &cred, "push", "--porcelain", "--no-verify", "--recurse-submodules=no", "--force-with-lease=refs/heads/"+a.Publication.Ref+":", "--", p.remote(cred.Remote), a.Candidate.Commit+":refs/heads/"+a.Publication.Ref) if e != nil { return team.Receipt{}, team.ErrUncertain } return p.reconcile(ctx, r) } func (p *Publisher) remote(remote string) string { if p.localRemote != nil { return p.localRemote(remote) } return remote } func descriptionMatches(got, want Description) bool { return got.Repository == want.Repository && got.Ref == want.Ref && got.Agent == want.Agent && got.Body == want.Body && got.Digest == want.Digest } func (p *Publisher) confirmDescription(ctx context.Context, cred Credential, r *record) error { desc := r.Description got, e := p.cfg.Description.Read(ctx, cred, desc.Repository, desc.Ref) if e == nil && descriptionMatches(got, desc) { return nil } // Once a write may have run, reconciliation only reads. A transport failure // also cannot prove that the existing description needs changing. if r.DescriptionAttempted || (e != nil && !errors.Is(e, team.ErrEvidence)) { return team.ErrUncertain } r.DescriptionAttempted = true if e = runnerproto.JournalCredentials(p.path(r.Authorization.Ticket.Dispatch), *r); e != nil { return team.ErrUncertain } // A failed command may have stored the description before losing its reply. if e = p.cfg.Description.Set(ctx, cred, desc); errors.Is(e, team.ErrNotDispatched) { // Only a proven pre-start failure permits a later write. Persist that // proof; a crash before this journal update keeps the conservative latch. r.DescriptionAttempted = false if e = runnerproto.JournalCredentials(p.path(r.Authorization.Ticket.Dispatch), *r); e != nil { r.DescriptionAttempted = true } return team.ErrUncertain } got, e = p.cfg.Description.Read(ctx, cred, desc.Repository, desc.Ref) if e != nil || !descriptionMatches(got, desc) { return team.ErrUncertain } return nil } func (p *Publisher) reconcile(ctx context.Context, r record) (team.Receipt, error) { if r.Phase == "prepared" || r.Phase == "not_dispatched" { return team.Receipt{}, team.ErrNotDispatched } if r.Phase != "" && r.Phase != "push_started" && r.Phase != "observed" { return team.Receipt{}, team.ErrUncertain } v := r.Authorization.Publication cred, e := p.credential(ctx, v.Repository) if e != nil { return team.Receipt{}, e } if cred.Agent != r.Description.Agent || cred.Remote != r.Remote || r.Description.Body != v.Description || r.Description.Digest != v.DescriptionHash { return team.Receipt{}, team.ErrConflict } ref := "refs/heads/" + v.Ref head, e := p.remoteHead(ctx, cred, v.Ref) if e != nil || head == "" { return team.Receipt{}, team.ErrUncertain } if head != v.Head { return team.Receipt{}, team.ErrConflict } if e = p.confirmDescription(ctx, cred, &r); e != nil { return team.Receipt{}, e } label := v.Isolation.Status if v.Isolation.RunnerTainted { label = "unconfined" } return team.Receipt{ID: "forge-" + Digest([]byte(r.Authorization.Ticket.Dispatch.Hash+"/"+v.DescriptionHash+"/"+cred.Agent)), Outcome: team.OutcomeSuccess, Provider: "amadan", Usage: &team.Usage{Calls: 1}, Fields: map[string]string{"label": label, "repository": v.Repository, "ref": v.Ref, "qualified_ref": ref, "head": v.Head, "candidate_hash": v.CandidateHash, "description_hash": v.DescriptionHash, "agent": cred.Agent, "isolation": v.Isolation.Status, "runner_tainted": strconv.FormatBool(v.Isolation.RunnerTainted)}}, nil } func (p *Publisher) Reconcile(ctx context.Context, d team.Dispatch) (team.ReconcileResult, error) { if validateDispatch(d) != nil { return team.ReconcileResult{}, team.ErrInvalid } unlock, e := p.lock(d) if e != nil { return team.ReconcileResult{}, e } defer unlock() r, e := p.load(d) if os.IsNotExist(e) { if err := runnerproto.JournalCredentials(p.path(d), record{Phase: "not_dispatched", Authorization: Authorization{Ticket: team.AdmissionTicket{Dispatch: d}}}); err != nil { return team.ReconcileResult{}, team.ErrUncertain } return team.ReconcileResult{}, team.ErrNotDispatched } if e != nil { return team.ReconcileResult{}, team.ErrUncertain } receipt, e := p.reconcile(ctx, r) if e != nil { return team.ReconcileResult{}, e } return team.ReconcileResult{Receipt: &receipt, Definitive: true}, nil } func (p *Publisher) remoteHead(ctx context.Context, cred Credential, branch string) (string, error) { ref := "refs/heads/" + branch out, err := p.git(ctx, p.cfg.Root, &cred, "ls-remote", "--refs", "--", p.remote(cred.Remote), ref) if err != nil { return "", team.ErrUncertain } fields := strings.Fields(out) if len(fields) == 0 { return "", nil } if len(fields) != 2 || !object.MatchString(fields[0]) || fields[1] != ref { return "", team.ErrUncertain } return fields[0], nil } func validRepository(repository string) bool { if !forgekey.ValidHub(repository) { return false } for _, part := range strings.Split(repository, "/")[1:] { if part == "." || part == ".." { return false } } return true }