| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "encoding/json" |
| 8 | "slices" |
| 9 | ) |
| 10 | |
| 11 | const GitCandidateMediaType = "application/vnd.equipo.git-candidate+json" |
| 12 | |
| 13 | type GitCandidate struct { |
| 14 | Repository string `json:"repository"` |
| 15 | BaseCommit string `json:"base_commit"` |
| 16 | Commit string `json:"commit"` |
| 17 | Tree string `json:"tree"` |
| 18 | } |
| 19 | |
| 20 | type TestIdentity struct { |
| 21 | Package string `json:"package"` |
| 22 | Name string `json:"name"` |
| 23 | } |
| 24 | |
| 25 | type RepositoryCheckResult struct { |
| 26 | ObservedNames []TestIdentity `json:"observed_names,omitempty"` |
| 27 | Isolation IsolationSnapshot `json:"isolation,omitzero"` |
| 28 | ExecutorBinary string `json:"executor_binary,omitempty"` |
| 29 | ExecutorVersion string `json:"executor_version,omitempty"` |
| 30 | CandidateHash string `json:"candidate_hash"` |
| 31 | Commit string `json:"commit"` |
| 32 | CheckDefinitionHash string `json:"check_definition_hash"` |
| 33 | BaselineTestSetHash string `json:"baseline_test_set_hash"` |
| 34 | ObservedTestSetHash string `json:"observed_test_set_hash"` |
| 35 | Outcome CheckOutcome `json:"outcome"` |
| 36 | ExitCode int `json:"exit_code"` |
| 37 | TestsRun int `json:"tests_run"` |
| 38 | TestsFailed int `json:"tests_failed"` |
| 39 | LogHash string `json:"log_hash"` |
| 40 | } |
| 41 | |
| 42 | type IsolationTuple struct { |
| 43 | Provider string `json:"provider"` |
| 44 | ProviderVersion string `json:"provider_version"` |
| 45 | PaseoVersion string `json:"paseo_version,omitempty"` |
| 46 | LauncherVersion string `json:"launcher_version,omitempty"` |
| 47 | BwrapVersion string `json:"bwrap_version,omitempty"` |
| 48 | PolicyVersion string `json:"policy_version,omitempty"` |
| 49 | IsolationConfigHash string `json:"isolation_config_hash"` |
| 50 | } |
| 51 | |
| 52 | type IsolationSnapshot struct { |
| 53 | Mode string `json:"mode,omitempty"` |
| 54 | ProfileApprovals []ProfileApproval `json:"profile_approvals,omitempty"` |
| 55 | Trial *TrialSnapshot `json:"trial,omitempty"` |
| 56 | Status string `json:"status"` |
| 57 | RunnerTainted bool `json:"runner_tainted"` |
| 58 | AcknowledgementIDs []string `json:"acknowledgement_ids"` |
| 59 | ObservedTuples []IsolationTuple `json:"observed_tuples"` |
| 60 | } |
| 61 | |
| 62 | // ProvenanceResolver reads the authorized assignment and observed session using |
| 63 | // the supplied transaction. It must not trust tool payloads or call Store methods. |
| 64 | // A missing resolver denies v2 artifact registration and publication. |
| 65 | type ProvenanceResolver func(context.Context, *sql.Tx, Scope, Handle) (Provenance, error) |
| 66 | |
| 67 | func lowerHex(s string, size int) bool { |
| 68 | if len(s) != size { |
| 69 | return false |
| 70 | } |
| 71 | for _, c := range s { |
| 72 | if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { |
| 73 | return false |
| 74 | } |
| 75 | } |
| 76 | return true |
| 77 | } |
| 78 | func gitObject(s string) bool { return lowerHex(s, 40) || lowerHex(s, 64) } |
| 79 | func validGitCandidate(c GitCandidate, target TargetBinding) bool { |
| 80 | return c.Repository == target.Repository && c.BaseCommit == target.BaseRevision && gitObject(c.BaseCommit) && gitObject(c.Commit) && gitObject(c.Tree) && len(c.BaseCommit) == len(c.Commit) && len(c.Tree) == len(c.Commit) |
| 81 | } |
| 82 | func gitCandidate(a *Artifact, j jobRow) (GitCandidate, error) { |
| 83 | var c GitCandidate |
| 84 | if a == nil || a.MediaType != GitCandidateMediaType || !gitCandidateFields(a.Payload) || strictJSON(a.Payload, &c) != nil || !validGitCandidate(c, j.Target) { |
| 85 | return c, fail(CodeEvidence, "git_candidate_invalid") |
| 86 | } |
| 87 | payload, hash, err := canonical(a.Payload) |
| 88 | if err != nil || hash != a.Hash || string(payload) != string(a.Payload) { |
| 89 | return c, fail(CodeEvidence, "git_candidate_identity_invalid") |
| 90 | } |
| 91 | return c, nil |
| 92 | } |
| 93 | func (p IsolationSnapshot) Valid() bool { return p.valid() } |
| 94 | |
| 95 | func (p IsolationSnapshot) valid() bool { |
| 96 | if p.Mode != "" && p.Mode != "owner mode" { |
| 97 | return false |
| 98 | } |
| 99 | if !validProfileApprovals(p.ProfileApprovals) || !p.Trial.valid() || (p.Trial != nil && (p.Status != "unconfined" || !p.RunnerTainted)) { |
| 100 | return false |
| 101 | } |
| 102 | if p.Status != "confined" && p.Status != "unconfined" { |
| 103 | return false |
| 104 | } |
| 105 | if len(p.ObservedTuples) == 0 { |
| 106 | return false |
| 107 | } |
| 108 | if (p.Status == "unconfined" || p.RunnerTainted) && len(p.AcknowledgementIDs) == 0 && p.Trial == nil { |
| 109 | return false |
| 110 | } |
| 111 | if p.Status == "unconfined" && !p.RunnerTainted { |
| 112 | return false |
| 113 | } |
| 114 | for _, id := range p.AcknowledgementIDs { |
| 115 | if id == "" { |
| 116 | return false |
| 117 | } |
| 118 | } |
| 119 | for _, v := range p.ObservedTuples { |
| 120 | if !v.valid() { |
| 121 | return false |
| 122 | } |
| 123 | } |
| 124 | return true |
| 125 | } |
| 126 | |
| 127 | // ValidForDirectLaunch checks the shape of direct isolation evidence. A caller |
| 128 | // must also authorize owner mode or match release certification before dispatch. |
| 129 | // Historical snapshots remain readable through Valid, but grant no direct work. |
| 130 | func (p IsolationSnapshot) ValidForDirectLaunch() bool { |
| 131 | // Valid unconfined and trial snapshots are always tainted. |
| 132 | if !p.valid() || p.RunnerTainted { |
| 133 | return false |
| 134 | } |
| 135 | for _, v := range p.ObservedTuples { |
| 136 | if !v.direct() { |
| 137 | return false |
| 138 | } |
| 139 | } |
| 140 | return true |
| 141 | } |
| 142 | |
| 143 | func (v IsolationTuple) valid() bool { |
| 144 | if v.LauncherVersion == "" && v.BwrapVersion == "" && v.PolicyVersion == "" { |
| 145 | return v.Provider != "" && v.ProviderVersion != "" && v.PaseoVersion != "" && lowerHex(v.IsolationConfigHash, 64) |
| 146 | } |
| 147 | return v.direct() |
| 148 | } |
| 149 | |
| 150 | func (v IsolationTuple) direct() bool { |
| 151 | return (v.Provider == "claude" || v.Provider == "codex") && |
| 152 | v.ProviderVersion != "" && v.PaseoVersion == "" && |
| 153 | v.LauncherVersion != "" && v.BwrapVersion != "" && v.PolicyVersion != "" && |
| 154 | lowerHex(v.IsolationConfigHash, 64) |
| 155 | } |
| 156 | |
| 157 | func mergeIsolation(a, b IsolationSnapshot) IsolationSnapshot { |
| 158 | if b.Mode == "owner mode" { |
| 159 | a.Mode = b.Mode |
| 160 | } |
| 161 | a.ProfileApprovals = MergeProfileApprovals(a.ProfileApprovals, b.ProfileApprovals) |
| 162 | a.Trial = MergeTrial(a.Trial, b.Trial) |
| 163 | if a.Trial != nil { |
| 164 | a.Status = "unconfined" |
| 165 | } |
| 166 | // Status belongs to this connection; historical runner exposure is separate. |
| 167 | a.RunnerTainted = a.RunnerTainted || b.RunnerTainted || b.Status == "unconfined" |
| 168 | a.AcknowledgementIDs = slices.Clone(a.AcknowledgementIDs) |
| 169 | a.ObservedTuples = slices.Clone(a.ObservedTuples) |
| 170 | for _, id := range b.AcknowledgementIDs { |
| 171 | if !slices.Contains(a.AcknowledgementIDs, id) { |
| 172 | a.AcknowledgementIDs = append(a.AcknowledgementIDs, id) |
| 173 | } |
| 174 | } |
| 175 | for _, v := range b.ObservedTuples { |
| 176 | if !slices.Contains(a.ObservedTuples, v) { |
| 177 | a.ObservedTuples = append(a.ObservedTuples, v) |
| 178 | } |
| 179 | } |
| 180 | slices.Sort(a.AcknowledgementIDs) |
| 181 | slices.SortFunc(a.ObservedTuples, func(a, b IsolationTuple) int { |
| 182 | x, _ := json.Marshal(a) |
| 183 | y, _ := json.Marshal(b) |
| 184 | return slices.Compare(x, y) |
| 185 | }) |
| 186 | return a |
| 187 | } |
| 188 | func lineageIsolation(ctx context.Context, tx *sql.Tx, job JobID, current IsolationSnapshot) (IsolationSnapshot, error) { |
| 189 | rows, err := tx.QueryContext(ctx, `SELECT provenance FROM artifacts WHERE job_id=? ORDER BY id`, int64(job)) |
| 190 | if err != nil { |
| 191 | return current, err |
| 192 | } |
| 193 | defer rows.Close() |
| 194 | for rows.Next() { |
| 195 | var raw string |
| 196 | var p Provenance |
| 197 | if err := rows.Scan(&raw); err != nil { |
| 198 | return current, err |
| 199 | } |
| 200 | if strictJSON([]byte(raw), &p) != nil || p.validate() != nil || !p.Isolation.valid() { |
| 201 | return current, fail(CodeEvidence, "isolation_provenance_missing") |
| 202 | } |
| 203 | current = mergeIsolation(current, p.Isolation) |
| 204 | } |
| 205 | return current, rows.Err() |
| 206 | } |
| 207 | func (s *Store) observedProvenance(ctx context.Context, tx *sql.Tx, scope Scope, h Handle) (Provenance, error) { |
| 208 | if s.provenance == nil { |
| 209 | return Provenance{}, fail(CodeEvidence, "observed_provenance_missing") |
| 210 | } |
| 211 | p, err := s.provenance(ctx, tx, scope, h) |
| 212 | if err != nil { |
| 213 | return p, err |
| 214 | } |
| 215 | if p.validate() != nil || !p.Isolation.valid() { |
| 216 | return p, fail(CodeEvidence, "observed_provenance_invalid") |
| 217 | } |
| 218 | p.Isolation, err = lineageIsolation(ctx, tx, scope.Job, p.Isolation) |
| 219 | return p, err |
| 220 | } |
| 221 | func independentForPolicy(a, b Provenance, p Policy) bool { |
| 222 | if p.Version == 1 { |
| 223 | return independent(a, b, p.RequireDistinctReviewProvider) |
| 224 | } |
| 225 | // The trusted resolver supplies canonical known families, or an empty/unknown |
| 226 | // family when observation cannot identify one. Provider profiles are not families. |
| 227 | known := func(s string) bool { return s != "" && s != "unknown" && s != "unspecified" } |
| 228 | return independent(a, b, false) && known(a.ModelFamily) && known(b.ModelFamily) && a.ModelFamily != b.ModelFamily |
| 229 | } |
| 230 | func validateRepositoryChecks(payload []byte, cand *Artifact, j jobRow) error { |
| 231 | c, err := gitCandidate(cand, j) |
| 232 | if err != nil { |
| 233 | return err |
| 234 | } |
| 235 | var r RepositoryCheckResult |
| 236 | if strictJSON(payload, &r) != nil { |
| 237 | return fail(CodeEvidence, "repository_checks_invalid") |
| 238 | } |
| 239 | if r.CandidateHash != cand.Hash || r.Commit != c.Commit || r.CheckDefinitionHash != j.Evidence.CheckDefinitionHash || !lowerHex(r.CheckDefinitionHash, 64) || !lowerHex(r.LogHash, 64) || !lowerHex(r.BaselineTestSetHash, 64) || r.BaselineTestSetHash != j.Evidence.BaselineTestSetHash || !lowerHex(r.ObservedTestSetHash, 64) || r.Outcome != CheckPass || r.ExitCode != 0 || r.TestsRun <= 0 || r.TestsFailed != 0 { |
| 240 | return fail(CodeEvidence, "repository_checks_failed") |
| 241 | } |
| 242 | return nil |
| 243 | } |
| 244 | |
| 245 | // Evidence evaluates stored evidence without changing job state. |
| 246 | func (s *Store) Evidence(ctx context.Context, scope Scope) (EvidenceReport, error) { |
| 247 | return s.evidence(ctx, scope, false) |
| 248 | } |
| 249 | |
| 250 | // ReadyToPublish excludes only the publication receipt from the predicate. |
| 251 | func (s *Store) ReadyToPublish(ctx context.Context, scope Scope) (EvidenceReport, error) { |
| 252 | return s.evidence(ctx, scope, true) |
| 253 | } |
| 254 | func (s *Store) evidence(ctx context.Context, scope Scope, ready bool) (EvidenceReport, error) { |
| 255 | var rep EvidenceReport |
| 256 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 257 | j, err := loadJob(ctx, tx, scope) |
| 258 | if err != nil { |
| 259 | return err |
| 260 | } |
| 261 | rep, err = s.evaluateEvidence(ctx, tx, j, ready) |
| 262 | return err |
| 263 | }) |
| 264 | return rep, err |
| 265 | } |
| 266 | func (s *Store) evaluateEvidence(ctx context.Context, tx *sql.Tx, j jobRow, ready bool) (EvidenceReport, error) { |
| 267 | switch j.Evidence.Predicate { |
| 268 | case "": |
| 269 | if ready { |
| 270 | return EvidenceReport{Reason: "read_only"}, nil |
| 271 | } |
| 272 | return s.evaluateReadWork(ctx, tx, j) |
| 273 | case PredicateRenderedChange: |
| 274 | return s.evaluateRenderedChange(ctx, tx, j, ready) |
| 275 | case PredicateSoftwareFeature, PredicateSoftwareFix: |
| 276 | return evaluateSoftwareFix(ctx, tx, j, ready) |
| 277 | case PredicateAttestedReconciliation: |
| 278 | return evaluateReconciliation(ctx, tx, j) |
| 279 | default: |
| 280 | return EvidenceReport{}, fail(CodeUnknownKind, "predicate %q", j.Evidence.Predicate) |
| 281 | } |
| 282 | } |
| 283 | func publicationMatches(p publication, cand *Artifact, j jobRow) bool { |
| 284 | if cand == nil || p.Repository != j.Target.Repository || p.Ref != j.Target.Ref || p.Ref == j.Target.DefaultRef { |
| 285 | return false |
| 286 | } |
| 287 | if j.Policy.Version == 1 { |
| 288 | return p.Head == cand.Hash |
| 289 | } |
| 290 | c, err := gitCandidate(cand, j) |
| 291 | return err == nil && p.Head == c.Commit && p.CandidateHash == cand.Hash && p.Isolation.valid() |
| 292 | } |
| 293 | |
| 294 | func isolationContains(have, need IsolationSnapshot) bool { |
| 295 | if need.Mode != "" && have.Mode != need.Mode { |
| 296 | return false |
| 297 | } |
| 298 | if !profileApprovalsContain(have.ProfileApprovals, need.ProfileApprovals) || !trialContains(have.Trial, need.Trial) || !have.valid() || !need.valid() || need.RunnerTainted && !have.RunnerTainted { |
| 299 | return false |
| 300 | } |
| 301 | for _, id := range need.AcknowledgementIDs { |
| 302 | if !slices.Contains(have.AcknowledgementIDs, id) { |
| 303 | return false |
| 304 | } |
| 305 | } |
| 306 | for _, v := range need.ObservedTuples { |
| 307 | if !slices.Contains(have.ObservedTuples, v) { |
| 308 | return false |
| 309 | } |
| 310 | } |
| 311 | return true |
| 312 | } |
| 313 | |
| 314 | // Reject aliases and duplicate keys before canonicalization can erase them. |
| 315 | func gitCandidateFields(raw []byte) bool { |
| 316 | dec := json.NewDecoder(bytes.NewReader(raw)) |
| 317 | token, err := dec.Token() |
| 318 | if err != nil || token != json.Delim('{') { |
| 319 | return false |
| 320 | } |
| 321 | seen := map[string]bool{} |
| 322 | for dec.More() { |
| 323 | token, err := dec.Token() |
| 324 | if err != nil { |
| 325 | return false |
| 326 | } |
| 327 | key, ok := token.(string) |
| 328 | if !ok || seen[key] { |
| 329 | return false |
| 330 | } |
| 331 | switch key { |
| 332 | case "repository", "base_commit", "commit", "tree": |
| 333 | default: |
| 334 | return false |
| 335 | } |
| 336 | seen[key] = true |
| 337 | var value string |
| 338 | if dec.Decode(&value) != nil { |
| 339 | return false |
| 340 | } |
| 341 | } |
| 342 | token, err = dec.Token() |
| 343 | return err == nil && token == json.Delim('}') && len(seen) == 4 && jsonEnd(dec) == nil |
| 344 | } |
| 345 | |
| 346 | // IsolationContains checks that reported provenance retains the current exposure. |
| 347 | func IsolationContains(have, need IsolationSnapshot) bool { return isolationContains(have, need) } |
| 348 | |