| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "sort" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | const artifactColumns = `id, job_id, step_id, attempt_id, fence, role, hash, media_type, size, provenance, payload, created_at` |
| 13 | |
| 14 | func scanArtifact(r rowScanner) (Artifact, error) { |
| 15 | var a Artifact |
| 16 | var role, prov, created string |
| 17 | if err := r.Scan(&a.ID, &a.Job, &a.Step, &a.Attempt, &a.Fence, &role, &a.Hash, &a.MediaType, &a.Size, &prov, &a.Payload, &created); err != nil { |
| 18 | return a, err |
| 19 | } |
| 20 | a.Role = Role(role) |
| 21 | if !a.Role.Valid() { |
| 22 | return a, fail(CodeUnknownKind, "artifact %d role %q", a.ID, role) |
| 23 | } |
| 24 | if err := strictJSON([]byte(prov), &a.Provenance); err != nil { |
| 25 | return a, fail(CodeUnknownKind, "artifact %d provenance: %v", a.ID, err) |
| 26 | } |
| 27 | a.CreatedAt = parseTS(created) |
| 28 | return a, nil |
| 29 | } |
| 30 | |
| 31 | // latestArtifact returns the newest artifact of the role produced by an |
| 32 | // attempt that succeeded, or nil. Artifacts of attempts that expired, were |
| 33 | // stopped or failed never count as evidence. |
| 34 | func latestArtifact(ctx context.Context, tx *sql.Tx, job JobID, role Role) (*Artifact, error) { |
| 35 | a, err := scanArtifact(tx.QueryRowContext(ctx, `SELECT `+artifactColumns+` FROM artifacts WHERE job_id=? AND role=? |
| 36 | AND attempt_id IN (SELECT id FROM attempts WHERE job_id=? AND state='succeeded') ORDER BY id DESC LIMIT 1`, int64(job), string(role), int64(job))) |
| 37 | if errors.Is(err, sql.ErrNoRows) { |
| 38 | return nil, nil |
| 39 | } |
| 40 | if err != nil { |
| 41 | return nil, fail(CodeInvalid, "artifact: %v", err) |
| 42 | } |
| 43 | return &a, nil |
| 44 | } |
| 45 | |
| 46 | // latestAny is latestArtifact without the succeeded-attempt filter, for |
| 47 | // registration-time checks against work still in progress. |
| 48 | func latestAny(ctx context.Context, tx *sql.Tx, job JobID, role Role) (*Artifact, error) { |
| 49 | a, err := scanArtifact(tx.QueryRowContext(ctx, `SELECT `+artifactColumns+` FROM artifacts WHERE job_id=? AND role=? ORDER BY id DESC LIMIT 1`, int64(job), string(role))) |
| 50 | if errors.Is(err, sql.ErrNoRows) { |
| 51 | return nil, nil |
| 52 | } |
| 53 | if err != nil { |
| 54 | return nil, fail(CodeInvalid, "artifact: %v", err) |
| 55 | } |
| 56 | return &a, nil |
| 57 | } |
| 58 | |
| 59 | // Register stores an immutable artifact under the attempt's current fence. |
| 60 | // The role must be one the step's capability may produce; typed payloads |
| 61 | // are decoded strictly; check results must name the frozen reproduction, |
| 62 | // the job's check definition and the right subject; a review must name |
| 63 | // the current candidate or reconciliation. A reproduction cannot be |
| 64 | // registered once any candidate exists: it is frozen by then. |
| 65 | func (s *Store) Register(ctx context.Context, scope Scope, h Handle, spec ArtifactSpec) (Artifact, error) { |
| 66 | if !spec.Role.Valid() { |
| 67 | return Artifact{}, fail(CodeUnknownKind, "role %q", spec.Role) |
| 68 | } |
| 69 | if len(spec.Payload) == 0 || len(spec.Payload) > MaxArtifactBytes { |
| 70 | return Artifact{}, fail(CodeSize, "artifact %d bytes", len(spec.Payload)) |
| 71 | } |
| 72 | if spec.MediaType == "" { |
| 73 | return Artifact{}, fail(CodeInvalid, "artifact needs a media type") |
| 74 | } |
| 75 | hash := hashBytes(spec.Payload) |
| 76 | var out Artifact |
| 77 | err := s.tx(ctx, func(tx *sql.Tx) error { |
| 78 | if err := admissionOpen(ctx, tx); err != nil { |
| 79 | return err |
| 80 | } |
| 81 | now := s.clock.Now() |
| 82 | hd, err := current(ctx, tx, scope, h, now) |
| 83 | if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | if hd.job.Target.Kind == TargetProjectRead && spec.Role != RoleAnswer { |
| 87 | return ErrScope |
| 88 | } |
| 89 | if spec.Role == RoleAnswer { |
| 90 | if err := s.validateAnswer(ctx, tx, hd.job, spec.Payload); err != nil { |
| 91 | return err |
| 92 | } |
| 93 | } |
| 94 | if !roleAllowed(hd.step.Capability, spec.Role) { |
| 95 | return fail(CodeScope, "capability %s may not register %s", hd.step.Capability, spec.Role) |
| 96 | } |
| 97 | if hd.job.Policy.Version == 2 { |
| 98 | spec.Provenance, err = s.observedProvenance(ctx, tx, scope, h) |
| 99 | if err != nil { |
| 100 | return err |
| 101 | } |
| 102 | if spec.Role == RoleCandidate { |
| 103 | if !gitCandidateFields(spec.Payload) { |
| 104 | return fail(CodeEvidence, "git_candidate_invalid") |
| 105 | } |
| 106 | spec.Payload, hash, err = canonical(spec.Payload) |
| 107 | if err != nil { |
| 108 | return fail(CodeEvidence, "git_candidate_invalid") |
| 109 | } |
| 110 | } |
| 111 | } else if err := spec.Provenance.validate(); err != nil { |
| 112 | return err |
| 113 | } |
| 114 | if (hd.job.Evidence.RequireBugFreeze || hd.job.Evidence.Predicate == PredicateSoftwareFeature || hd.job.Evidence.Predicate == PredicateRenderedChange) && (spec.Role == RoleRender || spec.Role == RoleBaseResult || spec.Role == RoleCandidateResult || spec.Role == RoleRepositoryChecks) { |
| 115 | if s.executorEvidence == nil { |
| 116 | return fail(CodeEvidence, "executor_attestation_missing") |
| 117 | } |
| 118 | executor, err := s.executorEvidence(ctx, tx, scope, h, spec) |
| 119 | if err != nil { |
| 120 | return err |
| 121 | } |
| 122 | if err := executor.validate(); err != nil { |
| 123 | return err |
| 124 | } |
| 125 | // Exposure comes from the instance observation, even for executor evidence. |
| 126 | executor.ConnectionID = spec.Provenance.ConnectionID |
| 127 | executor.Isolation = spec.Provenance.Isolation |
| 128 | spec.Provenance = executor |
| 129 | } |
| 130 | if err := validateArtifact(ctx, tx, hd.job, spec, hash); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | prov, _ := json.Marshal(spec.Provenance) |
| 134 | res, err := tx.ExecContext(ctx, `INSERT INTO artifacts(job_id, step_id, attempt_id, fence, role, hash, media_type, size, provenance, payload, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)`, |
| 135 | int64(hd.job.ID), int64(hd.step.ID), int64(hd.attempt.ID), hd.attempt.Fence, string(spec.Role), hash, spec.MediaType, len(spec.Payload), string(prov), spec.Payload, ts(now)) |
| 136 | if err != nil { |
| 137 | return fail(CodeInvalid, "insert artifact: %v", err) |
| 138 | } |
| 139 | id, _ := res.LastInsertId() |
| 140 | out = Artifact{ID: ArtifactID(id), Job: hd.job.ID, Step: hd.step.ID, Attempt: hd.attempt.ID, Fence: hd.attempt.Fence, Role: spec.Role, Hash: hash, |
| 141 | MediaType: spec.MediaType, Size: int64(len(spec.Payload)), Provenance: spec.Provenance, Payload: spec.Payload, CreatedAt: now} |
| 142 | return appendEvent(ctx, tx, scope, "artifact.registered", h.Runner, map[string]any{"artifact": id, "role": spec.Role, "hash": hash, "fence": hd.attempt.Fence, "producer": spec.Provenance.Producer, "provider": spec.Provenance.Provider}, now) |
| 143 | }) |
| 144 | return out, err |
| 145 | } |
| 146 | |
| 147 | func validateArtifact(ctx context.Context, tx *sql.Tx, j jobRow, spec ArtifactSpec, hash string) error { |
| 148 | switch spec.Role { |
| 149 | case RoleRender: |
| 150 | cand, err := latestAny(ctx, tx, j.ID, RoleCandidate) |
| 151 | if err != nil { |
| 152 | return err |
| 153 | } |
| 154 | return validateRender(spec.Payload, cand, j) |
| 155 | case RoleAcceptance: |
| 156 | if j.Evidence.Predicate != PredicateSoftwareFeature || j.Evidence.FrozenAcceptanceHash != "" { |
| 157 | return ErrEvidence |
| 158 | } |
| 159 | cand, err := latestAny(ctx, tx, j.ID, RoleCandidate) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | if cand != nil { |
| 164 | return ErrEvidence |
| 165 | } |
| 166 | case RoleReproduction: |
| 167 | if j.Evidence.FrozenReproductionHash != "" && hash != j.Evidence.FrozenReproductionHash { |
| 168 | return fail(CodeEvidence, "frozen_reproduction_changed") |
| 169 | } |
| 170 | cand, err := latestAny(ctx, tx, j.ID, RoleCandidate) |
| 171 | if err != nil { |
| 172 | return err |
| 173 | } |
| 174 | if cand != nil { |
| 175 | return fail(CodeState, "reproduction is frozen: a candidate exists") |
| 176 | } |
| 177 | case RoleBaseResult, RoleCandidateResult: |
| 178 | var cr CheckResult |
| 179 | if err := strictJSON(spec.Payload, &cr); err != nil { |
| 180 | return fail(CodeInvalid, "check result: %v", err) |
| 181 | } |
| 182 | if !cr.Outcome.Valid() { |
| 183 | return fail(CodeUnknownKind, "check outcome %q", cr.Outcome) |
| 184 | } |
| 185 | repro, err := latestAny(ctx, tx, j.ID, acceptanceRole(j)) |
| 186 | if err != nil { |
| 187 | return err |
| 188 | } |
| 189 | if repro == nil || cr.ReproductionHash != repro.Hash { |
| 190 | return fail(CodeEvidence, "check result ran reproduction %q, frozen is %q", short(cr.ReproductionHash), short(hashOf(repro))) |
| 191 | } |
| 192 | if cr.CheckDefinitionHash != j.Evidence.CheckDefinitionHash { |
| 193 | return fail(CodeEvidence, "check result under definition %q, trusted is %q", short(cr.CheckDefinitionHash), short(j.Evidence.CheckDefinitionHash)) |
| 194 | } |
| 195 | if spec.Role == RoleBaseResult && cr.SubjectHash != j.Target.BaseRevision { |
| 196 | return fail(CodeEvidence, "base result ran on %q, base is %q", short(cr.SubjectHash), short(j.Target.BaseRevision)) |
| 197 | } |
| 198 | if spec.Role == RoleCandidateResult { |
| 199 | cand, err := latestAny(ctx, tx, j.ID, RoleCandidate) |
| 200 | if err != nil { |
| 201 | return err |
| 202 | } |
| 203 | if cand == nil || cr.SubjectHash != cand.Hash { |
| 204 | return fail(CodeEvidence, "candidate result ran on %q, latest candidate is %q", short(cr.SubjectHash), short(hashOf(cand))) |
| 205 | } |
| 206 | } |
| 207 | case RoleReview: |
| 208 | var rv Review |
| 209 | if err := strictJSON(spec.Payload, &rv); err != nil { |
| 210 | return fail(CodeInvalid, "review: %v", err) |
| 211 | } |
| 212 | if !rv.Verdict.Valid() { |
| 213 | return fail(CodeUnknownKind, "verdict %q", rv.Verdict) |
| 214 | } |
| 215 | subjectRole := RoleCandidate |
| 216 | if j.Evidence.Predicate == PredicateAttestedReconciliation { |
| 217 | subjectRole = RoleReconciliation |
| 218 | } |
| 219 | subj, err := latestAny(ctx, tx, j.ID, subjectRole) |
| 220 | if err != nil { |
| 221 | return err |
| 222 | } |
| 223 | if subj == nil || subj.Hash != rv.SubjectHash { |
| 224 | return fail(CodeEvidence, "review of %q, latest %s is %q", short(rv.SubjectHash), subjectRole, short(hashOf(subj))) |
| 225 | } |
| 226 | if !independentForPolicy(subj.Provenance, spec.Provenance, j.Policy) { |
| 227 | return fail(CodeEvidence, "review is not independent of the %s it reviews", subjectRole) |
| 228 | } |
| 229 | if j.Policy.Version == 2 && subjectRole == RoleCandidate { |
| 230 | if err := independentBuilders(ctx, tx, j, spec.Provenance); err != nil { |
| 231 | return err |
| 232 | } |
| 233 | } |
| 234 | case RoleReconciliation: |
| 235 | var rc reconciliationWire |
| 236 | if err := strictJSON(spec.Payload, &rc); err != nil { |
| 237 | return fail(CodeInvalid, "reconciliation: %v", err) |
| 238 | } |
| 239 | if rc.Discrepancies == nil { |
| 240 | return fail(CodeEvidence, "reconciliation without an explicit discrepancies list") |
| 241 | } |
| 242 | case RoleRepositoryChecks: |
| 243 | if j.Policy.Version != 2 { |
| 244 | return fail(CodeEvidence, "repository_checks_require_v2") |
| 245 | } |
| 246 | cand, err := latestAny(ctx, tx, j.ID, RoleCandidate) |
| 247 | if err != nil { |
| 248 | return err |
| 249 | } |
| 250 | return validateRepositoryChecks(spec.Payload, cand, j) |
| 251 | case RoleCandidate: |
| 252 | if j.Evidence.Predicate == PredicateSoftwareFeature { |
| 253 | if err := featureBuildReady(ctx, tx, j); err != nil { |
| 254 | return err |
| 255 | } |
| 256 | } |
| 257 | if j.Evidence.RequireBugFreeze && j.Evidence.FrozenReproductionHash == "" { |
| 258 | return fail(CodeEvidence, "bug_evidence_not_frozen") |
| 259 | } |
| 260 | if j.Policy.Version == 2 { |
| 261 | _, err := gitCandidate(&Artifact{MediaType: spec.MediaType, Payload: spec.Payload, Hash: hash}, j) |
| 262 | return err |
| 263 | } |
| 264 | case RoleSourceRecord: |
| 265 | } |
| 266 | return nil |
| 267 | } |
| 268 | |
| 269 | // reconciliationWire detects an absent discrepancies key, which the |
| 270 | // value type cannot. |
| 271 | type reconciliationWire struct { |
| 272 | SourceHashes []string `json:"source_hashes"` |
| 273 | Matched int `json:"matched"` |
| 274 | Discrepancies *[]Discrepancy `json:"discrepancies"` |
| 275 | } |
| 276 | |
| 277 | func independent(subject, review Provenance, distinctProvider bool) bool { |
| 278 | if review.Producer == subject.Producer || review.Context == subject.Context { |
| 279 | return false |
| 280 | } |
| 281 | if distinctProvider && review.Provider == subject.Provider { |
| 282 | return false |
| 283 | } |
| 284 | return true |
| 285 | } |
| 286 | |
| 287 | func hashOf(a *Artifact) string { |
| 288 | if a == nil { |
| 289 | return "" |
| 290 | } |
| 291 | return a.Hash |
| 292 | } |
| 293 | |
| 294 | func short(h string) string { |
| 295 | if len(h) > 12 { |
| 296 | return h[:12] |
| 297 | } |
| 298 | return h |
| 299 | } |
| 300 | |
| 301 | // EvidenceReport is Conclude's finding: which artifacts and publication |
| 302 | // satisfied the predicate, or the first reason it is not satisfied. |
| 303 | type EvidenceReport struct { |
| 304 | RepositoryChecks string |
| 305 | Isolation IsolationSnapshot |
| 306 | Predicate Predicate |
| 307 | Satisfied bool |
| 308 | Reason string |
| 309 | Reproduction string // hash |
| 310 | BaseResult string |
| 311 | Candidate string |
| 312 | CandidateResult string |
| 313 | Review string |
| 314 | Reviewer Provenance |
| 315 | Publication ActionID |
| 316 | PublishReceipt string |
| 317 | Sources []string |
| 318 | Reconciliation string |
| 319 | } |
| 320 | |
| 321 | // Conclude evaluates the job's success predicate against stored evidence |
| 322 | // and ends the job: succeeded when satisfied, failed otherwise. Only |
| 323 | // artifacts of succeeded attempts count, each reviewed or verified hash |
| 324 | // must be the current one, reviews must be independent, and a software |
| 325 | // fix must have been published under a receipt for that exact candidate. |
| 326 | func (s *Store) Conclude(ctx context.Context, scope Scope, actor string) (EvidenceReport, error) { |
| 327 | var rep EvidenceReport |
| 328 | err := s.tx(ctx, func(tx *sql.Tx) error { |
| 329 | now := s.clock.Now() |
| 330 | j, err := loadJob(ctx, tx, scope) |
| 331 | if err != nil { |
| 332 | return err |
| 333 | } |
| 334 | if j.State.Terminal() { |
| 335 | return fail(CodeState, "job %d is %s", j.ID, j.State) |
| 336 | } |
| 337 | var live int |
| 338 | if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM attempts WHERE job_id=? AND containment='pending'`, int64(j.ID)).Scan(&live); err != nil { |
| 339 | return fail(CodeInvalid, "attempts: %v", err) |
| 340 | } |
| 341 | if live > 0 { |
| 342 | return fail(CodeState, "job %d has %d live attempts", j.ID, live) |
| 343 | } |
| 344 | var children int |
| 345 | if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM jobs WHERE parent=? AND state NOT IN ('succeeded','failed','cancelled')`, int64(j.ID)).Scan(&children); err != nil { |
| 346 | return fail(CodeInvalid, "children: %v", err) |
| 347 | } |
| 348 | if children != 0 { |
| 349 | return fail(CodeState, "job %d has %d unfinished children", j.ID, children) |
| 350 | } |
| 351 | if j.Policy.Version == 2 { |
| 352 | var unfinished int |
| 353 | if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM steps WHERE job_id=? AND state IN ('pending','running')`, int64(j.ID)).Scan(&unfinished); err != nil { |
| 354 | return err |
| 355 | } |
| 356 | if unfinished != 0 { |
| 357 | return fail(CodeState, "workflow_unfinished") |
| 358 | } |
| 359 | } |
| 360 | rep, err = s.evaluateEvidence(ctx, tx, j, false) |
| 361 | if err != nil { |
| 362 | return err |
| 363 | } |
| 364 | state, outcome := JobSucceeded, "evidence satisfied" |
| 365 | if !rep.Satisfied { |
| 366 | state, outcome = JobFailed, "evidence: "+rep.Reason |
| 367 | } |
| 368 | if state == JobFailed { |
| 369 | if _, err := terminate(ctx, tx, j, JobFailed, actor, outcome, now); err != nil { |
| 370 | return err |
| 371 | } |
| 372 | } else { |
| 373 | if _, err := terminate(ctx, tx, j, JobSucceeded, actor, outcome, now); err != nil { |
| 374 | return err |
| 375 | } |
| 376 | } |
| 377 | return appendEvent(ctx, tx, scope, "job.concluded", actor, rep, now) |
| 378 | }) |
| 379 | if err != nil { |
| 380 | return rep, err |
| 381 | } |
| 382 | if !rep.Satisfied { |
| 383 | return rep, fail(CodeEvidence, "%s", rep.Reason) |
| 384 | } |
| 385 | return rep, nil |
| 386 | } |
| 387 | |
| 388 | func evaluateSoftwareFix(ctx context.Context, tx *sql.Tx, j jobRow, ready bool) (EvidenceReport, error) { |
| 389 | rep := EvidenceReport{Predicate: j.Evidence.Predicate} |
| 390 | miss := func(why string) (EvidenceReport, error) { |
| 391 | rep.Reason = why |
| 392 | return rep, nil |
| 393 | } |
| 394 | repro, err := latestArtifact(ctx, tx, j.ID, acceptanceRole(j)) |
| 395 | if err != nil { |
| 396 | return rep, err |
| 397 | } |
| 398 | if repro == nil { |
| 399 | return miss("no frozen reproduction from a completed attempt") |
| 400 | } |
| 401 | if (j.Evidence.RequireBugFreeze && repro.Hash != j.Evidence.FrozenReproductionHash) || (j.Evidence.Predicate == PredicateSoftwareFeature && repro.Hash != j.Evidence.FrozenAcceptanceHash) { |
| 402 | return miss("frozen_reproduction_mismatch") |
| 403 | } |
| 404 | rep.Reproduction = repro.Hash |
| 405 | base, err := latestArtifact(ctx, tx, j.ID, RoleBaseResult) |
| 406 | if err != nil { |
| 407 | return rep, err |
| 408 | } |
| 409 | if base == nil { |
| 410 | return miss("no base result") |
| 411 | } |
| 412 | var br CheckResult |
| 413 | if err := strictJSON(base.Payload, &br); err != nil { |
| 414 | return rep, fail(CodeUnknownKind, "base result: %v", err) |
| 415 | } |
| 416 | if br.ReproductionHash != repro.Hash || br.CheckDefinitionHash != j.Evidence.CheckDefinitionHash || br.SubjectHash != j.Target.BaseRevision { |
| 417 | return miss("base result does not name the frozen reproduction, trusted check definition and base revision") |
| 418 | } |
| 419 | if br.Outcome != CheckFail || br.TestsRun <= 0 || br.TestsFailed <= 0 || br.TestsFailed > br.TestsRun { |
| 420 | return miss("base result is " + string(br.Outcome) + " with " + itoa(br.TestsRun) + " run and " + itoa(br.TestsFailed) + " failed; expected a failing test") |
| 421 | } |
| 422 | if j.Evidence.Predicate == PredicateSoftwareFix && !strings.Contains(br.FailureMessage, j.Evidence.ExpectedSymptom) { |
| 423 | return miss("base failure does not show the expected symptom") |
| 424 | } |
| 425 | rep.BaseResult = base.Hash |
| 426 | cand, err := latestArtifact(ctx, tx, j.ID, RoleCandidate) |
| 427 | if err != nil { |
| 428 | return rep, err |
| 429 | } |
| 430 | if cand == nil { |
| 431 | return miss("no candidate") |
| 432 | } |
| 433 | rep.Candidate = cand.Hash |
| 434 | if j.Policy.Version == 2 { |
| 435 | latest, err := latestAny(ctx, tx, j.ID, RoleCandidate) |
| 436 | if err != nil { |
| 437 | return rep, err |
| 438 | } |
| 439 | if latest == nil || latest.ID != cand.ID { |
| 440 | return miss("candidate_changed") |
| 441 | } |
| 442 | if _, err := gitCandidate(cand, j); err != nil { |
| 443 | return miss("git_candidate_invalid") |
| 444 | } |
| 445 | rep.Isolation, err = lineageIsolation(ctx, tx, j.ID, cand.Provenance.Isolation) |
| 446 | if err != nil { |
| 447 | return rep, err |
| 448 | } |
| 449 | } |
| 450 | review, err := latestArtifact(ctx, tx, j.ID, RoleReview) |
| 451 | if err != nil { |
| 452 | return rep, err |
| 453 | } |
| 454 | if review == nil { |
| 455 | return miss("no review") |
| 456 | } |
| 457 | var rv Review |
| 458 | if err := strictJSON(review.Payload, &rv); err != nil { |
| 459 | return rep, fail(CodeUnknownKind, "review: %v", err) |
| 460 | } |
| 461 | if rv.SubjectHash != cand.Hash || review.ID < cand.ID { |
| 462 | return miss("review is for another candidate; the candidate changed") |
| 463 | } |
| 464 | if !independentForPolicy(cand.Provenance, review.Provenance, j.Policy) { |
| 465 | return miss("review is not independent of the candidate") |
| 466 | } |
| 467 | if rv.Verdict != VerdictApprove { |
| 468 | return miss("review verdict " + string(rv.Verdict)) |
| 469 | } |
| 470 | if j.Policy.Version == 2 { |
| 471 | if err := independentBuilders(ctx, tx, j, review.Provenance); err != nil { |
| 472 | return miss("review_family_conflict") |
| 473 | } |
| 474 | } |
| 475 | rep.Review, rep.Reviewer = review.Hash, review.Provenance |
| 476 | cr, err := latestArtifact(ctx, tx, j.ID, RoleCandidateResult) |
| 477 | if err != nil { |
| 478 | return rep, err |
| 479 | } |
| 480 | if cr == nil { |
| 481 | return miss("no candidate result") |
| 482 | } |
| 483 | var vr CheckResult |
| 484 | if err := strictJSON(cr.Payload, &vr); err != nil { |
| 485 | return rep, fail(CodeUnknownKind, "candidate result: %v", err) |
| 486 | } |
| 487 | if vr.ReproductionHash != repro.Hash || vr.CheckDefinitionHash != j.Evidence.CheckDefinitionHash { |
| 488 | return miss("candidate result does not name the frozen reproduction and trusted check definition") |
| 489 | } |
| 490 | if vr.SubjectHash != cand.Hash || cr.ID < cand.ID { |
| 491 | return miss("candidate result is for another candidate; the candidate changed") |
| 492 | } |
| 493 | if vr.Outcome != CheckPass || vr.TestsRun <= 0 || vr.TestsFailed != 0 { |
| 494 | return miss("candidate result is " + string(vr.Outcome) + " with " + itoa(vr.TestsRun) + " run and " + itoa(vr.TestsFailed) + " failed; expected a pass") |
| 495 | } |
| 496 | rep.CandidateResult = cr.Hash |
| 497 | if j.Policy.Version == 2 { |
| 498 | checks, err := latestArtifact(ctx, tx, j.ID, RoleRepositoryChecks) |
| 499 | if err != nil { |
| 500 | return rep, err |
| 501 | } |
| 502 | if checks == nil || checks.ID < cand.ID { |
| 503 | return miss("repository_checks_missing") |
| 504 | } |
| 505 | if err := validateRepositoryChecks(checks.Payload, cand, j); err != nil { |
| 506 | return miss("repository_checks_failed") |
| 507 | } |
| 508 | rep.RepositoryChecks = checks.Hash |
| 509 | } |
| 510 | if ready { |
| 511 | rep.Satisfied = true |
| 512 | return rep, nil |
| 513 | } |
| 514 | rows, err := tx.QueryContext(ctx, `SELECT `+actionColumns+` FROM actions WHERE job_id=? AND operation=? AND state='succeeded' AND step_id IN (SELECT id FROM steps WHERE job_id=? AND capability=?) ORDER BY id DESC`, int64(j.ID), string(OpForgePublish), int64(j.ID), string(CapPublish)) |
| 515 | if err != nil { |
| 516 | return rep, fail(CodeInvalid, "publications: %v", err) |
| 517 | } |
| 518 | defer rows.Close() |
| 519 | for rows.Next() { |
| 520 | a, err := scanAction(rows) |
| 521 | if err != nil { |
| 522 | return rep, err |
| 523 | } |
| 524 | var p publication |
| 525 | if err := strictJSON(a.Payload, &p); err != nil { |
| 526 | continue |
| 527 | } |
| 528 | if publicationMatches(p, cand, j) && a.Receipt != nil && (j.Policy.Version == 1 || isolationContains(p.Isolation, rep.Isolation)) { |
| 529 | rep.Publication, rep.PublishReceipt = a.ID, a.Receipt.ID |
| 530 | break |
| 531 | } |
| 532 | } |
| 533 | if rep.Publication == 0 { |
| 534 | return miss("candidate not published with a receipt") |
| 535 | } |
| 536 | rep.Satisfied = true |
| 537 | return rep, nil |
| 538 | } |
| 539 | |
| 540 | func evaluateReconciliation(ctx context.Context, tx *sql.Tx, j jobRow) (EvidenceReport, error) { |
| 541 | rep := EvidenceReport{Predicate: PredicateAttestedReconciliation} |
| 542 | miss := func(why string) (EvidenceReport, error) { |
| 543 | rep.Reason = why |
| 544 | return rep, nil |
| 545 | } |
| 546 | rows, err := tx.QueryContext(ctx, `SELECT DISTINCT hash FROM artifacts WHERE job_id=? AND role=? AND attempt_id IN (SELECT id FROM attempts WHERE job_id=? AND state='succeeded') ORDER BY hash`, |
| 547 | int64(j.ID), string(RoleSourceRecord), int64(j.ID)) |
| 548 | if err != nil { |
| 549 | return rep, fail(CodeInvalid, "sources: %v", err) |
| 550 | } |
| 551 | for rows.Next() { |
| 552 | var h string |
| 553 | if err := rows.Scan(&h); err != nil { |
| 554 | rows.Close() |
| 555 | return rep, fail(CodeInvalid, "sources: %v", err) |
| 556 | } |
| 557 | rep.Sources = append(rep.Sources, h) |
| 558 | } |
| 559 | rows.Close() |
| 560 | if len(rep.Sources) < j.Evidence.RequiredSources { |
| 561 | return miss("only " + itoa(len(rep.Sources)) + " source records of " + itoa(j.Evidence.RequiredSources) + " required") |
| 562 | } |
| 563 | rec, err := latestArtifact(ctx, tx, j.ID, RoleReconciliation) |
| 564 | if err != nil { |
| 565 | return rep, err |
| 566 | } |
| 567 | if rec == nil { |
| 568 | return miss("no reconciliation") |
| 569 | } |
| 570 | var rw reconciliationWire |
| 571 | if err := strictJSON(rec.Payload, &rw); err != nil { |
| 572 | return rep, fail(CodeUnknownKind, "reconciliation: %v", err) |
| 573 | } |
| 574 | got := append([]string(nil), rw.SourceHashes...) |
| 575 | sort.Strings(got) |
| 576 | if strings.Join(got, ",") != strings.Join(rep.Sources, ",") { |
| 577 | return miss("reconciliation does not cover exactly the collected source records") |
| 578 | } |
| 579 | if rw.Discrepancies == nil { |
| 580 | return miss("reconciliation has no explicit discrepancies list") |
| 581 | } |
| 582 | rep.Reconciliation = rec.Hash |
| 583 | review, err := latestArtifact(ctx, tx, j.ID, RoleReview) |
| 584 | if err != nil { |
| 585 | return rep, err |
| 586 | } |
| 587 | if review == nil { |
| 588 | return miss("no review") |
| 589 | } |
| 590 | var rv Review |
| 591 | if err := strictJSON(review.Payload, &rv); err != nil { |
| 592 | return rep, fail(CodeUnknownKind, "review: %v", err) |
| 593 | } |
| 594 | if rv.SubjectHash != rec.Hash || review.ID < rec.ID { |
| 595 | return miss("review is for another reconciliation") |
| 596 | } |
| 597 | if !independentForPolicy(rec.Provenance, review.Provenance, j.Policy) { |
| 598 | return miss("review is not independent of the reconciliation") |
| 599 | } |
| 600 | if rv.Verdict != VerdictApprove { |
| 601 | return miss("review verdict " + string(rv.Verdict)) |
| 602 | } |
| 603 | rep.Review, rep.Reviewer = review.Hash, review.Provenance |
| 604 | rep.Satisfied = true |
| 605 | return rep, nil |
| 606 | } |
| 607 | |
| 608 | func itoa(n int) string { |
| 609 | b, _ := json.Marshal(n) |
| 610 | return string(b) |
| 611 | } |
| 612 | |
| 613 | // Artifacts lists the job's artifacts without payloads. |
| 614 | func (s *Store) Artifacts(ctx context.Context, scope Scope) ([]Artifact, error) { |
| 615 | var out []Artifact |
| 616 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 617 | if _, err := loadJob(ctx, tx, scope); err != nil { |
| 618 | return err |
| 619 | } |
| 620 | rows, err := tx.QueryContext(ctx, `SELECT `+artifactColumns+` FROM artifacts WHERE job_id=? ORDER BY id`, int64(scope.Job)) |
| 621 | if err != nil { |
| 622 | return fail(CodeInvalid, "artifacts: %v", err) |
| 623 | } |
| 624 | defer rows.Close() |
| 625 | for rows.Next() { |
| 626 | a, err := scanArtifact(rows) |
| 627 | if err != nil { |
| 628 | return err |
| 629 | } |
| 630 | a.Payload = nil |
| 631 | out = append(out, a) |
| 632 | } |
| 633 | return rows.Err() |
| 634 | }) |
| 635 | return out, err |
| 636 | } |
| 637 | |
| 638 | // Artifact reads one artifact with its payload. |
| 639 | func (s *Store) Artifact(ctx context.Context, scope Scope, id ArtifactID) (Artifact, error) { |
| 640 | var out Artifact |
| 641 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 642 | if _, err := loadJob(ctx, tx, scope); err != nil { |
| 643 | return err |
| 644 | } |
| 645 | a, err := scanArtifact(tx.QueryRowContext(ctx, `SELECT `+artifactColumns+` FROM artifacts WHERE job_id=? AND id=?`, int64(scope.Job), int64(id))) |
| 646 | if errors.Is(err, sql.ErrNoRows) { |
| 647 | return fail(CodeScope, "artifact %d", id) |
| 648 | } |
| 649 | out = a |
| 650 | return err |
| 651 | }) |
| 652 | return out, err |
| 653 | } |
| 654 | |