diff --git a/.github/workflows/agentic-datacenter-benchmark-conformance.yml b/.github/workflows/agentic-datacenter-benchmark-conformance.yml new file mode 100644 index 0000000..37328f1 --- /dev/null +++ b/.github/workflows/agentic-datacenter-benchmark-conformance.yml @@ -0,0 +1,60 @@ +# Agentic-Datacenter benchmark result references workflow. +# +# floating installs the latest released agentrust-trace, unpinned on purpose, +# as drift detection. +# fixed installs the agentrust-trace version named in integration.yaml +# tested_against, so that claim cannot move underneath itself. +# Both also resolve a real published record (--online); the examples cite a synthetic one. +# This integration is an external-evidence-source and asserts no TRACE level. +name: agentic-datacenter-benchmark conformance +on: + push: + paths: + - "integrations/agentic-datacenter-benchmark/**" + - ".github/workflows/agentic-datacenter-benchmark-conformance.yml" + pull_request: + paths: + - "integrations/agentic-datacenter-benchmark/**" + - ".github/workflows/agentic-datacenter-benchmark-conformance.yml" + schedule: + - cron: "0 6 * * 1" # weekly: catch drift against the latest released packages + workflow_dispatch: + +permissions: + contents: read + +jobs: + check: + name: ${{ matrix.mode }} (py${{ matrix.python }}) + strategy: + fail-fast: false + matrix: + python: ["3.11", "3.12", "3.13"] + mode: [floating, fixed] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # The job runs a pull request's code: keep no token in .git/config. + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ matrix.python }} + - name: Install agentrust-trace (latest release) + if: matrix.mode == 'floating' + run: pip install agentrust-trace + - name: Install agentrust-trace (tested_against) + if: matrix.mode == 'fixed' + run: | + v=$(sed -n 's/^ agentrust-trace: "\(.*\)"$/\1/p' integrations/agentic-datacenter-benchmark/integration.yaml) + test -n "$v" + pip install "agentrust-trace==$v" + - name: Install this integration + run: pip install -e "integrations/agentic-datacenter-benchmark[test]" + - name: Integration tests, resolving the published record + # The attestation lookup asks api.github.com. Without a token GitHub counts it + # against the runner's address, which other jobs share; with the job's own + # read-only token it is counted against this repository. + env: + GITHUB_TOKEN: ${{ github.token }} + run: pytest integrations/agentic-datacenter-benchmark/tests -q --online diff --git a/README.md b/README.md index 55c889b..17d080c 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ TRACE only works as a standard if it is genuinely neutral. Integrations are list |---|---|---|---| | [claude-code](claude-code/) | agentrust-io | agent-manifest, trace | community | | [Agent Passport System](integrations/aeoess-aps/) | aeoess | trace | verified | +| [Agentic-Datacenter benchmark result references](integrations/agentic-datacenter-benchmark/) | Agentic-Datacenter | trace | community | | [cA2A Cross-Operator Delegation](integrations/agentrust-ca2a-cross-operator/) | agentrust-io | ca2a | community | | [Confidential Workflow Acceptance Harness](integrations/agentrust-confidential-workflow-harness/) | agentrust-io | cmcp, ca2a, trace | community | | [AAIF Authority Comparison Runner](integrations/alakris-authority-comparison/) | Alakris Research | trace | community | diff --git a/integrations/agentic-datacenter-benchmark/README.md b/integrations/agentic-datacenter-benchmark/README.md new file mode 100644 index 0000000..ecd0d98 --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/README.md @@ -0,0 +1,51 @@ +# Agentic-Datacenter benchmark result references + +[Agentic-Datacenter](https://github.com/agentic-datacenter/agentic-datacenter) is a simulated datacenter in which an AI agent proposes operating steps and a governance gate decides on each one. A benchmark run writes, beside its result card, a record of the code commit and of the SHA-256 of every file it made (`provenance.json`), and the workflow that ran it attests that record with a GitHub artifact attestation. This integration lets a TRACE Trust Record of a governance gate cite such a result: one `references` entry with `rel: "benchmark-result"` whose `id` is the raw URL of `provenance.json` at a fixed commit and whose `digest` pins its bytes. + +## What it does + +- `adc_reference.py make ` prints the entry for a record at a commit. It checks the URL before fetching anything: https, `raw.githubusercontent.com`, a 40-character commit, no `.`, `..` or empty path segment. It accepts only what a benchmark result writes: schema `adc-provenance/v1`, product `Agentic-Datacenter`, the label `benchmark result` exactly (a frozen run with a language-model agent, or on a facility of its owner, keeps `frozen: true` but has another label and is not a benchmark result), `benchmark_version` with `frozen: true`, a 40-character `code_commit`, and `files` naming `result_card.json`, each file by a plain relative name with its SHA-256. A body larger than 64 MiB is refused, not cut. A redirect is followed only to a URL that could have been fetched itself, and an `http.client` error is reported like any other failure to resolve. The entry's `resolver` is the repository the record is kept in, the one its URL names. +- `adc_reference.py check ` resolves the entry and checks that its resolver is the repository the URL names, that the bytes are the cited bytes and that they are such a record. `--file result_card.json` (or any file the record lists) also checks that file against the hash the record gives it. `--attestations` asks the GitHub API for the attestations of the record, and holds only one whose statement names the record's digest as its subject, a workflow of the resolver's repository as the one that made it, the ref it ran from, and the builder `{repository}/{path}@{ref}` exactly. The ref is part of the policy, because a branch, a pull request or a tag can change what a workflow runs: + - for `agentic-datacenter/agentic-datacenter`, the workflow must be `.github/workflows/bench-runner.yml` run from `refs/heads/main`; + - for any other repository, any workflow of that repository run from its default branch, which the check asks the GitHub API for (`refs/heads/`). An attestation from another branch, `refs/pull/…` or `refs/tags/…` does not count. + + Otherwise it reports which workflows, at which refs, made the attestations it found. A lookup GitHub refuses is reported with its status (`attestations unresolved: HTTPError 403`). The GitHub API limits requests without a token by address, so on a shared address such as a CI runner's set `GITHUB_TOKEN` or `GH_TOKEN`: the token is sent to `api.github.com` only, never with a request for a raw file and never with a redirect. +- `examples/` holds two Trust Records signed by a demo key derived from a published seed, each citing a record: one whose digest matches and one whose digest does not. The record they cite, `source/provenance.json`, is synthetic: made for this example in the schema a benchmark run writes, with plainly fake values, and not the record of any run. All of it regenerates with `examples/make_examples.py`. +- `tests/` verifies both records with released `agentrust-trace`, validates the entry against its `Reference` model, and checks each case offline against the synthetic record. With `--online`, one test makes an entry for [a real published record](https://raw.githubusercontent.com/agentic-datacenter/agentic-datacenter/d00a805e7f661ff083e29060a7198d0853bf4075/results/remora/benchmark-v1.7-statements-only/provenance.json) at a fixed commit and resolves it, a file it lists and its attestation. + +## Run it + +``` +pip install -e "integrations/agentic-datacenter-benchmark[test]" +python -m pytest integrations/agentic-datacenter-benchmark/tests --online +python integrations/agentic-datacenter-benchmark/adc_reference.py check entry.json --file result_card.json --attestations +``` + +`check` exits 0 when the entry resolves, 1 when it finds problems, and 2 when it cannot run: an entry file that is missing, not JSON, or not a JSON object. `make` exits 2 on any failure. + +To get a result of your own gate to cite, run the benchmark from your repository with Agentic-Datacenter's [participant workflow](https://github.com/agentic-datacenter/agentic-datacenter/blob/main/examples/ci/agentic-datacenter.yml), which records and attests the result in your repository ([how a gate connects](https://github.com/agentic-datacenter/agentic-datacenter/blob/main/docs/guides/bring-your-own-gate.md)). + +### From the attested run to a URL at a commit + +The participant workflow attests `bench/provenance.json` and uploads a reportable result as the artifact `agentic-datacenter-stable-result-`, with the result's files in its `bench/` folder; it does not commit it. Downloaded by name with `--dir result-artifact`, the files are in `result-artifact/bench/`. Run the workflow from your default branch, since an attestation from any other ref does not count. To cite the result, put the attested bytes in your repository, byte for byte, at a fixed commit: + +``` +gh run download --repo / --name agentic-datacenter-stable-result- --dir result-artifact +gh attestation verify result-artifact/bench/provenance.json --repo / +mkdir -p results/ && cp result-artifact/bench/* results// +git add results/ && git commit -m "Benchmark result " && git push +``` + +A result of Agentic-Datacenter's own `bench-runner.yml` is the artifact `bench-`, with its files at the top level: download it with `--name bench-`, and the files are `result-artifact/provenance.json` and the others beside it. + +Copy the files as they are: no formatting, no line-ending conversion (if your repository sets `text=auto`, mark the folder `-text` in `.gitattributes`). `gh attestation verify` checks the signature and which workflow and run made the record; run it again on the committed file to see that the bytes did not change. Then cite the record at that commit: + +``` +python adc_reference.py make https://raw.githubusercontent.com///<40-character commit>/results//provenance.json +``` + +The entry's `resolver` is then `https://github.com//`: your repository keeps the bytes. A record anyone could commit is not evidence by itself; `check --attestations` asks GitHub whether that repository holds an attestation of it, and `gh attestation verify` shows by which run. + +## What it does NOT claim + +A resolved entry establishes that the resolved bytes are the cited bytes, and that they are the record of an Agentic-Datacenter result. It does not establish that the gate behaved as the result says: the result is a simulation, and an attestation shows which workflow made the files, not that the gate under test is what the card says it is. `--attestations` reads the statement of each attestation GitHub returns for the digest in the resolver's repository, and reports a lookup that fails as a problem. It does not verify the signature over that statement or its certificate, so it relies on GitHub's answer for which workflow signed; `gh attestation verify provenance.json --repo --signer-workflow /.github/workflows/` verifies both. An entry never changes whether the Trust Record itself verifies (trace-v0.2 section 3.1.2). The `benchmark-result` value of `rel` is not registered. No TRACE conformance level is claimed. diff --git a/integrations/agentic-datacenter-benchmark/adc_reference.py b/integrations/agentic-datacenter-benchmark/adc_reference.py new file mode 100644 index 0000000..b861771 --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/adc_reference.py @@ -0,0 +1,353 @@ +"""Cite a published Agentic-Datacenter benchmark result from a TRACE Trust Record. + +An Agentic-Datacenter benchmark run writes, beside its result card, a record of the +code commit and of the SHA-256 of every file it made (``provenance.json``), and the +workflow that ran it attests that record with a GitHub artifact attestation. This +module makes a TRACE ``references`` entry that points at such a record by a URL fixed +to one commit, and checks an entry: the bytes it resolves to are the cited bytes, they +are an Agentic-Datacenter record that lists a result card, and any file of the result +that is resolved matches the hash the record gives it. + + python adc_reference.py make + python adc_reference.py check [--file result_card.json] [--attestations] + +What a check establishes is that the resolved bytes are the cited bytes and are the +record of a benchmark result. It does not establish that the gate behaved as the +result says, and it never changes whether the Trust Record itself verifies. + +``make`` accepts a record only when it is what a benchmark result writes: schema +``adc-provenance/v1``, product ``Agentic-Datacenter``, the label ``benchmark result`` +exactly, ``benchmark_version`` with ``frozen: true``, a 40-character ``code_commit``, +and ``files`` naming ``result_card.json``, each file by a plain relative name with its +SHA-256. The entry's ``resolver`` is the repository the record is kept in, the one its +URL names; a check refuses any other. + +An attestation counts only when its statement names the record as its subject and +was made by the attesting workflow on the branch it must run from: for +``agentic-datacenter/agentic-datacenter``, ``bench-runner.yml`` on ``refs/heads/main``; +for any other repository, a workflow of that repository on its default branch, as the +GitHub API names it. A run from another branch, a pull request or a tag does not +count, since such a ref can change what the workflow runs. +""" + +from __future__ import annotations + +import argparse +import base64 +import hashlib +import http.client +import json +import os +import re +import sys +import urllib.error +import urllib.request +from collections.abc import Callable, Mapping, Sequence +from typing import Any + +#: The relation of the entry. ``rel`` is open in trace-v0.2; this value is not registered. +REL = "benchmark-result" +SCHEMA = "adc-provenance/v1" +#: The label bench.py writes for a frozen run with the scripted agents, and the only +#: one a benchmark result has. A frozen run with a language-model agent, or one on a +#: facility of its owner, is labelled otherwise and is not a benchmark result. +BENCHMARK = "benchmark result" +#: What a benchmark result's record hashes: each part of the frozen benchmark version. +VERSION_PARTS = ("agents", "contract_library", "oracle", "profile", "scenario_library") +#: One segment of a path: plain characters, never ``.`` or ``..``. +SEGMENT = r"[A-Za-z0-9_-][A-Za-z0-9._-]*" +#: A record's URL names one commit, so the bytes behind it cannot move. +RECORD_URL = re.compile( + rf"https://raw\.githubusercontent\.com/(?P[A-Za-z0-9-]+/{SEGMENT})/" + rf"(?P[0-9a-f]{{40}})/(?P(?:{SEGMENT}/)*)provenance\.json" +) +#: A file the record names: a plain relative path inside the record's folder. +FILE_NAME = re.compile(rf"(?:{SEGMENT}/)*{SEGMENT}") +#: The GitHub API: the only place a token is sent to. +API = "https://api.github.com/" +#: The only places anything is fetched from. +HOSTS = ("https://raw.githubusercontent.com/", API) +#: Where a token for the GitHub API is read from, in this order. Without one the API +#: answers a shared address, such as a CI runner's, only until its rate limit is used up. +TOKENS = ("GITHUB_TOKEN", "GH_TOKEN") +ATTESTATIONS = "https://api.github.com/repos/{repo}/attestations/sha256:{digest}" +#: Where the GitHub API names a repository's default branch. +REPOSITORY = "https://api.github.com/repos/{repo}" +MAX_BYTES = 64 * 1024 * 1024 +#: What a lookup over the network, or parsing what it returns, may raise: an +#: http.client error is not an OSError, and deeply nested JSON raises RecursionError. +UNRESOLVED = (OSError, ValueError, http.client.HTTPException, RecursionError) +#: The provenance an attestation must state. +SLSA = "https://slsa.dev/provenance/v1" +#: The workflow that attests a result and the ref it must run from, for a repository +#: whose workflow is known. Any other repository: a workflow of it on its default branch. +WORKFLOWS = { + "agentic-datacenter/agentic-datacenter": ( + ".github/workflows/bench-runner.yml", "refs/heads/main"), +} + +Fetch = Callable[[str], bytes] + + +def _fetchable(url: str) -> bool: + return url.startswith(HOSTS) and "/../" not in url and "/./" not in url + + +class _StayOnGitHub(urllib.request.HTTPRedirectHandler): + """Follow a redirect only to a URL that could have been fetched itself.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def] + if not _fetchable(newurl): + raise urllib.error.URLError(f"not followed: a redirect to {newurl[:80]!r}") + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +def _open(request: urllib.request.Request) -> Any: + """Open *request*, following a redirect only to a URL that could have been fetched itself.""" + return urllib.request.build_opener(_StayOnGitHub).open(request, timeout=60) + + +def fetch(url: str) -> bytes: + """GET *url* over https from GitHub; refuse anything larger than MAX_BYTES. + + A token in the environment (:data:`TOKENS`) is sent with a request to the GitHub API + and with no other: not with a request for a raw file, and not with a redirect. + + Raises: + ValueError: If *url* is not an https URL of GitHub, or the body is too large. + """ + if not _fetchable(url): + raise ValueError(f"not fetched: {url[:80]!r} is not an https URL of GitHub") + request = urllib.request.Request(url, headers={"User-Agent": "adc-reference"}) + token = next((os.environ[name] for name in TOKENS if os.environ.get(name)), "") + if token and url.startswith(API): + # An unredirected header: urllib does not repeat it when it follows a redirect. + request.add_unredirected_header("Authorization", f"Bearer {token}") + with _open(request) as response: + data = bytes(response.read(MAX_BYTES + 1)) + if len(data) > MAX_BYTES: + raise ValueError(f"not read: larger than {MAX_BYTES} bytes") + return data + + +def _why(exc: BaseException) -> str: + """The name of a failure to resolve, with the status when the server gave one.""" + if isinstance(exc, urllib.error.HTTPError): + return f"{type(exc).__name__} {exc.code}" + return type(exc).__name__ + + +def resolver(url: str) -> str: + """The repository a record at *url* is kept in, as a resolver.""" + match = RECORD_URL.fullmatch(url) + if not match: + raise ValueError("cite a provenance.json by its raw URL at a 40-character commit") + return f"https://github.com/{match['repo']}" + + +def digest(data: bytes) -> str: + """The TRACE digest string of *data*.""" + return "sha256:" + hashlib.sha256(data).hexdigest() + + +def make(url: str, data: bytes) -> dict[str, Any]: + """The references entry for the record at *url*, whose bytes are *data*.""" + kept_in = resolver(url) + problems = record_problems(data) + if problems: + raise ValueError("; ".join(problems)) + return {"rel": REL, "id": url, "resolver": kept_in, "digest": digest(data)} + + +def record_problems(data: bytes) -> list[str]: + """What makes *data* not the record of an Agentic-Datacenter benchmark result.""" + try: + record = json.loads(data) + except (ValueError, RecursionError): + return ["not JSON"] + if not isinstance(record, Mapping) or record.get("product") != "Agentic-Datacenter": + return ["not an Agentic-Datacenter record"] + if record.get("schema") != SCHEMA: + return [f"the record's schema is not {SCHEMA}"] + label = record.get("label") + if not isinstance(label, str) or not label.strip(): + return ["the record has no label"] + if label != BENCHMARK: + return [f"the record is labelled {label[:80]!r}, not {BENCHMARK!r}: not a benchmark result"] + version = record.get("benchmark_version") + if not isinstance(version, Mapping): + return ["the record names no benchmark version"] + if version.get("frozen") is not True: + return ["the record's benchmark version is not frozen: not a benchmark result"] + missing = [part for part in VERSION_PARTS + if not (isinstance(version.get(part), str) + and re.fullmatch(r"[0-9a-f]{64}", version[part]))] # fmt: skip + if missing: + return [f"the record's benchmark version has no SHA-256 of its {missing[0]}"] + schema_version = record.get("card_schema_version") + if type(schema_version) is not int or schema_version < 1: + return ["the record names no card_schema_version"] + files = record.get("files") + if not isinstance(files, Mapping) or "result_card.json" not in files: + return ["the record lists no result card"] + commit = record.get("code_commit") + if not isinstance(commit, str) or not re.fullmatch(r"[0-9a-f]{40}", commit): + return ["the record names no code commit"] + bad = [str(name) for name in files if not FILE_NAME.fullmatch(str(name))] + if bad: + return [f"a file name of the record could leave its folder: {bad[0][:80]!r}"] + if not all(isinstance(h, str) and re.fullmatch(r"[0-9a-f]{64}", h) for h in files.values()): + return ["a file of the record has no SHA-256"] + return [] + + +def check(entry: Mapping[str, Any], get: Fetch = fetch, files: Sequence[str] = (), + attestations: bool = False) -> list[str]: # fmt: skip + """What is wrong with *entry*; nothing when it resolves to the bytes it cites.""" + if entry.get("rel") != REL: + return [f"rel is not {REL}"] + url = str(entry.get("id", "")) + match = RECORD_URL.fullmatch(url) + if not match: + return ["id is not the raw URL of a provenance.json at a commit"] + if entry.get("resolver") != f"https://github.com/{match['repo']}": + return ["the resolver is not the repository the record is kept in"] + try: + data = get(url) + except UNRESOLVED as exc: + return [f"unresolved: {_why(exc)}"] + if digest(data) != entry.get("digest"): + return ["the resolved bytes are not the cited bytes"] + problems = record_problems(data) + if problems: + return problems + listed = json.loads(data)["files"] + base = url.rsplit("/", 1)[0] + for name in files: + if name not in listed: + problems.append(f"{name} is not in the record") + continue + try: + got = get(f"{base}/{name}") + except UNRESOLVED as exc: + problems.append(f"{name} unresolved: {_why(exc)}") + continue + if hashlib.sha256(got).hexdigest() != listed[name]: + problems.append(f"{name} does not match the hash in the record") + if attestations: + try: + found = json.loads(get(ATTESTATIONS.format(repo=match["repo"], digest=digest(data)[7:]))) + except UNRESOLVED as exc: + problems.append(f"attestations unresolved: {_why(exc)}") + else: + if not isinstance(found, Mapping): + problems.append("attestations unresolved: not an answer of the GitHub API") + elif not found.get("attestations"): + problems.append("attestations: GitHub holds none of the record") + else: + problems += _attested(found["attestations"], match["repo"], digest(data), get) + return problems + + +def _attested(found: object, repo: str, record_digest: str, get: Fetch) -> list[str]: + """attestation_problems, with the ref asked of GitHub for a repository not in WORKFLOWS.""" + known = WORKFLOWS.get(repo.lower()) + if known: + return attestation_problems(found, repo, record_digest, known[1]) + try: + answer = json.loads(get(REPOSITORY.format(repo=repo))) + except UNRESOLVED as exc: + return [f"attestations unresolved: the default branch: {_why(exc)}"] + branch = answer.get("default_branch") if isinstance(answer, Mapping) else None + if not isinstance(branch, str) or not branch: + return ["attestations unresolved: the GitHub API names no default branch"] + return attestation_problems(found, repo, record_digest, f"refs/heads/{branch}") + + +def signer(attestation: object, record_digest: str) -> str | None: + """The workflow that signed an attestation of the record, as ``owner/repo:path@ref``. + + The builder must be exactly ``{repository}/{path}@{ref}`` of that workflow. This reads + the attestation's statement as GitHub returns it. It does not check the signature + over it or the certificate; ``gh attestation verify`` does. + """ + try: + envelope = attestation["bundle"]["dsseEnvelope"] # type: ignore[index] + statement = json.loads(base64.b64decode(envelope["payload"], validate=True)) + if statement.get("predicateType") != SLSA: + return None + subjects = [s.get("digest", {}).get("sha256") for s in statement.get("subject") or []] + if record_digest[len("sha256:"):] not in subjects: + return None + workflow = statement["predicate"]["buildDefinition"]["externalParameters"]["workflow"] + repository, path = str(workflow["repository"]), str(workflow["path"]) + ref = str(workflow["ref"]) + builder = str(statement["predicate"]["runDetails"]["builder"]["id"]) + except (KeyError, TypeError, ValueError, AttributeError, RecursionError): + return None + prefix = "https://github.com/" + if not repository.startswith(prefix) or builder != f"{repository}/{path}@{ref}": + return None + return f"{repository[len(prefix):]}:{path}@{ref}" + + +def attestation_problems(found: object, repo: str, record_digest: str, ref: str) -> list[str]: + """Whether an attestation of the record was made by a workflow of its repository on *ref*. + + For a repository whose attesting workflow is known (:data:`WORKFLOWS`), it must be + that workflow. + """ + signers = [signer(a, record_digest) for a in found] if isinstance(found, list) else [] + named = sorted({s for s in signers if s}) + known = WORKFLOWS.get(repo.lower()) + want = known[0] if known else None + for name in named: + owner_repo, rest = name.split(":", 1) + path, made_on = rest.rsplit("@", 1) + if owner_repo.lower() == repo.lower() and made_on == ref and (want is None or path == want): + return [] + if not named: + return ["attestations: none states the record as its subject and the workflow that made it"] + return [f"attestations: made by {', '.join(named)}, not by " + f"{repo + ':' + want if want else 'a workflow of ' + repo}@{ref}"] + + +def main(argv: Sequence[str] | None = None) -> int: + """Run the command line.""" + parser = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0]) + actions = parser.add_subparsers(dest="action", required=True) + one = actions.add_parser("make", help="Print the references entry for a record.") + one.add_argument("url") + two = actions.add_parser("check", help="Resolve an entry and check what it cites.") + two.add_argument("entry", help="A file holding the entry as JSON.") + two.add_argument("--file", action="append", default=[], help="A file of the result to check.") + two.add_argument("--attestations", action="store_true", + help="Also ask GitHub whether it holds an attestation of the record.") # fmt: skip + args = parser.parse_args(argv) + if args.action == "make": + try: + resolver(args.url) # the URL is checked before anything is fetched + print(json.dumps(make(args.url, fetch(args.url)), indent=2)) + except UNRESOLVED as exc: + print(f"adc_reference: {exc}", file=sys.stderr) + return 2 + return 0 + try: + with open(args.entry, encoding="utf-8") as handle: + entry = json.load(handle) + except (OSError, ValueError, RecursionError) as exc: + print(f"adc_reference: {args.entry}: {type(exc).__name__}: {exc}"[:300], file=sys.stderr) + return 2 + if not isinstance(entry, Mapping): + print(f"adc_reference: {args.entry}: not a JSON object", file=sys.stderr) + return 2 + problems = check(entry, files=args.file, attestations=args.attestations) + for problem in problems: + print(problem) + if not problems: + print("resolved: the cited bytes, the record of a benchmark result") + return 1 if problems else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/agentic-datacenter-benchmark/examples/01-result-cited.json b/integrations/agentic-datacenter-benchmark/examples/01-result-cited.json new file mode 100644 index 0000000..6f851d7 --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/examples/01-result-cited.json @@ -0,0 +1,42 @@ +{ + "appraisal": { + "status": "none", + "verifier": "https://verifier.example.org" + }, + "build_provenance": { + "digest": "sha256:eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", + "slsa_level": 1 + }, + "cnf": { + "jwk": { + "crv": "Ed25519", + "kty": "OKP", + "x": "xjN2ztotcVeA3GOyFOe85OAqN3VNSZjeW_rXOzxQeC0" + } + }, + "data_class": "internal", + "eat_profile": "tag:agentrust-io.com,2026:trace-v0.2", + "iat": 1795996800, + "model": { + "model_id": "example-model", + "provider": "example" + }, + "policy": { + "bundle_hash": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "enforcement_mode": "enforce" + }, + "references": [ + { + "digest": "sha256:641974e9414b0c7d582f6feeb2b28e95a38a3a396512e3e707ca10935281a0e8", + "id": "https://raw.githubusercontent.com/example-org/example-gate/1111111111111111111111111111111111111111/results/example/provenance.json", + "rel": "benchmark-result", + "resolver": "https://github.com/example-org/example-gate" + } + ], + "runtime": { + "measurement": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "platform": "software-only" + }, + "signature": "tTKdvHBtffDie5y74veexN6lk1PNeC32V7ZTboGIhU2GB45ib65kNSIgbXUxNU4PHuCyiHD5fB6MYN46KZJmAQ", + "subject": "spiffe://trust.example.org/agent/governance-gate" +} diff --git a/integrations/agentic-datacenter-benchmark/examples/02-digest-not-the-record.json b/integrations/agentic-datacenter-benchmark/examples/02-digest-not-the-record.json new file mode 100644 index 0000000..8aefb8f --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/examples/02-digest-not-the-record.json @@ -0,0 +1,42 @@ +{ + "appraisal": { + "status": "none", + "verifier": "https://verifier.example.org" + }, + "build_provenance": { + "digest": "sha256:eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", + "slsa_level": 1 + }, + "cnf": { + "jwk": { + "crv": "Ed25519", + "kty": "OKP", + "x": "xjN2ztotcVeA3GOyFOe85OAqN3VNSZjeW_rXOzxQeC0" + } + }, + "data_class": "internal", + "eat_profile": "tag:agentrust-io.com,2026:trace-v0.2", + "iat": 1795996800, + "model": { + "model_id": "example-model", + "provider": "example" + }, + "policy": { + "bundle_hash": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "enforcement_mode": "enforce" + }, + "references": [ + { + "digest": "sha256:abdd2af10237dacab9abc4e8920b0ef80bbc4381425167370517c32f4fac87d0", + "id": "https://raw.githubusercontent.com/example-org/example-gate/1111111111111111111111111111111111111111/results/example/provenance.json", + "rel": "benchmark-result", + "resolver": "https://github.com/example-org/example-gate" + } + ], + "runtime": { + "measurement": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "platform": "software-only" + }, + "signature": "xP32dktu74lxEci40OAjztCJ-uao3ku8TneLEeC8ckDEKUEO_C1aojUnb-oZCtRif06RWZLg4U1ohbJRjNJLCg", + "subject": "spiffe://trust.example.org/agent/governance-gate" +} diff --git a/integrations/agentic-datacenter-benchmark/examples/expected.json b/integrations/agentic-datacenter-benchmark/examples/expected.json new file mode 100644 index 0000000..f7dd39c --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/examples/expected.json @@ -0,0 +1,19 @@ +{ + "cases": { + "01-result-cited.json": { + "record_verifies": true, + "reference": [] + }, + "02-digest-not-the-record.json": { + "record_verifies": true, + "reference": [ + "the resolved bytes are not the cited bytes" + ] + } + }, + "signer_jwk": { + "crv": "Ed25519", + "kty": "OKP", + "x": "xjN2ztotcVeA3GOyFOe85OAqN3VNSZjeW_rXOzxQeC0" + } +} diff --git a/integrations/agentic-datacenter-benchmark/examples/make_examples.py b/integrations/agentic-datacenter-benchmark/examples/make_examples.py new file mode 100644 index 0000000..7b4c3f4 --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/examples/make_examples.py @@ -0,0 +1,121 @@ +"""Regenerate the example Trust Records. Everything here derives from one published seed. + + python integrations/agentic-datacenter-benchmark/examples/make_examples.py + +``source/provenance.json`` is a synthetic record made for this example, in the +schema an Agentic-Datacenter benchmark run writes (``adc-provenance/v1``), with +plainly fake values: it is not the record of any run. It carries the label a +benchmark result has, ``benchmark result``, since a check accepts no other. The two Trust Records are +fixtures: a demo key derived from SEED signs them, so anyone can rebuild them, and +they claim nothing about any real workload. The online test resolves a real +published record instead, at PUBLISHED_URL. +""" + +from __future__ import annotations + +import hashlib +import json +import sys +from pathlib import Path +from typing import Any + +from agentrust_trace import key_to_jwk, sign_record +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent)) +import adc_reference # noqa: E402 + +SEED = b"agentic-datacenter benchmark reference demo/1" +IAT = 1795996800 # 2026-11-30T00:00:00Z +#: Where the synthetic record is cited from. Nothing is served there: the offline +#: tests serve the synthetic bytes in its place. +COMMIT = "1" * 40 +RECORD_URL = ( + f"https://raw.githubusercontent.com/example-org/example-gate/{COMMIT}/" + "results/example/provenance.json" +) +#: A real record, published by an Agentic-Datacenter run at a fixed commit; only the +#: online test resolves it. +PUBLISHED_COMMIT = "d00a805e7f661ff083e29060a7198d0853bf4075" +PUBLISHED_URL = ( + "https://raw.githubusercontent.com/agentic-datacenter/agentic-datacenter/" + f"{PUBLISHED_COMMIT}/results/remora/benchmark-v1.7-statements-only/provenance.json" +) + + +def synthetic_record() -> bytes: + """A record in the schema a benchmark run writes, with plainly fake values.""" + fake = { + name: hashlib.sha256(f"example {name}".encode()).hexdigest() + for name in ("check.txt", "decisions.jsonl", "report.html", "result_card.json", + "summary.md") + } # fmt: skip + record = { + "schema": "adc-provenance/v1", + "product": "Agentic-Datacenter", + "label": "benchmark result", + "code_commit": "0" * 40, + "card_schema_version": 6, + "benchmark_version": {"frozen": True, **{part: "0" * 64 for part in ( + "agents", "contract_library", "oracle", "profile", "scenario_library")}}, + "files": fake, + } + return (json.dumps(record, indent=2, sort_keys=True) + "\n").encode() + + +def key() -> Ed25519PrivateKey: + """The demo signing key, from the published seed.""" + return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(SEED).digest()) + + +def record(reference: dict[str, Any]) -> dict[str, Any]: + """A software-only Trust Record of a governance gate, citing *reference*.""" + signer = key() + unsigned = { + "eat_profile": "tag:agentrust-io.com,2026:trace-v0.2", + "iat": IAT, + "subject": "spiffe://trust.example.org/agent/governance-gate", + "model": {"provider": "example", "model_id": "example-model"}, + "runtime": {"platform": "software-only", "measurement": "sha256:" + "0" * 64}, + "policy": {"bundle_hash": "sha256:" + "b" * 64, "enforcement_mode": "enforce"}, + "data_class": "internal", + "build_provenance": {"slsa_level": 1, "digest": "sha256:" + "e" * 64}, + "appraisal": {"status": "none", "verifier": "https://verifier.example.org"}, + "cnf": {"jwk": key_to_jwk(signer)}, + "references": [reference], + } + return sign_record(unsigned, signer) + + +def build() -> dict[str, dict[str, Any]]: + """Every example Trust Record and the expected results, by name.""" + data = synthetic_record() + cited = adc_reference.make(RECORD_URL, data) + altered = {**cited, "digest": "sha256:" + hashlib.sha256(data + b" ").hexdigest()} + return { + "01-result-cited.json": record(cited), + "02-digest-not-the-record.json": record(altered), + "expected.json": { + "signer_jwk": key_to_jwk(key()), + "cases": { + "01-result-cited.json": {"record_verifies": True, "reference": []}, + "02-digest-not-the-record.json": { + "record_verifies": True, + "reference": ["the resolved bytes are not the cited bytes"], + }, + }, + }, + } + + +def main() -> None: + """Write the examples.""" + (HERE / "source").mkdir(exist_ok=True) + (HERE / "source" / "provenance.json").write_bytes(synthetic_record()) + for name, value in build().items(): + (HERE / name).write_text(json.dumps(value, indent=2, sort_keys=True) + "\n") + + +if __name__ == "__main__": + main() diff --git a/integrations/agentic-datacenter-benchmark/examples/source/provenance.json b/integrations/agentic-datacenter-benchmark/examples/source/provenance.json new file mode 100644 index 0000000..52bca75 --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/examples/source/provenance.json @@ -0,0 +1,22 @@ +{ + "benchmark_version": { + "agents": "0000000000000000000000000000000000000000000000000000000000000000", + "contract_library": "0000000000000000000000000000000000000000000000000000000000000000", + "frozen": true, + "oracle": "0000000000000000000000000000000000000000000000000000000000000000", + "profile": "0000000000000000000000000000000000000000000000000000000000000000", + "scenario_library": "0000000000000000000000000000000000000000000000000000000000000000" + }, + "card_schema_version": 6, + "code_commit": "0000000000000000000000000000000000000000", + "files": { + "check.txt": "66a1fae0169698723885eb55c132d111b689fb4f47c893c0b876a61395779e62", + "decisions.jsonl": "792dcac09d81c996cf4dc868e5f1a70256e654e97a37ba0a11445a0da2ae9285", + "report.html": "24abe082e5524ff48ed51ea921d878c9368ce1189d9a570c714b7a619129f211", + "result_card.json": "a3ba9a0d423281e7583b76bae8f3a2bb3428fcba956e1870ac016cb1733a389f", + "summary.md": "c64f25560ab200f963ba235e32a8dc6978da1e538d11437fd0435bbf9d3d4dfa" + }, + "label": "benchmark result", + "product": "Agentic-Datacenter", + "schema": "adc-provenance/v1" +} diff --git a/integrations/agentic-datacenter-benchmark/integration.yaml b/integrations/agentic-datacenter-benchmark/integration.yaml new file mode 100644 index 0000000..ce48ef4 --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/integration.yaml @@ -0,0 +1,26 @@ +name: Agentic-Datacenter benchmark result references +vendor: Agentic-Datacenter +integrates_with: + - trace +description: >- + A TRACE Trust Record of an agent-governance gate cites the gate's published + Agentic-Datacenter benchmark result through a references entry, checked for + digest match against the result's record. +maintainer: + github: darklordVirtual +repository: https://github.com/agentic-datacenter/agentic-datacenter +license: Apache-2.0 +tier: community +marketplace: + category: Evidence & receipts + mark: ADC + keywords: [benchmark, governance-gate, references, provenance, simulation] +# Role. The referenced object is another party's evidence: the record +# (provenance.json) that an Agentic-Datacenter benchmark run wrote beside its +# result card, which GitHub attested for the run that made it. The Trust Records +# here are fixtures signed by a demo key derived from a published seed, so this +# integration issues no Trust Record of its own and declares no conformance level. +trace_roles: + - external-evidence-source +tested_against: + agentrust-trace: "0.11.0" diff --git a/integrations/agentic-datacenter-benchmark/pyproject.toml b/integrations/agentic-datacenter-benchmark/pyproject.toml new file mode 100644 index 0000000..9814db8 --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/pyproject.toml @@ -0,0 +1,21 @@ +[build-system] +requires = ["setuptools>=77"] +build-backend = "setuptools.build_meta" + +[project] +name = "agentic-datacenter-benchmark-integration" +version = "0.1.0" +description = "TRACE Trust Records citing a published Agentic-Datacenter benchmark result through a references entry" +requires-python = ">=3.11" +license = "Apache-2.0" +dependencies = [ + # 0.11.0 verifies a record carrying a references entry with an open rel value. + "agentrust-trace>=0.11.0", + "cryptography", +] + +[project.optional-dependencies] +test = ["pytest"] + +[tool.setuptools] +py-modules = ["adc_reference"] diff --git a/integrations/agentic-datacenter-benchmark/tests/conftest.py b/integrations/agentic-datacenter-benchmark/tests/conftest.py new file mode 100644 index 0000000..a0ada8f --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/tests/conftest.py @@ -0,0 +1,22 @@ +"""``online`` tests resolve the published record over the network; run them with --online.""" + +from __future__ import annotations + +import pytest + + +def pytest_addoption(parser: pytest.Parser) -> None: + parser.addoption("--online", action="store_true", help="Also resolve the published record.") + + +def pytest_configure(config: pytest.Config) -> None: + config.addinivalue_line("markers", "online: resolves the published record over the network") + + +def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None: + if config.getoption("--online"): + return + skip = pytest.mark.skip(reason="resolves over the network; run with --online") + for item in items: + if "online" in item.keywords: + item.add_marker(skip) diff --git a/integrations/agentic-datacenter-benchmark/tests/test_adc_reference.py b/integrations/agentic-datacenter-benchmark/tests/test_adc_reference.py new file mode 100644 index 0000000..db384d7 --- /dev/null +++ b/integrations/agentic-datacenter-benchmark/tests/test_adc_reference.py @@ -0,0 +1,700 @@ +"""A Trust Record citing a published Agentic-Datacenter result, and what a check finds. + +Offline, against ``examples/source/provenance.json``, a synthetic record served in +place of the example URL. The test marked ``online`` resolves a real published record. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +import pytest +from agentrust_trace import Reference, verify_record + +HERE = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE / "examples")) +import adc_reference # noqa: E402 +import make_examples # noqa: E402 + +SOURCE = (HERE / "examples" / "source" / "provenance.json").read_bytes() +EXPECTED = json.loads((HERE / "examples" / "expected.json").read_text()) + + +def _serve(url: str) -> bytes: + if url == make_examples.RECORD_URL: + return SOURCE + raise OSError(f"not served offline: {url}") + + +def _load(name: str) -> dict: + return json.loads((HERE / "examples" / name).read_text()) + + +def test_the_examples_are_what_the_generator_makes() -> None: + assert SOURCE == make_examples.synthetic_record(), "the synthetic record" + assert json.loads(SOURCE)["label"] == "benchmark result" + for name, value in make_examples.build().items(): + assert _load(name) == value, name + + +@pytest.mark.parametrize("name", sorted(EXPECTED["cases"])) +def test_each_record_verifies_and_its_reference_checks_as_expected(name: str) -> None: + record = _load(name) + verify_record(record, EXPECTED["signer_jwk"], max_age_seconds=None) + (entry,) = record["references"] + Reference.model_validate(entry) + assert adc_reference.check(entry, _serve) == EXPECTED["cases"][name]["reference"] + + +def test_an_entry_cites_a_fixed_commit_and_a_real_record_only() -> None: + with pytest.raises(ValueError, match="commit"): + adc_reference.make(make_examples.RECORD_URL.replace(make_examples.COMMIT, "main"), SOURCE) + with pytest.raises(ValueError, match="not an Agentic-Datacenter record"): + adc_reference.make(make_examples.RECORD_URL, b'{"product": "other"}') + without_card = json.loads(SOURCE) + del without_card["files"]["result_card.json"] + with pytest.raises(ValueError, match="no result card"): + adc_reference.make(make_examples.RECORD_URL, json.dumps(without_card).encode()) + + +def test_an_unresolvable_entry_is_reported_and_does_not_change_the_record() -> None: + record = _load("01-result-cited.json") + (entry,) = record["references"] + assert adc_reference.check(entry, lambda url: (_ for _ in ()).throw(OSError("down"))) == [ + "unresolved: OSError" + ] + verify_record(record, EXPECTED["signer_jwk"], max_age_seconds=None) + + +def test_a_file_of_the_result_must_match_the_hash_the_record_gives_it() -> None: + (entry,) = _load("01-result-cited.json")["references"] + + def serve(url: str) -> bytes: + return SOURCE if url == make_examples.RECORD_URL else b"not the summary" + + assert adc_reference.check(entry, serve, files=["summary.md"]) == [ + "summary.md does not match the hash in the record" + ] + assert adc_reference.check(entry, serve, files=["other.txt"]) == ["other.txt is not in the record"] + + +@pytest.mark.online +def test_a_real_published_record_resolves_with_its_summary_and_attestation() -> None: + url = make_examples.PUBLISHED_URL + entry = adc_reference.make(url, adc_reference.fetch(url)) + Reference.model_validate(entry) + assert adc_reference.check(entry, files=["summary.md"], attestations=True) == [] + + +# --- Review of #438: each point, refused or caught ----------------------------------- + + +def _record(**change: object) -> bytes: + record = json.loads(SOURCE) + for key, value in change.items(): + if value is None: + record.pop(key, None) + else: + record[key] = value + return json.dumps(record).encode() + + +@pytest.mark.parametrize( + ("change", "why"), + [ + ({"schema": None}, "schema"), + ({"schema": "other/v1"}, "schema"), + ({"label": None}, "label"), + ({"benchmark_version": None}, "benchmark version"), + ({"benchmark_version": {"frozen": False}}, "frozen"), + ({"label": "development run, not a benchmark result"}, "development run"), + # The full shape a benchmark result writes: every part of the version, hashed. + ({"benchmark_version": {"frozen": True}}, "SHA-256 of its agents"), + ({"benchmark_version": {"frozen": True, "oracle": "0" * 64}}, "SHA-256 of its agents"), + *[({"benchmark_version": {"frozen": True, **{p: "0" * 64 for p in + ("agents", "contract_library", "oracle", "profile", "scenario_library") if p != gone}}}, + f"SHA-256 of its {gone}") + for gone in ("agents", "contract_library", "oracle", "profile", "scenario_library")], + ({"benchmark_version": {"frozen": True, **{p: "X" * 64 for p in + ("agents", "contract_library", "oracle", "profile", "scenario_library")}}}, + "SHA-256 of its agents"), + ({"card_schema_version": None}, "card_schema_version"), + ({"card_schema_version": "6"}, "card_schema_version"), + ({"card_schema_version": 0}, "card_schema_version"), + ], +) +def test_a_record_must_be_the_schema_a_benchmark_result_writes(change: dict, why: str) -> None: + """Point 1: the schema and its required fields are enforced, and a development run is not + a benchmark result.""" + with pytest.raises(ValueError, match=why): + adc_reference.make(make_examples.RECORD_URL, _record(**change)) + minimal = json.dumps({"product": "Agentic-Datacenter", "code_commit": "0" * 40, + "files": {"result_card.json": "a" * 64}}).encode() # fmt: skip + with pytest.raises(ValueError): + adc_reference.make(make_examples.RECORD_URL, minimal) + + +def test_the_resolver_is_the_repository_the_record_is_kept_in() -> None: + """Points 2 and 7: the resolver names the repository the URL is in, and a check refuses an + entry whose resolver is another one.""" + (entry,) = _load("01-result-cited.json")["references"] + assert entry["resolver"] == "https://github.com/example-org/example-gate" + for resolver in ("https://github.com/agentic-datacenter/agentic-datacenter", + "https://example.org/somewhere-else", None): # fmt: skip + wrong = {**entry, "resolver": resolver} + assert adc_reference.check(wrong, _serve) == [ + "the resolver is not the repository the record is kept in" + ] + + +@pytest.mark.parametrize( + "url", + [ + f"https://raw.githubusercontent.com/example-org/example-gate/{'1' * 40}/../secret/provenance.json", + f"https://raw.githubusercontent.com/example-org/example-gate/{'1' * 40}/a/./provenance.json", + f"https://raw.githubusercontent.com/example-org/example-gate/{'1' * 40}/a//provenance.json", + f"https://raw.githubusercontent.com/../example-gate/{'1' * 40}/provenance.json", + ], +) +def test_a_url_with_a_dot_segment_is_refused(url: str) -> None: + """Point 3: no `.`, `..` or empty segment in the record's URL.""" + with pytest.raises(ValueError): + adc_reference.make(url, SOURCE) + + +@pytest.mark.parametrize("name", ["../secret.txt", "a/../../b", "/etc/passwd", "a\\b", ".", "", "a//b"]) +def test_a_file_name_in_the_record_that_could_leave_its_folder_is_refused(name: str) -> None: + """Point 3: names taken from the record are never used to build a URL outside it.""" + files = {**json.loads(SOURCE)["files"], name: "a" * 64} + with pytest.raises(ValueError, match="file name"): + adc_reference.make(make_examples.RECORD_URL, _record(files=files)) + + +def test_more_than_the_limit_is_refused_not_cut(monkeypatch: pytest.MonkeyPatch) -> None: + """Point 4: a body longer than MAX_BYTES is refused, never truncated and parsed.""" + monkeypatch.setattr(adc_reference, "MAX_BYTES", 10) + + class Response: + def __enter__(self) -> "Response": + return self + + def __exit__(self, *args: object) -> None: + return None + + def read(self, n: int) -> bytes: + return (b"{}" + b" " * 100)[:n] + + monkeypatch.setattr(adc_reference, "_open", lambda *a, **k: Response()) + with pytest.raises(ValueError, match="larger than"): + adc_reference.fetch(make_examples.RECORD_URL) + + +def test_the_url_is_checked_before_anything_is_fetched(monkeypatch: pytest.MonkeyPatch) -> None: + """Point 5: the command line refuses a URL before fetching, and fetch never opens file://.""" + fetched: list[str] = [] + monkeypatch.setattr(adc_reference, "fetch", lambda url: fetched.append(url) or SOURCE) + assert adc_reference.main(["make", "file:///etc/passwd"]) == 2 + assert adc_reference.main(["make", "https://example.org/provenance.json"]) == 2 + assert fetched == [] + monkeypatch.undo() + for url in ("file:///etc/passwd", "http://raw.githubusercontent.com/x/y/z", + "https://example.org/provenance.json"): # fmt: skip + with pytest.raises(ValueError): + adc_reference.fetch(url) + + +@pytest.mark.parametrize("failure", [OSError("down"), ValueError("not JSON"), b"[1]", b"not json"]) +def test_an_attestation_lookup_that_fails_is_a_problem_not_a_crash(failure: object) -> None: + """Point 6: network, API and JSON failures of the attestation lookup are reported.""" + (entry,) = _load("01-result-cited.json")["references"] + + def serve(url: str) -> bytes: + if url == make_examples.RECORD_URL: + return SOURCE + if isinstance(failure, Exception): + raise failure + return failure # type: ignore[return-value] + + problems = adc_reference.check(entry, serve, attestations=True) + assert len(problems) == 1 and problems[0].startswith("attestations") + + +def test_the_package_needs_a_setuptools_that_reads_its_licence() -> None: + """Point 9: `license = "Apache-2.0"` needs setuptools 77 or later.""" + text = (HERE / "pyproject.toml").read_text() + assert 'requires = ["setuptools>=77"]' in text + + +def test_the_readme_says_how_to_commit_the_attested_record() -> None: + """Point 8: the step from the attested artifact to a URL at a commit is written down.""" + text = (HERE / "README.md").read_text() + for words in ("gh run download", "gh attestation verify", "byte for byte", "git add"): + assert words in text, words + + +# --- Follow-up: what the first round left open ---------------------------------------- + + +def test_a_code_commit_must_be_a_string() -> None: + """Point 1: a JSON number of 40 digits is not a commit.""" + assert adc_reference.record_problems(_record(code_commit=int("1" * 40))) == [ + "the record names no code commit" + ] + assert adc_reference.record_problems(_record(code_commit="1" * 40)) == [] + + +@pytest.fixture +def two_servers(): + """A server that redirects to a second one on another port, which records what it got.""" + import http.server + import threading + + seen: list[str] = [] + + class Second(http.server.BaseHTTPRequestHandler): + def do_GET(self) -> None: # noqa: N802 + seen.append(self.path) + self.send_response(200) + self.end_headers() + self.wfile.write(b"from the other host") + + def log_message(self, *args: object) -> None: + pass + + second = http.server.HTTPServer(("127.0.0.1", 0), Second) + + class First(Second): + def do_GET(self) -> None: # noqa: N802 + if self.path == "/same": + target = f"http://127.0.0.1:{first.server_port}/here" + elif self.path == "/here": + return Second.do_GET(self) + else: + target = f"http://127.0.0.1:{second.server_port}/there" + self.send_response(302) + self.send_header("Location", target) + self.end_headers() + + first = http.server.HTTPServer(("127.0.0.1", 0), First) + for server in (first, second): + threading.Thread(target=server.serve_forever, daemon=True).start() + yield f"http://127.0.0.1:{first.server_port}/", seen + for server in (first, second): + server.shutdown() + + +def test_a_redirect_to_another_host_is_not_followed(two_servers, monkeypatch) -> None: + """Point 5: fetch follows a redirect only to a URL it could have fetched itself.""" + allowed, seen = two_servers + monkeypatch.setattr(adc_reference, "HOSTS", (allowed,)) + assert adc_reference.fetch(allowed + "same") == b"from the other host" # same host: followed + seen.clear() + with pytest.raises(OSError, match="not followed"): + adc_reference.fetch(allowed + "away") + assert seen == [] + + +@pytest.mark.parametrize("where", ["record", "file", "attestations"]) +@pytest.mark.parametrize("error", ["IncompleteRead", "BadStatusLine", "RemoteDisconnected"]) +def test_an_http_client_error_is_a_problem_not_a_crash(where: str, error: str) -> None: + """Point 6: http.client's errors are not OSErrors; each is reported where it happens.""" + import http.client + + failure = { + "IncompleteRead": http.client.IncompleteRead(b""), + "BadStatusLine": http.client.BadStatusLine("x"), + "RemoteDisconnected": http.client.RemoteDisconnected("x"), + }[error] + (entry,) = _load("01-result-cited.json")["references"] + + def serve(url: str) -> bytes: + if url == make_examples.RECORD_URL and where != "record": + return SOURCE + raise failure + + problems = adc_reference.check( + entry, serve, files=["summary.md"] if where == "file" else [], + attestations=where == "attestations", + ) + said = {"record": "unresolved: ", "file": "summary.md unresolved: ", + "attestations": "attestations unresolved: "}[where] + assert problems == [said + type(failure).__name__] + + +def _attestation(repository: str, path: str, subject: str, ref: str = "refs/heads/main", + builder: str | None = None, + predicate_type: str = "https://slsa.dev/provenance/v1") -> dict: # fmt: skip + """An attestation as the GitHub API returns one, with the statement it signs.""" + import base64 + + statement = { + "_type": "https://in-toto.io/Statement/v1", + "subject": [{"name": "provenance.json", "digest": {"sha256": subject}}], + "predicateType": predicate_type, + "predicate": { + "buildDefinition": {"externalParameters": {"workflow": { + "ref": ref, "repository": repository, "path": path}}}, + "runDetails": {"builder": {"id": builder or f"{repository}/{path}@{ref}"}}, + }, + } # fmt: skip + payload = base64.b64encode(json.dumps(statement).encode()).decode() + return {"bundle": {"dsseEnvelope": {"payload": payload, + "payloadType": "application/vnd.in-toto+json"}}} + + +@pytest.mark.parametrize( + ("repository", "path", "subject", "holds"), + [ + ("https://github.com/example-org/example-gate", ".github/workflows/bench.yml", "record", True), + ("https://github.com/mallory/fake", ".github/workflows/bench.yml", "record", False), + ("https://github.com/example-org/example-gate", ".github/workflows/bench.yml", "other", False), + ], +) +def test_an_attestation_must_be_of_the_record_by_a_workflow_of_its_repository( + repository: str, path: str, subject: str, holds: bool +) -> None: + """Point 7: an attestation counts only when its statement names the record and a workflow + of the repository the record is kept in.""" + (entry,) = _load("01-result-cited.json")["references"] + record_digest = entry["digest"][len("sha256:"):] + answer = {"attestations": [_attestation( + repository, path, record_digest if subject == "record" else "0" * 64)]} # fmt: skip + + def serve(url: str) -> bytes: + if url == make_examples.RECORD_URL: + return SOURCE + if url == adc_reference.REPOSITORY.format(repo="example-org/example-gate"): + return b'{"default_branch": "main"}' + return json.dumps(answer).encode() + + problems = adc_reference.check(entry, serve, attestations=True) + assert (problems == []) is holds, problems + + +def test_agentic_datacenter_s_own_results_must_be_attested_by_its_bench_workflow() -> None: + """Point 7: for Agentic-Datacenter's repository the attesting workflow is known.""" + repo = "agentic-datacenter/agentic-datacenter" + record = "a" * 64 + main = "refs/heads/main" + good = _attestation(f"https://github.com/{repo}", ".github/workflows/bench-runner.yml", record) + other = _attestation(f"https://github.com/{repo}", ".github/workflows/scratch.yml", record) + assert adc_reference.attestation_problems([good], repo, "sha256:" + record, main) == [] + assert adc_reference.attestation_problems([other, good], repo, "sha256:" + record, main) == [] + assert adc_reference.attestation_problems([other], repo, "sha256:" + record, main) == [ + f"attestations: made by {repo}:.github/workflows/scratch.yml@{main}, not by " + f"{repo}:.github/workflows/bench-runner.yml@{main}" + ] + assert adc_reference.attestation_problems([{"bundle": {}}], repo, "sha256:" + record, main) == [ + "attestations: none states the record as its subject and the workflow that made it" + ] + + +def test_the_readme_downloads_the_artifact_by_name_to_the_paths_it_uses() -> None: + """Second review: each command names a path the downloaded artifact has. The participant + workflow's artifact holds the result in bench/; bench-runner.yml's holds it at the top.""" + text = (HERE / "README.md").read_text() + assert "--name agentic-datacenter-stable-result- --dir result-artifact" in text + assert "gh attestation verify result-artifact/bench/provenance.json" in text + assert "cp result-artifact/bench/* results//" in text + assert "--name bench-" in text and "`result-artifact/provenance.json`" in text + assert "*/bench/" not in text + + +# --- The conformance run that failed on an attestation lookup with HTTPError -------------- +@pytest.mark.parametrize("where", ["record", "file", "attestations"]) +def test_an_http_status_is_reported_with_the_failure(where: str) -> None: + """A lookup GitHub refuses says with which status: 403 or 429 is a rate limit, 5xx is not.""" + import urllib.error + from email.message import Message + + (entry,) = _load("01-result-cited.json")["references"] + + def serve(url: str) -> bytes: + if url == make_examples.RECORD_URL and where != "record": + return SOURCE + raise urllib.error.HTTPError(url, 403, "rate limit exceeded", Message(), None) + + problems = adc_reference.check( + entry, serve, files=["summary.md"] if where == "file" else [], + attestations=where == "attestations", + ) + said = {"record": "unresolved: ", "file": "summary.md unresolved: ", + "attestations": "attestations unresolved: "}[where] # fmt: skip + assert problems == [said + "HTTPError 403"] + + +class _Empty: + def __enter__(self) -> "_Empty": + return self + + def __exit__(self, *args: object) -> None: + return None + + def read(self, n: int) -> bytes: + return b"{}" + + +@pytest.mark.parametrize("name", ["GITHUB_TOKEN", "GH_TOKEN"]) +def test_a_token_is_sent_to_the_github_api_and_nowhere_else( + name: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """The attestation lookup is authenticated when a token is set; a raw file never is.""" + asked: list = [] + monkeypatch.setattr(adc_reference, "_open", lambda request: asked.append(request) or _Empty()) + for other in adc_reference.TOKENS: + monkeypatch.delenv(other, raising=False) + api = adc_reference.ATTESTATIONS.format(repo="o/r", digest="0" * 64) + + adc_reference.fetch(api) + assert asked[-1].get_header("Authorization") is None # no token: asked without one + + monkeypatch.setenv(name, "not-a-real-token") + adc_reference.fetch(api) + assert asked[-1].unredirected_hdrs == {"Authorization": "Bearer not-a-real-token"} + assert "Authorization" not in asked[-1].headers # never among the headers a redirect repeats + adc_reference.fetch(make_examples.RECORD_URL) + assert asked[-1].get_header("Authorization") is None + + monkeypatch.setenv(name, "") + adc_reference.fetch(api) + assert asked[-1].get_header("Authorization") is None # an empty value is no token + + +def test_a_token_does_not_follow_a_redirect(monkeypatch: pytest.MonkeyPatch) -> None: + """A redirect, even one within the API's own host, is followed without the token.""" + import http.server + import threading + + got: list[tuple[str, str | None]] = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self) -> None: # noqa: N802 + got.append((self.path, self.headers.get("Authorization"))) + if self.path == "/first": + self.send_response(302) + self.send_header("Location", f"http://127.0.0.1:{server.server_port}/second") + self.end_headers() + return + self.send_response(200) + self.end_headers() + self.wfile.write(b"{}") + + def log_message(self, *args: object) -> None: + pass + + server = http.server.HTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + here = f"http://127.0.0.1:{server.server_port}/" + monkeypatch.setattr(adc_reference, "API", here) + monkeypatch.setattr(adc_reference, "HOSTS", (here,)) + monkeypatch.setenv("GITHUB_TOKEN", "not-a-real-token") + assert adc_reference.fetch(here + "first") == b"{}" + finally: + server.shutdown() + assert got == [("/first", "Bearer not-a-real-token"), ("/second", None)] + + +def test_the_conformance_workflow_gives_the_lookup_its_token() -> None: + """Six jobs ask the API from addresses shared with other runners: unauthenticated, one is refused.""" + workflow = (HERE.parents[1] / ".github" / "workflows" + / "agentic-datacenter-benchmark-conformance.yml").read_text() # fmt: skip + assert "GITHUB_TOKEN: ${{ github.token }}" in workflow + assert "contents: read" in workflow + + +# --- Third review: the label, the attesting ref, nested JSON, and what no test caught ---------- + +LLM = ("result with a language-model agent, reported apart from the scripted agents, " + "not a benchmark result") # fmt: skip +FACILITY = "result on a facility of its owner, not a benchmark result" + + +@pytest.mark.parametrize( + "label", + [LLM, FACILITY, f"{FACILITY}; {LLM}", "development run, not a benchmark result", + "Benchmark result", "benchmark result ", "example record"], +) +def test_only_the_label_of_a_benchmark_result_is_accepted(label: str) -> None: + """A frozen run with a language-model agent, or on a facility of its owner, keeps + ``frozen: true`` but is not a benchmark result: only the exact label bench.py writes + for one is accepted.""" + with pytest.raises(ValueError, match="not a benchmark result"): + adc_reference.make(make_examples.RECORD_URL, _record(label=label)) + assert adc_reference.record_problems(_record(label="benchmark result")) == [] + + +def test_a_boolean_card_schema_version_is_not_one() -> None: + """``True`` is an int to isinstance; it is not a card_schema_version.""" + assert adc_reference.record_problems(_record(card_schema_version=True)) == [ + "the record names no card_schema_version" + ] + + +@pytest.mark.parametrize("bad", ["A" * 64, "g" * 64, "a" * 63, "a" * 65, 7, None]) +def test_a_file_hash_that_is_not_a_lowercase_hex_sha256_is_refused(bad: object) -> None: + files = {**json.loads(SOURCE)["files"], "summary.md": bad} + assert adc_reference.record_problems(_record(files=files)) == [ + "a file of the record has no SHA-256" + ] + + +DEEP = b"[" * 200_000 + + +def test_deeply_nested_json_in_the_record_is_reported_not_a_crash() -> None: + assert adc_reference.record_problems(DEEP) == ["not JSON"] + with pytest.raises(ValueError, match="not JSON"): + adc_reference.make(make_examples.RECORD_URL, DEEP) + entry = {**_load("01-result-cited.json")["references"][0]} + entry["digest"] = adc_reference.digest(DEEP) + assert adc_reference.check(entry, lambda url: DEEP) == ["not JSON"] + + +@pytest.mark.parametrize("where", ["attestations", "repository", "statement"]) +def test_deeply_nested_json_in_an_api_answer_is_reported_not_a_crash(where: str) -> None: + (entry,) = _load("01-result-cited.json")["references"] + import base64 + + nested = {"bundle": {"dsseEnvelope": {"payload": base64.b64encode(DEEP).decode()}}} + + def serve(url: str) -> bytes: + if url == make_examples.RECORD_URL: + return SOURCE + if url.startswith(adc_reference.REPOSITORY.format(repo="example-org/example-gate") + "/"): + if where == "attestations": + return DEEP + return json.dumps({"attestations": [nested]}).encode() + return DEEP if where == "repository" else b'{"default_branch": "main"}' + + problems = adc_reference.check(entry, serve, attestations=True) + assert len(problems) == 1 and problems[0].startswith("attestations"), problems + if where != "statement": + assert problems[0].endswith("RecursionError"), problems + + +ADC = "agentic-datacenter/agentic-datacenter" +BENCH = ".github/workflows/bench-runner.yml" + + +@pytest.mark.parametrize( + ("ref", "builder", "holds"), + [ + ("refs/heads/main", None, True), + ("refs/heads/repro/remora-statements-only", None, False), + ("refs/pull/12/merge", None, False), + ("refs/tags/v1.7.0", None, False), + # The builder must be exactly {repository}/{path}@{ref}. + ("refs/heads/main", f"https://github.com/{ADC}/{BENCH}@refs/heads/main-evil", False), + ("refs/heads/main", f"https://github.com/{ADC}/{BENCH}@refs/heads/main/x", False), + ("refs/heads/main", f"https://github.com/{ADC}/{BENCH}@refs/heads/feature", False), + ], +) +def test_agentic_datacenter_s_results_must_be_attested_from_main( + ref: str, builder: str | None, holds: bool +) -> None: + """A branch, a pull request or a tag can change what bench-runner.yml runs; only main counts.""" + record = "a" * 64 + attestation = _attestation(f"https://github.com/{ADC}", BENCH, record, ref, builder) + problems = adc_reference.attestation_problems( + [attestation], ADC, "sha256:" + record, "refs/heads/main") + assert (problems == []) is holds, problems + + +def test_the_published_record_s_two_attestations_hold_by_the_one_from_main() -> None: + """The published record has one attestation from main and one from a feature branch.""" + record = "a" * 64 + feature = _attestation(f"https://github.com/{ADC}", BENCH, record, + "refs/heads/repro/remora-statements-only") # fmt: skip + main = _attestation(f"https://github.com/{ADC}", BENCH, record) + assert adc_reference.attestation_problems([feature], ADC, "sha256:" + record, + "refs/heads/main") == [ # fmt: skip + f"attestations: made by {ADC}:{BENCH}@refs/heads/repro/remora-statements-only, " + f"not by {ADC}:{BENCH}@refs/heads/main" + ] + assert adc_reference.attestation_problems([feature, main], ADC, "sha256:" + record, + "refs/heads/main") == [] # fmt: skip + + +@pytest.mark.parametrize( + ("ref", "holds"), + [("refs/heads/trunk", True), ("refs/heads/main", False), ("refs/heads/feature", False), + ("refs/pull/3/merge", False), ("refs/tags/v1", False)], +) +def test_another_repository_s_result_must_be_attested_from_its_default_branch( + ref: str, holds: bool +) -> None: + """For a repository not in WORKFLOWS, the ref is its default branch, as the API names it.""" + (entry,) = _load("01-result-cited.json")["references"] + record = entry["digest"][len("sha256:"):] + answer = {"attestations": [_attestation( + "https://github.com/example-org/example-gate", ".github/workflows/bench.yml", record, ref)]} + asked: list[str] = [] + + def serve(url: str) -> bytes: + asked.append(url) + if url == make_examples.RECORD_URL: + return SOURCE + if url == adc_reference.REPOSITORY.format(repo="example-org/example-gate"): + return b'{"default_branch": "trunk"}' + return json.dumps(answer).encode() + + problems = adc_reference.check(entry, serve, attestations=True) + assert (problems == []) is holds, problems + assert adc_reference.REPOSITORY.format(repo="example-org/example-gate") in asked + + +@pytest.mark.parametrize("answer", [b"{}", b'{"default_branch": ""}', b"[]", b"null"]) +def test_a_repository_without_a_default_branch_is_reported(answer: bytes) -> None: + (entry,) = _load("01-result-cited.json")["references"] + record = entry["digest"][len("sha256:"):] + found = {"attestations": [_attestation( + "https://github.com/example-org/example-gate", ".github/workflows/bench.yml", record)]} + + def serve(url: str) -> bytes: + if url == make_examples.RECORD_URL: + return SOURCE + if url == adc_reference.REPOSITORY.format(repo="example-org/example-gate"): + return answer + return json.dumps(found).encode() + + assert adc_reference.check(entry, serve, attestations=True) == [ + "attestations unresolved: the GitHub API names no default branch" + ] + + +def test_an_attestation_of_another_predicate_type_does_not_count() -> None: + record = "a" * 64 + other = _attestation(f"https://github.com/{ADC}", BENCH, record, + predicate_type="https://spdx.dev/Document/v2.3") # fmt: skip + assert adc_reference.attestation_problems([other], ADC, "sha256:" + record, + "refs/heads/main") == [ # fmt: skip + "attestations: none states the record as its subject and the workflow that made it" + ] + + +@pytest.mark.parametrize( + ("content", "said"), + [(None, "FileNotFoundError"), ("{not json", "JSONDecodeError"), + ("[1, 2]", "not a JSON object"), ("null", "not a JSON object"), ("[" * 200_000, "RecursionError")], +) +def test_check_on_an_entry_it_cannot_read_exits_2_not_1( + content: str | None, said: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """Exit 1 means problems were found; an entry that cannot be read is exit 2, as for make.""" + path = tmp_path / "entry.json" + if content is not None: + path.write_text(content) + assert adc_reference.main(["check", str(path)]) == 2 + out = capsys.readouterr() + assert out.out == "" and said in out.err + + +def test_the_conformance_workflow_does_not_keep_the_checkout_s_credentials() -> None: + """The job runs a pull request's code; the token must not stay in .git/config.""" + workflow = (HERE.parents[1] / ".github" / "workflows" + / "agentic-datacenter-benchmark-conformance.yml").read_text() # fmt: skip + assert "persist-credentials: false" in workflow diff --git a/marketplace/catalog.json b/marketplace/catalog.json index 86aae64..fa70851 100644 --- a/marketplace/catalog.json +++ b/marketplace/catalog.json @@ -1,6 +1,6 @@ { "catalog_version": 1, - "count": 51, + "count": 52, "integrations": [ { "name": "Claude Code", @@ -250,6 +250,30 @@ "cost" ] }, + { + "name": "Agentic-Datacenter benchmark result references", + "package_name": "Agentic-Datacenter benchmark result references", + "vendor": "Agentic-Datacenter", + "description": "A TRACE Trust Record of an agent-governance gate cites the gate's published Agentic-Datacenter benchmark result through a references entry, checked for digest match against the result's record.", + "path": "integrations/agentic-datacenter-benchmark", + "url": "https://github.com/agentrust-io/integrations/tree/main/integrations/agentic-datacenter-benchmark", + "homepage": null, + "repository": "https://github.com/agentic-datacenter/agentic-datacenter", + "tier": "community", + "stack": [ + "TRACE" + ], + "category": "Evidence & receipts", + "mark": "ADC", + "featured": null, + "keywords": [ + "benchmark", + "governance-gate", + "references", + "provenance", + "simulation" + ] + }, { "name": "AI Agent Incident Register", "package_name": "AI Agent Incident Register",