cbm-attach 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cbm_attach/cli.py ADDED
@@ -0,0 +1,904 @@
1
+ """CBM attach CLI: verify | upload | finalize.
2
+
3
+ Every coded path writes a CBM report before exiting. The exit code and the
4
+ report status are one decision, made in one place, so a caller cannot see exit 3
5
+ with a PASS report or exit 0 with a FAIL report.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import re
14
+ import sys
15
+ import traceback
16
+ from dataclasses import dataclass
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from . import __version__, body
22
+ from .artifacts import (
23
+ Artifact,
24
+ fetch_artifact,
25
+ fetch_report,
26
+ locate_build_once_root,
27
+ verify_build_once,
28
+ )
29
+ from .gates import Evaluation, evaluate, upstream_summary
30
+ from .intoto import build_statement
31
+ from .reasons import (
32
+ CbmError,
33
+ GateError,
34
+ InputError,
35
+ Reason,
36
+ UploadError,
37
+ VerifyError,
38
+ )
39
+ from .reports import Report, artifact_hash_from_cbp, load_report
40
+ from .uploader import load_uploader
41
+
42
+
43
+ HEX40_RE = re.compile(r"^[a-fA-F0-9]{40}$")
44
+ REPO_RE = re.compile(r"^[^/\s]+/[^/\s]+$")
45
+ TAG_RE = re.compile(r"^v[0-9]+\.[0-9]+\.[0-9]+$")
46
+ VERSION_RE = re.compile(r"^v?[0-9]+\.[0-9]+\.[0-9]+$")
47
+
48
+ DEFAULT_REPORT = "cbm-evidence/cbm-report.json"
49
+ DEFAULT_BODY = "cbm-evidence/cbm-body.md"
50
+ DEFAULT_DECISION = "cbm-evidence/cbm-decision.json"
51
+ DEFAULT_FINAL_REPORT = "cbm-evidence/cbm-report.final.json"
52
+ DEFAULT_FINAL_BODY = "cbm-evidence/cbm-body.final.md"
53
+
54
+
55
+ @dataclass
56
+ class ReportContext:
57
+ now: str
58
+ version: str | None = None
59
+ tag: str | None = None
60
+ release_tag: str | None = None
61
+ declared_attached: bool = False
62
+ cbm_gate_status: str = "PRECONDITION_FAIL"
63
+ exit_code: int = 2
64
+ upload_status: str = "NOT_UPLOADED"
65
+ reason: str = Reason.SCHEMA_VIOLATION.value
66
+ reason_detail: str = ""
67
+ cbe: Report | None = None
68
+ cbp: Report | None = None
69
+ artifact: Artifact | None = None
70
+ upload_target: str | None = None
71
+ build_once_run_id: str | None = None
72
+ ci_commit_sha: str | None = None
73
+ uploaded_asset_url: str | None = None
74
+ uploaded_asset_digest: str | None = None
75
+
76
+
77
+ def _now(value: str | None) -> str:
78
+ if value:
79
+ return value
80
+ return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
81
+
82
+
83
+ def _canonical_sha256(report: dict[str, Any]) -> str:
84
+ payload = {key: value for key, value in report.items() if key != "evidence_sha256"}
85
+ raw = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
86
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()
87
+
88
+
89
+ def _seal(report: dict[str, Any]) -> dict[str, Any]:
90
+ sealed = dict(report)
91
+ sealed.pop("evidence_sha256", None)
92
+ sealed["evidence_sha256"] = _canonical_sha256(sealed)
93
+ return sealed
94
+
95
+
96
+ def _write_json(path: Path, data: dict[str, Any]) -> None:
97
+ path.parent.mkdir(parents=True, exist_ok=True)
98
+ temporary = path.with_name(path.name + ".tmp")
99
+ temporary.write_text(
100
+ json.dumps(data, indent=2, ensure_ascii=False) + "\n",
101
+ encoding="utf-8",
102
+ )
103
+ os.replace(temporary, path)
104
+
105
+
106
+ def _write_text(path: Path, text: str) -> None:
107
+ path.parent.mkdir(parents=True, exist_ok=True)
108
+ temporary = path.with_name(path.name + ".tmp")
109
+ temporary.write_text(text, encoding="utf-8")
110
+ os.replace(temporary, path)
111
+
112
+
113
+ def _write_evidence(
114
+ output: Path,
115
+ body_path: Path,
116
+ decision_path: Path,
117
+ report: dict[str, Any],
118
+ decision: dict[str, Any],
119
+ ) -> None:
120
+ _write_json(output, report)
121
+ _write_text(body_path, body.render_marked(report))
122
+ _write_json(decision_path, decision)
123
+
124
+
125
+ def _decision(report: dict[str, Any], choice: str, artifact: Artifact | None) -> dict[str, Any]:
126
+ return {
127
+ "decision": choice,
128
+ "reason": report.get("reason"),
129
+ "cbm_gate_status": report.get("cbm_gate_status"),
130
+ "upload_status": report.get("upload_status"),
131
+ "report_sha256": report.get("evidence_sha256"),
132
+ "artifact": (
133
+ {
134
+ "name": artifact.name,
135
+ "sha256": artifact.sha256,
136
+ }
137
+ if artifact is not None
138
+ else None
139
+ ),
140
+ }
141
+
142
+
143
+ def _require(value: str | None, name: str) -> str:
144
+ if value is None or not str(value).strip():
145
+ raise InputError(f"{name} is required", reason=Reason.MISSING_ARGUMENT)
146
+ return str(value).strip()
147
+
148
+
149
+ def _parse_bool(value: str | None, name: str, *, required: bool) -> bool:
150
+ if value is None or not str(value).strip():
151
+ if required:
152
+ raise InputError(f"{name} is required", reason=Reason.MISSING_DECLARED_ATTACHED)
153
+ return False
154
+ text = str(value).strip().lower()
155
+ if text not in {"true", "false"}:
156
+ raise InputError(
157
+ f"{name} must be 'true' or 'false', got {value!r}",
158
+ reason=Reason.SCHEMA_VIOLATION,
159
+ )
160
+ return text == "true"
161
+
162
+
163
+ def _parse_version(value: str | None, *, required: bool) -> str | None:
164
+ if value is None or not str(value).strip():
165
+ if required:
166
+ raise InputError("version is required", reason=Reason.MISSING_ARGUMENT)
167
+ return None
168
+ text = str(value).strip()
169
+ if not VERSION_RE.fullmatch(text):
170
+ raise InputError(
171
+ f"invalid version {text!r}; expected vX.Y.Z",
172
+ reason=Reason.SCHEMA_VIOLATION,
173
+ )
174
+ return text
175
+
176
+
177
+ def _parse_tag(value: str | None, name: str, *, required: bool) -> str | None:
178
+ if value is None or not str(value).strip():
179
+ if required:
180
+ raise InputError(f"{name} is required", reason=Reason.MISSING_ARGUMENT)
181
+ return None
182
+ text = str(value).strip()
183
+ if not TAG_RE.fullmatch(text):
184
+ raise InputError(
185
+ f"invalid {name} {text!r}; expected vX.Y.Z",
186
+ reason=Reason.SCHEMA_VIOLATION,
187
+ )
188
+ return text
189
+
190
+
191
+ def _parse_repo(value: str | None, *, required: bool) -> str | None:
192
+ if value is None or not str(value).strip():
193
+ if required:
194
+ raise InputError("repository is required", reason=Reason.MISSING_ARGUMENT)
195
+ return None
196
+ text = str(value).strip()
197
+ if not REPO_RE.fullmatch(text):
198
+ raise InputError(
199
+ f"invalid repository {text!r}; expected owner/name",
200
+ reason=Reason.SCHEMA_VIOLATION,
201
+ )
202
+ return text
203
+
204
+
205
+ def _parse_target(value: str | None, *, required: bool) -> str | None:
206
+ if value is None or not str(value).strip():
207
+ if required:
208
+ raise InputError("upload_target is required", reason=Reason.MISSING_ARGUMENT)
209
+ return None
210
+ text = str(value).strip()
211
+ if text not in {"github-release", "pypi"}:
212
+ raise InputError(
213
+ f"unsupported upload_target {text!r}",
214
+ reason=Reason.UNSUPPORTED_UPLOAD_TARGET,
215
+ )
216
+ return text
217
+
218
+
219
+ def _parse_ci_commit(value: str | None) -> str | None:
220
+ if value is None or not str(value).strip():
221
+ return None
222
+ text = str(value).strip()
223
+ if not HEX40_RE.fullmatch(text):
224
+ raise InputError(
225
+ f"invalid ci_commit_sha {text!r}; expected 40 hex characters",
226
+ reason=Reason.SCHEMA_VIOLATION,
227
+ )
228
+ return text.lower()
229
+
230
+
231
+ def _report_dict(ctx: ReportContext) -> dict[str, Any]:
232
+ cbp_artifact_sha = None
233
+ if ctx.cbp is not None and ctx.artifact is not None:
234
+ cbp_artifact_sha = artifact_hash_from_cbp(ctx.cbp, ctx.artifact.name)
235
+ return {
236
+ "schema_version": "1",
237
+ "package_id": "cbm",
238
+ "version": ctx.version,
239
+ "tag": ctx.tag,
240
+ "release_tag": ctx.release_tag,
241
+ "cbm_gate_status": ctx.cbm_gate_status,
242
+ "exit_code": ctx.exit_code,
243
+ "cbe_report_hash": ctx.cbe.sha256 if ctx.cbe is not None else None,
244
+ "cbp_report_hash": ctx.cbp.sha256 if ctx.cbp is not None else None,
245
+ "cbp_release_body_hash": (
246
+ ctx.cbp.data.get("release_body_hash") if ctx.cbp is not None else None
247
+ ),
248
+ "cbp_body_hash_scope": (
249
+ ctx.cbp.data.get("body_hash_scope") if ctx.cbp is not None else None
250
+ ),
251
+ "cbp_artifact_repository": (
252
+ ctx.cbp.data.get("artifact_repository") if ctx.cbp is not None else None
253
+ ),
254
+ "upload_status": ctx.upload_status,
255
+ "reason": ctx.reason,
256
+ "reason_detail": ctx.reason_detail,
257
+ "declared_attached": ctx.declared_attached,
258
+ "upstream_gate_status": upstream_summary(ctx.cbe, ctx.cbp),
259
+ "artifact_name": ctx.artifact.name if ctx.artifact is not None else None,
260
+ "artifact_sha256": ctx.artifact.sha256 if ctx.artifact is not None else None,
261
+ "cbp_artifact_sha256": cbp_artifact_sha,
262
+ "build_once_run_id": ctx.build_once_run_id,
263
+ "ci_commit_sha": ctx.ci_commit_sha,
264
+ "upload_target": ctx.upload_target,
265
+ "uploaded_asset_url": ctx.uploaded_asset_url,
266
+ "uploaded_asset_digest": ctx.uploaded_asset_digest,
267
+ "verified_at": ctx.now,
268
+ }
269
+
270
+
271
+ def _apply_error(ctx: ReportContext, error: CbmError) -> None:
272
+ ctx.cbm_gate_status = error.cbm_gate_status
273
+ ctx.upload_status = error.upload_status
274
+ ctx.reason = error.reason_value
275
+ ctx.reason_detail = error.detail
276
+ ctx.exit_code = error.exit_code
277
+
278
+
279
+ def _load_inputs(
280
+ args: argparse.Namespace,
281
+ workspace: Path,
282
+ ) -> tuple[Report | None, Report | None, Artifact | None]:
283
+ cbe: Report | None = None
284
+ cbp: Report | None = None
285
+ artifact: Artifact | None = None
286
+
287
+ if args.fetch:
288
+ artifact_repository = _require(
289
+ args.artifact_repository or args.repository,
290
+ "artifact_repository",
291
+ )
292
+ if args.build_once_run_id and args.build_once_artifact:
293
+ fetched = fetch_artifact(
294
+ repository=artifact_repository,
295
+ run_id=args.build_once_run_id,
296
+ artifact_name=args.build_once_artifact,
297
+ destination=workspace / "build-once",
298
+ missing_reason=Reason.MISSING_BUILD_ONCE_ARTIFACT,
299
+ gh_bin=args.gh_bin,
300
+ )
301
+ artifact = verify_build_once(locate_build_once_root(fetched))
302
+ if args.cbe_run_id and args.cbe_report_artifact:
303
+ cbe = fetch_report(
304
+ repository=artifact_repository,
305
+ run_id=args.cbe_run_id,
306
+ artifact_name=args.cbe_report_artifact,
307
+ kind="cbe",
308
+ destination=workspace / "cbe",
309
+ gh_bin=args.gh_bin,
310
+ )
311
+ if args.cbp_run_id and args.cbp_report_artifact:
312
+ cbp = fetch_report(
313
+ repository=artifact_repository,
314
+ run_id=args.cbp_run_id,
315
+ artifact_name=args.cbp_report_artifact,
316
+ kind="cbp",
317
+ destination=workspace / "cbp",
318
+ gh_bin=args.gh_bin,
319
+ )
320
+ else:
321
+ if args.build_once_dir:
322
+ artifact = verify_build_once(args.build_once_dir)
323
+ if args.cbe_report:
324
+ cbe = load_report(args.cbe_report, "cbe")
325
+ if args.cbp_report:
326
+ cbp = load_report(args.cbp_report, "cbp")
327
+ return cbe, cbp, artifact
328
+
329
+
330
+ def _verify(args: argparse.Namespace) -> int:
331
+ ctx = ReportContext(now=_now(args.now))
332
+ try:
333
+ ctx.version = _parse_version(args.version, required=True)
334
+ ctx.tag = _parse_tag(args.tag, "tag", required=True)
335
+ ctx.release_tag = _parse_tag(args.release_tag, "release_tag", required=True)
336
+ ctx.declared_attached = _parse_bool(
337
+ args.declared_attached, "declared_attached", required=True
338
+ )
339
+ ctx.upload_target = _parse_target(args.upload_target, required=True)
340
+ expected_artifact_repository = _parse_repo(
341
+ args.artifact_repository, required=ctx.declared_attached
342
+ )
343
+ ctx.build_once_run_id = args.build_once_run_id or None
344
+ ctx.ci_commit_sha = _parse_ci_commit(args.ci_commit_sha)
345
+
346
+ workspace = Path(args.workdir or ".cbm-incoming")
347
+ cbe, cbp, artifact = _load_inputs(args, workspace)
348
+ ctx.cbe, ctx.cbp, ctx.artifact = cbe, cbp, artifact
349
+
350
+ if ctx.declared_attached:
351
+ if cbe is None:
352
+ raise InputError(
353
+ "declared_attached=true but no CBE report was supplied",
354
+ reason=Reason.MISSING_CBE_REPORT,
355
+ )
356
+ if cbp is None:
357
+ raise InputError(
358
+ "declared_attached=true but no CBP manifest was supplied",
359
+ reason=Reason.MISSING_CBP_REPORT,
360
+ )
361
+ if artifact is None:
362
+ raise InputError(
363
+ "declared_attached=true but no build-once artifact was supplied",
364
+ reason=Reason.MISSING_BUILD_ONCE_ARTIFACT,
365
+ )
366
+
367
+ evaluation: Evaluation = evaluate(
368
+ cbe,
369
+ cbp,
370
+ version=ctx.version,
371
+ tag=ctx.tag,
372
+ declared_attached=ctx.declared_attached,
373
+ wheel_name=artifact.name if artifact is not None else None,
374
+ artifact_sha256=artifact.sha256 if artifact is not None else None,
375
+ expected_artifact_repository=expected_artifact_repository,
376
+ )
377
+ ctx.cbm_gate_status = evaluation.cbm_gate_status
378
+ ctx.upload_status = evaluation.upload_status
379
+ ctx.reason = evaluation.reason
380
+ ctx.reason_detail = evaluation.reason_detail
381
+ ctx.exit_code = evaluation.exit_code
382
+
383
+ report = _seal(_report_dict(ctx))
384
+ decision = _decision(
385
+ report,
386
+ "UPLOAD" if evaluation.upload_allowed else "NO_UPLOAD",
387
+ artifact,
388
+ )
389
+ _write_evidence(
390
+ Path(args.output),
391
+ Path(args.body),
392
+ Path(args.decision),
393
+ report,
394
+ decision,
395
+ )
396
+ _write_statement_for(report, args)
397
+ print(
398
+ "CBM_VERIFY "
399
+ f"decision={decision['decision']} "
400
+ f"cbm_gate_status={report['cbm_gate_status']} "
401
+ f"upload_status={report['upload_status']} "
402
+ f"reason={report['reason']}"
403
+ )
404
+ return evaluation.exit_code
405
+ except CbmError as error:
406
+ _apply_error(ctx, error)
407
+ report = _seal(_report_dict(ctx))
408
+ decision = _decision(report, "NO_UPLOAD", ctx.artifact)
409
+ _write_evidence(
410
+ Path(args.output),
411
+ Path(args.body),
412
+ Path(args.decision),
413
+ report,
414
+ decision,
415
+ )
416
+ _write_statement_for(report, args)
417
+ print(f"{error.reason_value}: {error.detail}", file=sys.stderr)
418
+ return error.exit_code
419
+ except Exception as error: # noqa: BLE001 - evidence must survive unknown failures
420
+ ctx.cbm_gate_status = "FAIL"
421
+ ctx.exit_code = 3
422
+ ctx.upload_status = "NOT_UPLOADED"
423
+ ctx.reason = Reason.INTERNAL_ERROR.value
424
+ ctx.reason_detail = f"{type(error).__name__}: {error}"
425
+ report = _seal(_report_dict(ctx))
426
+ decision = _decision(report, "NO_UPLOAD", ctx.artifact)
427
+ _write_evidence(
428
+ Path(args.output),
429
+ Path(args.body),
430
+ Path(args.decision),
431
+ report,
432
+ decision,
433
+ )
434
+ traceback.print_exc()
435
+ return 3
436
+
437
+
438
+ def _load_json(path: str | Path, *, what: str) -> dict[str, Any]:
439
+ candidate = Path(path)
440
+ if not candidate.is_file():
441
+ raise InputError(f"{candidate}: {what} not found", reason=Reason.MISSING_EVIDENCE)
442
+ try:
443
+ data = json.loads(candidate.read_text(encoding="utf-8"))
444
+ except (OSError, json.JSONDecodeError) as error:
445
+ raise InputError(
446
+ f"{candidate}: cannot read {what}: {error}",
447
+ reason=Reason.INVALID_JSON,
448
+ ) from error
449
+ if not isinstance(data, dict):
450
+ raise InputError(f"{candidate}: {what} must be a JSON object", reason=Reason.INVALID_JSON)
451
+ return data
452
+
453
+
454
+ def _check_upload_approval(report: dict[str, Any], decision: dict[str, Any]) -> None:
455
+ if not _evidence_hash_ok(report):
456
+ raise GateError(
457
+ "report evidence_sha256 does not match its contents",
458
+ reason=Reason.EVIDENCE_INVALID,
459
+ )
460
+ if decision.get("report_sha256") != report.get("evidence_sha256"):
461
+ raise GateError(
462
+ "decision is not bound to this report",
463
+ reason=Reason.EVIDENCE_INVALID,
464
+ )
465
+ if decision.get("decision") != "UPLOAD":
466
+ raise GateError(
467
+ f"decision={decision.get('decision')!r}; upload is not approved",
468
+ reason=Reason.UPLOAD_NOT_APPROVED,
469
+ )
470
+ if report.get("cbm_gate_status") != "NOT_UPLOADED":
471
+ raise GateError(
472
+ f"cbm_gate_status={report.get('cbm_gate_status')!r}; upload is not approved",
473
+ reason=Reason.UPLOAD_NOT_APPROVED,
474
+ )
475
+ if report.get("upload_status") != "NOT_UPLOADED":
476
+ raise GateError(
477
+ f"upload_status={report.get('upload_status')!r}; upload is not approved",
478
+ reason=Reason.UPLOAD_NOT_APPROVED,
479
+ )
480
+ if report.get("reason") != Reason.UPLOAD_PENDING.value:
481
+ raise GateError(
482
+ f"reason={report.get('reason')!r}; upload is not approved",
483
+ reason=Reason.UPLOAD_NOT_APPROVED,
484
+ )
485
+ if report.get("artifact_sha256") is None:
486
+ raise GateError(
487
+ "report has no artifact_sha256",
488
+ reason=Reason.MISSING_BUILD_ONCE_ARTIFACT,
489
+ )
490
+
491
+
492
+ def _verify_artifact_against_report(report: dict[str, Any], artifact: Artifact) -> None:
493
+ expected = report.get("artifact_sha256")
494
+ if expected != artifact.sha256:
495
+ raise GateError(
496
+ f"build-once parser saw {artifact.sha256} but the approved report says {expected}",
497
+ reason=Reason.ARTIFACT_HASH_MISMATCH,
498
+ )
499
+ cbp_expected = report.get("cbp_artifact_sha256")
500
+ if cbp_expected is not None and cbp_expected != artifact.sha256:
501
+ raise GateError(
502
+ f"build-once parser saw {artifact.sha256} but CBP said {cbp_expected}",
503
+ reason=Reason.ARTIFACT_HASH_MISMATCH,
504
+ )
505
+
506
+
507
+ def _upload(args: argparse.Namespace) -> int:
508
+ report = _load_json(args.report, what="CBM report")
509
+ decision = _load_json(args.decision, what="CBM decision")
510
+ now = _now(args.now)
511
+ try:
512
+ _check_upload_approval(report, decision)
513
+ if args.fetch:
514
+ artifact_repository = _require(
515
+ args.artifact_repository or args.repository,
516
+ "artifact_repository",
517
+ )
518
+ run_id = args.build_once_run_id or report.get("build_once_run_id")
519
+ artifact_name = args.build_once_artifact or f"cbm-build-once"
520
+ if not run_id:
521
+ raise InputError(
522
+ "build_once_run_id is required to fetch the artifact",
523
+ reason=Reason.MISSING_BUILD_ONCE_ARTIFACT,
524
+ )
525
+ fetched = fetch_artifact(
526
+ repository=artifact_repository,
527
+ run_id=str(run_id),
528
+ artifact_name=artifact_name,
529
+ destination=Path(args.workdir or ".cbm-incoming") / "upload-build-once",
530
+ missing_reason=Reason.MISSING_BUILD_ONCE_ARTIFACT,
531
+ gh_bin=args.gh_bin,
532
+ )
533
+ artifact = verify_build_once(locate_build_once_root(fetched))
534
+ else:
535
+ if not args.build_once_dir:
536
+ raise InputError(
537
+ "build_once_dir is required to re-verify the artifact",
538
+ reason=Reason.MISSING_BUILD_ONCE_ARTIFACT,
539
+ )
540
+ artifact = verify_build_once(args.build_once_dir)
541
+
542
+ _verify_artifact_against_report(report, artifact)
543
+
544
+ target = _parse_target(
545
+ args.upload_target or report.get("upload_target"),
546
+ required=True,
547
+ )
548
+ repository = _parse_repo(args.repository, required=target == "github-release")
549
+ release_tag = _parse_tag(
550
+ args.release_tag or report.get("release_tag"),
551
+ "release_tag",
552
+ required=target == "github-release",
553
+ )
554
+ uploader = load_uploader(
555
+ target,
556
+ repository=repository or "",
557
+ release_tag=release_tag or "",
558
+ wheel_name=artifact.name,
559
+ gh_bin=args.gh_bin,
560
+ twine_bin=args.twine_bin,
561
+ )
562
+
563
+ existing = uploader.get_digest(artifact.name)
564
+ if existing == artifact.sha256:
565
+ remote = existing
566
+ uploaded_url = uploader.get_url(artifact.name)
567
+ elif existing is not None:
568
+ raise UploadError(
569
+ f"remote asset {artifact.name!r} has sha256 {existing}, not {artifact.sha256}",
570
+ reason=Reason.ASSET_DIGEST_CONFLICT,
571
+ )
572
+ else:
573
+ uploader.upload(artifact.path, artifact.name)
574
+ remote = uploader.get_digest(artifact.name)
575
+ if remote != artifact.sha256:
576
+ report["uploaded_asset_digest"] = remote
577
+ raise VerifyError(
578
+ f"remote digest {remote!r} != local {artifact.sha256}",
579
+ reason=Reason.UPLOAD_VERIFY_FAILED,
580
+ )
581
+ uploaded_url = uploader.get_url(artifact.name)
582
+
583
+ report["cbm_gate_status"] = "PASS"
584
+ report["upload_status"] = "UPLOADED_VERIFIED"
585
+ report["reason"] = Reason.UPLOADED_VERIFIED.value
586
+ report["reason_detail"] = "uploaded asset digest verified"
587
+ report["exit_code"] = 0
588
+ report["uploaded_asset_digest"] = remote
589
+ report["uploaded_asset_url"] = uploaded_url
590
+ report["verified_at"] = now
591
+ sealed = _seal(report)
592
+ _write_json(Path(args.output), sealed)
593
+ _write_text(Path(args.body), body.render_marked(sealed))
594
+ _write_statement_for(sealed, args)
595
+ print(
596
+ "CBM_UPLOAD "
597
+ f"cbm_gate_status=PASS upload_status=UPLOADED_VERIFIED "
598
+ f"asset={artifact.name} sha256={artifact.sha256}"
599
+ )
600
+ return 0
601
+ except CbmError as error:
602
+ report["cbm_gate_status"] = error.cbm_gate_status
603
+ report["upload_status"] = error.upload_status
604
+ report["reason"] = error.reason_value
605
+ report["reason_detail"] = error.detail
606
+ report["exit_code"] = error.exit_code
607
+ report["verified_at"] = now
608
+ if error.upload_status != "UPLOADED_VERIFIED":
609
+ report["uploaded_asset_url"] = None
610
+ sealed = _seal(report)
611
+ _write_json(Path(args.output), sealed)
612
+ _write_text(Path(args.body), body.render_marked(sealed))
613
+ _write_statement_for(sealed, args)
614
+ print(f"{error.reason_value}: {error.detail}", file=sys.stderr)
615
+ return error.exit_code
616
+ except Exception as error: # noqa: BLE001
617
+ report["cbm_gate_status"] = "FAIL"
618
+ report["upload_status"] = "NOT_UPLOADED"
619
+ report["reason"] = Reason.INTERNAL_ERROR.value
620
+ report["reason_detail"] = f"{type(error).__name__}: {error}"
621
+ report["exit_code"] = 3
622
+ report["verified_at"] = now
623
+ sealed = _seal(report)
624
+ _write_json(Path(args.output), sealed)
625
+ _write_text(Path(args.body), body.render_marked(sealed))
626
+ traceback.print_exc()
627
+ return 3
628
+
629
+
630
+ def _evidence_hash_ok(report: dict[str, Any]) -> bool:
631
+ stored = report.get("evidence_sha256")
632
+ if not isinstance(stored, str):
633
+ return False
634
+ return _canonical_sha256(report) == stored
635
+
636
+
637
+ def _consistent_pass(report: dict[str, Any]) -> bool:
638
+ gate = report.get("cbm_gate_status")
639
+ upload = report.get("upload_status")
640
+ if gate == "PASS" and upload != "UPLOADED_VERIFIED":
641
+ return False
642
+ if upload == "UPLOADED_VERIFIED" and gate != "PASS":
643
+ return False
644
+ return True
645
+
646
+
647
+ def _failure_report(
648
+ ctx: ReportContext,
649
+ *,
650
+ reason: Reason,
651
+ detail: str,
652
+ status: str = "FAIL",
653
+ exit_code: int = 3,
654
+ ) -> dict[str, Any]:
655
+ ctx.cbm_gate_status = status
656
+ ctx.exit_code = exit_code
657
+ ctx.upload_status = "NOT_UPLOADED"
658
+ ctx.reason = reason.value
659
+ ctx.reason_detail = detail
660
+ ctx.uploaded_asset_url = None
661
+ ctx.uploaded_asset_digest = None
662
+ return _seal(_report_dict(ctx))
663
+
664
+
665
+ def _finalize(args: argparse.Namespace) -> int:
666
+ now = _now(args.now)
667
+ ctx = ReportContext(now=now)
668
+ try:
669
+ ctx.version = _parse_version(args.version, required=False)
670
+ ctx.tag = _parse_tag(args.tag, "tag", required=False)
671
+ ctx.release_tag = _parse_tag(args.release_tag, "release_tag", required=False)
672
+ ctx.declared_attached = _parse_bool(
673
+ args.declared_attached, "declared_attached", required=False
674
+ )
675
+ except CbmError as error:
676
+ _apply_error(ctx, error)
677
+ report = _failure_report(
678
+ ctx,
679
+ reason=error.reason,
680
+ detail=error.detail,
681
+ status=error.cbm_gate_status,
682
+ exit_code=error.exit_code,
683
+ )
684
+ _write_json(Path(args.output), report)
685
+ _write_text(Path(args.body), body.render_marked(report))
686
+ _export_outputs(report)
687
+ print(f"{error.reason_value}: {error.detail}", file=sys.stderr)
688
+ return 0
689
+
690
+ input_dir = Path(args.input)
691
+ candidates = (
692
+ [path for path in input_dir.rglob("cbm-report*.json") if path.is_file()]
693
+ if input_dir.is_dir()
694
+ else []
695
+ )
696
+ chosen: Path | None = None
697
+ for preferred in ("cbm-report.final.json", "cbm-report.json"):
698
+ matches = [path for path in candidates if path.name == preferred]
699
+ if matches:
700
+ chosen = max(matches, key=lambda path: path.stat().st_mtime)
701
+ break
702
+ if chosen is None and candidates:
703
+ chosen = max(candidates, key=lambda path: path.stat().st_mtime)
704
+
705
+ report: dict[str, Any]
706
+ if chosen is None:
707
+ report = _failure_report(
708
+ ctx,
709
+ reason=Reason.EVIDENCE_ABSENT,
710
+ detail="no CBM report was produced before finalization; WORKFLOW_FAILED_BEFORE_EVIDENCE",
711
+ status="SKIPPED_INFRA",
712
+ exit_code=3,
713
+ )
714
+ else:
715
+ try:
716
+ base = _load_json(chosen, what="CBM report")
717
+ except CbmError as error:
718
+ report = _failure_report(
719
+ ctx,
720
+ reason=error.reason,
721
+ detail=error.detail,
722
+ status="FAIL",
723
+ exit_code=3,
724
+ )
725
+ else:
726
+ if not _evidence_hash_ok(base):
727
+ report = _failure_report_from_base(
728
+ base,
729
+ now,
730
+ reason=Reason.EVIDENCE_INVALID,
731
+ detail="evidence_sha256 does not match the report contents",
732
+ )
733
+ elif not _consistent_pass(base):
734
+ report = _failure_report_from_base(
735
+ base,
736
+ now,
737
+ reason=Reason.EVIDENCE_INVALID,
738
+ detail="PASS/upload status contradiction",
739
+ )
740
+ else:
741
+ report = dict(base)
742
+ upload_result = (args.upload_result or "").lower()
743
+ if upload_result and report.get("reason") == Reason.UPLOAD_PENDING.value:
744
+ report = _failure_report_from_base(
745
+ report,
746
+ now,
747
+ reason=Reason.UPLOAD_FAILED,
748
+ detail=f"upload job result={upload_result}",
749
+ )
750
+ report["verified_at"] = report.get("verified_at") or now
751
+ report = _seal(report)
752
+
753
+ _write_json(Path(args.output), report)
754
+ _write_text(Path(args.body), body.render_marked(report))
755
+ _export_outputs(report)
756
+ print(
757
+ "CBM_FINALIZE "
758
+ f"cbm_gate_status={report.get('cbm_gate_status')} "
759
+ f"upload_status={report.get('upload_status')} "
760
+ f"reason={report.get('reason')}"
761
+ )
762
+ return 0
763
+
764
+
765
+ def _failure_report_from_base(
766
+ base: dict[str, Any],
767
+ now: str,
768
+ *,
769
+ reason: Reason,
770
+ detail: str,
771
+ ) -> dict[str, Any]:
772
+ report = dict(base)
773
+ report["cbm_gate_status"] = "FAIL"
774
+ report["exit_code"] = 3
775
+ report["upload_status"] = "NOT_UPLOADED"
776
+ report["reason"] = reason.value
777
+ report["reason_detail"] = detail
778
+ report["uploaded_asset_url"] = None
779
+ report["uploaded_asset_digest"] = None
780
+ report["verified_at"] = now
781
+ return _seal(report)
782
+
783
+
784
+ def _export_outputs(report: dict[str, Any]) -> None:
785
+ destination = os.environ.get("GITHUB_OUTPUT")
786
+ if not destination:
787
+ return
788
+ values = {
789
+ "cbm_gate_status": report.get("cbm_gate_status") or "",
790
+ "upload_status": report.get("upload_status") or "",
791
+ "cbe_report_hash": report.get("cbe_report_hash") or "",
792
+ "cbp_report_hash": report.get("cbp_report_hash") or "",
793
+ }
794
+ with open(destination, "a", encoding="utf-8") as handle:
795
+ for key, value in values.items():
796
+ handle.write(f"{key}={value}\n")
797
+
798
+
799
+ def _write_statement_for(report: dict[str, Any], args: argparse.Namespace) -> Path:
800
+ """Write the in-toto Statement next to the report unless overridden."""
801
+ output = Path(args.output)
802
+ path = Path(args.statement) if getattr(args, "statement", "") else output.with_name(output.stem + ".statement.json")
803
+ _write_json(path, build_statement(report))
804
+ return path
805
+
806
+
807
+ def _build_parser() -> argparse.ArgumentParser:
808
+ parser = argparse.ArgumentParser(prog="cbm_attach")
809
+ parser.add_argument("--version", action="version", version=f"cbm-attach {__version__}")
810
+ sub = parser.add_subparsers(dest="command")
811
+
812
+ verify = sub.add_parser("verify", help="consume CBE/CBP and decide upload")
813
+ verify.add_argument("--version")
814
+ verify.add_argument("--tag")
815
+ verify.add_argument("--release-tag")
816
+ verify.add_argument("--declared-attached")
817
+ verify.add_argument("--upload-target")
818
+ verify.add_argument("--repository")
819
+ verify.add_argument("--artifact-repository")
820
+ verify.add_argument("--cbm-repository")
821
+ verify.add_argument("--ci-commit-sha")
822
+ verify.add_argument("--cbe-report")
823
+ verify.add_argument("--cbp-report")
824
+ verify.add_argument("--build-once-dir")
825
+ verify.add_argument("--cbe-run-id")
826
+ verify.add_argument("--cbe-report-artifact")
827
+ verify.add_argument("--cbp-run-id")
828
+ verify.add_argument("--cbp-report-artifact")
829
+ verify.add_argument("--build-once-run-id")
830
+ verify.add_argument("--build-once-artifact")
831
+ verify.add_argument("--fetch", action="store_true")
832
+ verify.add_argument("--workdir", default=".cbm-incoming")
833
+ verify.add_argument("--gh-bin", default="gh")
834
+ verify.add_argument("--output", default=DEFAULT_REPORT)
835
+ verify.add_argument("--body", default=DEFAULT_BODY)
836
+ verify.add_argument("--decision", default=DEFAULT_DECISION)
837
+ verify.add_argument("--statement", default="")
838
+ verify.add_argument("--now")
839
+
840
+ upload = sub.add_parser("upload", help="upload the approved build-once asset")
841
+ upload.add_argument("--report", default=DEFAULT_REPORT)
842
+ upload.add_argument("--decision", default=DEFAULT_DECISION)
843
+ upload.add_argument("--build-once-dir")
844
+ upload.add_argument("--build-once-run-id")
845
+ upload.add_argument("--build-once-artifact", default="cbm-build-once")
846
+ upload.add_argument("--fetch", action="store_true")
847
+ upload.add_argument("--workdir", default=".cbm-incoming")
848
+ upload.add_argument("--repository")
849
+ upload.add_argument("--artifact-repository")
850
+ upload.add_argument("--release-tag")
851
+ upload.add_argument("--upload-target")
852
+ upload.add_argument("--gh-bin", default="gh")
853
+ upload.add_argument("--twine-bin", default="twine")
854
+ upload.add_argument("--output", default=DEFAULT_FINAL_REPORT)
855
+ upload.add_argument("--body", default=DEFAULT_FINAL_BODY)
856
+ upload.add_argument("--statement", default="")
857
+ upload.add_argument("--now")
858
+
859
+ finalize = sub.add_parser("finalize", help="emit the final report and body fragment")
860
+ finalize.add_argument("--input", default="cbm-evidence")
861
+ finalize.add_argument("--output", default="cbm-evidence-out/cbm-report.json")
862
+ finalize.add_argument("--body", default="cbm-evidence-out/cbm-body.md")
863
+ finalize.add_argument("--declared-attached")
864
+ finalize.add_argument("--version")
865
+ finalize.add_argument("--tag")
866
+ finalize.add_argument("--release-tag")
867
+ finalize.add_argument("--upload-result")
868
+ finalize.add_argument("--now")
869
+
870
+ statement = sub.add_parser("statement", help="write an in-toto Statement from a CBM report")
871
+ statement.add_argument("--report", default=DEFAULT_REPORT)
872
+ statement.add_argument("--output", default="")
873
+
874
+ return parser
875
+
876
+
877
+ def main(argv: list[str] | None = None) -> int:
878
+ parser = _build_parser()
879
+ args = parser.parse_args(argv)
880
+ if not getattr(args, "command", None):
881
+ parser.print_help(sys.stderr)
882
+ return 2
883
+ try:
884
+ if args.command == "verify":
885
+ return _verify(args)
886
+ if args.command == "upload":
887
+ return _upload(args)
888
+ if args.command == "finalize":
889
+ return _finalize(args)
890
+ if args.command == "statement":
891
+ report = json.loads(Path(args.report).read_text(encoding="utf-8"))
892
+ output = Path(args.output) if args.output else Path(args.report).with_name(Path(args.report).stem + ".statement.json")
893
+ _write_json(output, build_statement(report))
894
+ print(f"CBM_STATEMENT {output}")
895
+ return 0
896
+ parser.print_help(sys.stderr)
897
+ return 2
898
+ except OSError as error:
899
+ print(f"CBM_EVIDENCE_WRITE_FAILED: {error}", file=sys.stderr)
900
+ return 3
901
+
902
+
903
+ if __name__ == "__main__": # pragma: no cover
904
+ raise SystemExit(main())