| 1 | package forge |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/wire/forgekey" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "net/url" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "reflect" |
| 13 | "regexp" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | "syscall" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 20 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 21 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 22 | ) |
| 23 | |
| 24 | type Authorization = runnerproto.PublicationAuthorization |
| 25 | |
| 26 | type Credential struct{ Remote, Agent, Bearer, GitPassword string } |
| 27 | type Description struct { |
| 28 | Repository, Ref, Agent, Body, Digest string |
| 29 | At int64 |
| 30 | AgentMetadata json.RawMessage |
| 31 | Channels DescriptionChannels |
| 32 | ContentHash string |
| 33 | } |
| 34 | |
| 35 | // DescriptionTransport must confirm the stored body and its attributed agent. |
| 36 | type DescriptionTransport interface { |
| 37 | BeforePush() bool |
| 38 | Set(context.Context, Credential, Description) error |
| 39 | Read(context.Context, Credential, string, string) (Description, error) |
| 40 | } |
| 41 | type Config struct { |
| 42 | Root, GitPath, Runner string |
| 43 | Incarnation int64 |
| 44 | Clock func() time.Time |
| 45 | Authorize func(context.Context, team.Dispatch) (Authorization, error) |
| 46 | Revalidate func(context.Context, Authorization) error |
| 47 | Export func(context.Context, team.GitCandidate, string) error |
| 48 | Credential func(context.Context, string) (Credential, error) |
| 49 | Description DescriptionTransport |
| 50 | } |
| 51 | type Publisher struct { |
| 52 | cfg Config |
| 53 | localRemote func(string) string |
| 54 | localReceivePack string |
| 55 | beforePush func() |
| 56 | } |
| 57 | |
| 58 | var _ team.Adapter = (*Publisher)(nil) |
| 59 | var object = regexp.MustCompile(`^(?:[0-9a-f]{40}|[0-9a-f]{64})$`) |
| 60 | |
| 61 | func New(cfg Config) (*Publisher, error) { return newPublisher(cfg, nil) } |
| 62 | func newPublisher(cfg Config, local func(string) string) (*Publisher, error) { |
| 63 | 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 { |
| 64 | return nil, team.ErrInvalid |
| 65 | } |
| 66 | if err := os.MkdirAll(cfg.Root, 0700); err != nil { |
| 67 | return nil, team.ErrUncertain |
| 68 | } |
| 69 | actual, err := filepath.EvalSymlinks(cfg.Root) |
| 70 | if err != nil || actual != cfg.Root { |
| 71 | return nil, team.ErrInvalid |
| 72 | } |
| 73 | info, err := os.Stat(cfg.Root) |
| 74 | if err != nil || info.Mode().Perm()&0077 != 0 { |
| 75 | return nil, team.ErrInvalid |
| 76 | } |
| 77 | if _, err := os.Lstat(filepath.Join(cfg.Root, ".git")); !os.IsNotExist(err) { |
| 78 | return nil, team.ErrInvalid |
| 79 | } |
| 80 | return &Publisher{cfg: cfg, localRemote: local}, nil |
| 81 | } |
| 82 | func (*Publisher) Classify(op team.Operation) (team.ReplayClass, error) { |
| 83 | if op != team.OpForgePublish { |
| 84 | return "", team.ErrUnknownKind |
| 85 | } |
| 86 | return team.ReplayReconcilable, nil |
| 87 | } |
| 88 | func Digest(b []byte) string { return team.ContentDigest(b) } |
| 89 | func Canonical(raw []byte) ([]byte, string, error) { return team.CanonicalJSON(raw) } |
| 90 | func CanonicalHash(v any) string { raw, _ := json.Marshal(v); _, h, _ := Canonical(raw); return h } |
| 91 | func validRef(ref string) bool { |
| 92 | 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, ".") { |
| 93 | return false |
| 94 | } |
| 95 | for _, s := range strings.Split(ref, "/") { |
| 96 | if s == "" || strings.HasPrefix(s, ".") || strings.HasSuffix(s, ".lock") { |
| 97 | return false |
| 98 | } |
| 99 | for _, c := range s { |
| 100 | if c < 32 || c == 127 { |
| 101 | return false |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | return true |
| 106 | } |
| 107 | func validateDispatch(d team.Dispatch) error { |
| 108 | b, h, err := Canonical(d.Payload) |
| 109 | if err != nil || !bytes.Equal(b, d.Payload) || h != d.Hash || d.Action <= 0 || d.Key == "" || d.Operation != team.OpForgePublish { |
| 110 | return team.ErrInvalid |
| 111 | } |
| 112 | return nil |
| 113 | } |
| 114 | func (p *Publisher) validate(a Authorization, d team.Dispatch) error { |
| 115 | t := a.Ticket |
| 116 | c := a.Candidate |
| 117 | v := a.Publication |
| 118 | target := a.Target |
| 119 | now := p.cfg.Clock() |
| 120 | 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 { |
| 121 | return team.ErrFence |
| 122 | } |
| 123 | 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) { |
| 124 | return team.ErrEvidence |
| 125 | } |
| 126 | var saved team.Publication |
| 127 | dec := json.NewDecoder(bytes.NewReader(d.Payload)) |
| 128 | dec.DisallowUnknownFields() |
| 129 | if dec.Decode(&saved) != nil || !reflect.DeepEqual(saved, v) || v.Description == "" || v.DescriptionHash != Digest([]byte(v.Description)) { |
| 130 | return team.ErrEvidence |
| 131 | } |
| 132 | iso := v.Isolation |
| 133 | if len(iso.ProfileApprovals) > 0 { |
| 134 | var description team.PublicationDescription |
| 135 | if json.Unmarshal([]byte(v.Description), &description) != nil || description.Version != 1 || !reflect.DeepEqual(description.Isolation.ProfileApprovals, iso.ProfileApprovals) { |
| 136 | return team.ErrEvidence |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | if !iso.Valid() || (iso.Trial != nil && !strings.Contains(v.Description, "supervised trial")) || ((iso.RunnerTainted || iso.Status == "unconfined") && !strings.Contains(v.Description, "unconfined")) { |
| 141 | return team.ErrEvidence |
| 142 | } |
| 143 | return nil |
| 144 | } |
| 145 | func (p *Publisher) credential(ctx context.Context, repository string) (Credential, error) { |
| 146 | c, err := p.cfg.Credential(ctx, repository) |
| 147 | if err != nil { |
| 148 | return Credential{}, team.ErrUncertain |
| 149 | } |
| 150 | u, e := url.Parse(c.Remote) |
| 151 | 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 { |
| 152 | return Credential{}, team.ErrInvalid |
| 153 | } |
| 154 | if c.GitPassword == "" { |
| 155 | return Credential{}, workspace.ErrGitPassword |
| 156 | } |
| 157 | return c, nil |
| 158 | } |
| 159 | |
| 160 | type record struct { |
| 161 | Authorization Authorization |
| 162 | Description Description |
| 163 | Remote string |
| 164 | DescriptionAttempted bool |
| 165 | // An empty phase is a legacy journal and cannot prove no dispatch. |
| 166 | Phase string |
| 167 | } |
| 168 | |
| 169 | func (p *Publisher) path(d team.Dispatch) string { |
| 170 | return filepath.Join(p.cfg.Root, "publish-"+strconv.FormatInt(int64(d.Action), 10)+".json") |
| 171 | } |
| 172 | func (p *Publisher) lock(d team.Dispatch) (func(), error) { |
| 173 | f, e := os.OpenFile(p.path(d)+".lock", os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600) |
| 174 | if e != nil { |
| 175 | return nil, team.ErrUncertain |
| 176 | } |
| 177 | if syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) != nil { |
| 178 | f.Close() |
| 179 | return nil, team.ErrUncertain |
| 180 | } |
| 181 | return func() { _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN); _ = f.Close() }, nil |
| 182 | } |
| 183 | func (p *Publisher) load(d team.Dispatch) (record, error) { |
| 184 | var r record |
| 185 | b, e := os.ReadFile(p.path(d)) |
| 186 | if e != nil { |
| 187 | return r, e |
| 188 | } |
| 189 | if json.Unmarshal(b, &r) != nil || !reflect.DeepEqual(r.Authorization.Ticket.Dispatch, d) { |
| 190 | return r, team.ErrConflict |
| 191 | } |
| 192 | return r, nil |
| 193 | } |
| 194 | func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (receipt team.Receipt, resultErr error) { |
| 195 | if validateDispatch(d) != nil { |
| 196 | return team.Receipt{}, team.ErrInvalid |
| 197 | } |
| 198 | unlock, e := p.lock(d) |
| 199 | if e != nil { |
| 200 | return team.Receipt{}, e |
| 201 | } |
| 202 | defer unlock() |
| 203 | if r, err := p.load(d); err == nil { |
| 204 | return p.reconcile(ctx, r) |
| 205 | } else if !os.IsNotExist(err) { |
| 206 | return team.Receipt{}, err |
| 207 | } |
| 208 | // Only a fresh action under its lock can prove a preparation failure. |
| 209 | mayPublish := false |
| 210 | defer func() { |
| 211 | if resultErr != nil && !mayPublish && !errors.Is(resultErr, team.ErrConflict) { |
| 212 | resultErr = team.ErrNotDispatched |
| 213 | } else if resultErr != nil && mayPublish && !errors.Is(resultErr, team.ErrConflict) { |
| 214 | resultErr = team.ErrUncertain |
| 215 | } |
| 216 | }() |
| 217 | a, e := p.cfg.Authorize(ctx, d) |
| 218 | if e != nil { |
| 219 | return team.Receipt{}, e |
| 220 | } |
| 221 | if e = p.validate(a, d); e != nil { |
| 222 | return team.Receipt{}, e |
| 223 | } |
| 224 | if e = p.cfg.Revalidate(ctx, a); e != nil { |
| 225 | return team.Receipt{}, e |
| 226 | } |
| 227 | cred, e := p.credential(ctx, a.Publication.Repository) |
| 228 | if e != nil { |
| 229 | return team.Receipt{}, e |
| 230 | } |
| 231 | dir, e := os.MkdirTemp(p.cfg.Root, "objects-") |
| 232 | if e != nil { |
| 233 | return team.Receipt{}, team.ErrUncertain |
| 234 | } |
| 235 | defer os.RemoveAll(dir) |
| 236 | repo, e := p.stage(ctx, dir, a.Candidate) |
| 237 | if e != nil { |
| 238 | return team.Receipt{}, e |
| 239 | } |
| 240 | if e = p.validate(a, d); e != nil { |
| 241 | return team.Receipt{}, e |
| 242 | } |
| 243 | desc := Description{Repository: a.Publication.Repository, Ref: a.Publication.Ref, Agent: cred.Agent, Body: a.Publication.Description, Digest: a.Publication.DescriptionHash} |
| 244 | r := record{Authorization: a, Description: desc, Remote: cred.Remote, Phase: "prepared"} |
| 245 | if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { |
| 246 | return team.Receipt{}, team.ErrUncertain |
| 247 | } |
| 248 | head, err := p.remoteHead(ctx, cred, a.Publication.Ref) |
| 249 | if err != nil { |
| 250 | return team.Receipt{}, err |
| 251 | } |
| 252 | if head != "" && head != a.Candidate.Commit { |
| 253 | return team.Receipt{}, team.ErrConflict |
| 254 | } |
| 255 | ready := func() error { |
| 256 | if err := ctx.Err(); err != nil { |
| 257 | return err |
| 258 | } |
| 259 | if err := p.verifyObjects(ctx, repo, a.Candidate); err != nil { |
| 260 | return err |
| 261 | } |
| 262 | if err := p.validate(a, d); err != nil { |
| 263 | return err |
| 264 | } |
| 265 | return p.cfg.Revalidate(ctx, a) |
| 266 | } |
| 267 | if e = ready(); e != nil { |
| 268 | return team.Receipt{}, e |
| 269 | } |
| 270 | if head == a.Candidate.Commit { |
| 271 | r.Phase = "observed" |
| 272 | if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { |
| 273 | return team.Receipt{}, e |
| 274 | } |
| 275 | mayPublish = true |
| 276 | return p.reconcile(ctx, r) |
| 277 | } |
| 278 | if p.cfg.Description.BeforePush() { |
| 279 | r.Phase = "description_started" |
| 280 | if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { |
| 281 | return team.Receipt{}, e |
| 282 | } |
| 283 | mayPublish = true |
| 284 | if e = p.confirmDescription(ctx, cred, &r); e != nil { |
| 285 | return team.Receipt{}, team.ErrUncertain |
| 286 | } |
| 287 | } |
| 288 | if e = ready(); e != nil { |
| 289 | return team.Receipt{}, e |
| 290 | } |
| 291 | r.Phase = "push_started" |
| 292 | if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { |
| 293 | return team.Receipt{}, e |
| 294 | } |
| 295 | mayPublish = true |
| 296 | if p.beforePush != nil { |
| 297 | p.beforePush() |
| 298 | } |
| 299 | _, 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) |
| 300 | if e != nil { |
| 301 | return team.Receipt{}, team.ErrUncertain |
| 302 | } |
| 303 | return p.reconcile(ctx, r) |
| 304 | } |
| 305 | func (p *Publisher) remote(remote string) string { |
| 306 | if p.localRemote != nil { |
| 307 | return p.localRemote(remote) |
| 308 | } |
| 309 | return remote |
| 310 | } |
| 311 | func descriptionMatches(got, want Description) bool { |
| 312 | return got.Repository == want.Repository && got.Ref == want.Ref && got.Agent == want.Agent && got.Body == want.Body && got.Digest == want.Digest |
| 313 | } |
| 314 | |
| 315 | func (p *Publisher) confirmDescription(ctx context.Context, cred Credential, r *record) error { |
| 316 | desc := r.Description |
| 317 | got, e := p.cfg.Description.Read(ctx, cred, desc.Repository, desc.Ref) |
| 318 | if e == nil && descriptionMatches(got, desc) { |
| 319 | return nil |
| 320 | } |
| 321 | // Once a write may have run, reconciliation only reads. A transport failure |
| 322 | // also cannot prove that the existing description needs changing. |
| 323 | if r.DescriptionAttempted || (e != nil && !errors.Is(e, team.ErrEvidence)) { |
| 324 | return team.ErrUncertain |
| 325 | } |
| 326 | r.DescriptionAttempted = true |
| 327 | if e = runnerproto.JournalCredentials(p.path(r.Authorization.Ticket.Dispatch), *r); e != nil { |
| 328 | return team.ErrUncertain |
| 329 | } |
| 330 | // A failed command may have stored the description before losing its reply. |
| 331 | if e = p.cfg.Description.Set(ctx, cred, desc); errors.Is(e, team.ErrNotDispatched) { |
| 332 | // Only a proven pre-start failure permits a later write. Persist that |
| 333 | // proof; a crash before this journal update keeps the conservative latch. |
| 334 | r.DescriptionAttempted = false |
| 335 | if e = runnerproto.JournalCredentials(p.path(r.Authorization.Ticket.Dispatch), *r); e != nil { |
| 336 | r.DescriptionAttempted = true |
| 337 | } |
| 338 | return team.ErrUncertain |
| 339 | } |
| 340 | got, e = p.cfg.Description.Read(ctx, cred, desc.Repository, desc.Ref) |
| 341 | if e != nil || !descriptionMatches(got, desc) { |
| 342 | return team.ErrUncertain |
| 343 | } |
| 344 | return nil |
| 345 | } |
| 346 | func (p *Publisher) reconcile(ctx context.Context, r record) (team.Receipt, error) { |
| 347 | if r.Phase == "prepared" || r.Phase == "not_dispatched" { |
| 348 | return team.Receipt{}, team.ErrNotDispatched |
| 349 | } |
| 350 | if r.Phase != "" && r.Phase != "push_started" && r.Phase != "observed" { |
| 351 | return team.Receipt{}, team.ErrUncertain |
| 352 | } |
| 353 | v := r.Authorization.Publication |
| 354 | cred, e := p.credential(ctx, v.Repository) |
| 355 | if e != nil { |
| 356 | return team.Receipt{}, e |
| 357 | } |
| 358 | if cred.Agent != r.Description.Agent || cred.Remote != r.Remote || r.Description.Body != v.Description || r.Description.Digest != v.DescriptionHash { |
| 359 | return team.Receipt{}, team.ErrConflict |
| 360 | } |
| 361 | ref := "refs/heads/" + v.Ref |
| 362 | head, e := p.remoteHead(ctx, cred, v.Ref) |
| 363 | if e != nil || head == "" { |
| 364 | return team.Receipt{}, team.ErrUncertain |
| 365 | } |
| 366 | if head != v.Head { |
| 367 | return team.Receipt{}, team.ErrConflict |
| 368 | } |
| 369 | if e = p.confirmDescription(ctx, cred, &r); e != nil { |
| 370 | return team.Receipt{}, e |
| 371 | } |
| 372 | label := v.Isolation.Status |
| 373 | if v.Isolation.RunnerTainted { |
| 374 | label = "unconfined" |
| 375 | } |
| 376 | 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 |
| 377 | } |
| 378 | func (p *Publisher) Reconcile(ctx context.Context, d team.Dispatch) (team.ReconcileResult, error) { |
| 379 | if validateDispatch(d) != nil { |
| 380 | return team.ReconcileResult{}, team.ErrInvalid |
| 381 | } |
| 382 | unlock, e := p.lock(d) |
| 383 | if e != nil { |
| 384 | return team.ReconcileResult{}, e |
| 385 | } |
| 386 | defer unlock() |
| 387 | r, e := p.load(d) |
| 388 | if os.IsNotExist(e) { |
| 389 | if err := runnerproto.JournalCredentials(p.path(d), record{Phase: "not_dispatched", Authorization: Authorization{Ticket: team.AdmissionTicket{Dispatch: d}}}); err != nil { |
| 390 | return team.ReconcileResult{}, team.ErrUncertain |
| 391 | } |
| 392 | return team.ReconcileResult{}, team.ErrNotDispatched |
| 393 | } |
| 394 | if e != nil { |
| 395 | return team.ReconcileResult{}, team.ErrUncertain |
| 396 | } |
| 397 | receipt, e := p.reconcile(ctx, r) |
| 398 | if e != nil { |
| 399 | return team.ReconcileResult{}, e |
| 400 | } |
| 401 | return team.ReconcileResult{Receipt: &receipt, Definitive: true}, nil |
| 402 | } |
| 403 | |
| 404 | func (p *Publisher) remoteHead(ctx context.Context, cred Credential, branch string) (string, error) { |
| 405 | ref := "refs/heads/" + branch |
| 406 | out, err := p.git(ctx, p.cfg.Root, &cred, "ls-remote", "--refs", "--", p.remote(cred.Remote), ref) |
| 407 | if err != nil { |
| 408 | return "", team.ErrUncertain |
| 409 | } |
| 410 | fields := strings.Fields(out) |
| 411 | if len(fields) == 0 { |
| 412 | return "", nil |
| 413 | } |
| 414 | if len(fields) != 2 || !object.MatchString(fields[0]) || fields[1] != ref { |
| 415 | return "", team.ErrUncertain |
| 416 | } |
| 417 | return fields[0], nil |
| 418 | } |
| 419 | |
| 420 | func validRepository(repository string) bool { |
| 421 | if !forgekey.ValidHub(repository) { |
| 422 | return false |
| 423 | } |
| 424 | for _, part := range strings.Split(repository, "/")[1:] { |
| 425 | if part == "." || part == ".." { |
| 426 | return false |
| 427 | } |
| 428 | } |
| 429 | return true |
| 430 | } |
| 431 | |