"""Harbor collection command, executed only inside the trusted team service.""" from __future__ import annotations import argparse import json import os import tempfile import urllib.request from pathlib import Path def export_evidence(destination: Path, *, timeout: float | None = None) -> dict: request = urllib.request.Request( "http://127.0.0.1:8001/finalize", data=b"{}", headers={"Content-Type": "application/json"}, method="POST", ) with urllib.request.urlopen(request, timeout=timeout) as response: envelope = json.load(response) if not isinstance(envelope, dict) or envelope.get("schema_version") != 1: raise ValueError("Team service did not return a versioned evidence envelope") destination.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile("w", dir=destination.parent, delete=False) as stream: temporary = Path(stream.name) try: json.dump(envelope, stream, ensure_ascii=False, allow_nan=False) stream.write("\n") stream.flush() os.fsync(stream.fileno()) except BaseException: temporary.unlink(missing_ok=True) raise temporary.replace(destination) return envelope def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, default=Path("/evidence/final.json")) parser.add_argument("--timeout", type=float, default=None) args = parser.parse_args(argv) export_evidence(args.output, timeout=args.timeout) if __name__ == "__main__": main()