modelcertify 0.1.0__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.
- modelcertify/__init__.py +63 -0
- modelcertify/attestation.py +148 -0
- modelcertify/certify.py +356 -0
- modelcertify/cli.py +196 -0
- modelcertify/proof.py +193 -0
- modelcertify/py.typed +0 -0
- modelcertify-0.1.0.dist-info/METADATA +147 -0
- modelcertify-0.1.0.dist-info/RECORD +12 -0
- modelcertify-0.1.0.dist-info/WHEEL +5 -0
- modelcertify-0.1.0.dist-info/entry_points.txt +2 -0
- modelcertify-0.1.0.dist-info/licenses/LICENSE +202 -0
- modelcertify-0.1.0.dist-info/top_level.txt +1 -0
modelcertify/__init__.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""modelcertify: certify the supply chain of a trained model.
|
|
2
|
+
|
|
3
|
+
A model is only as trustworthy as the run that produced it. modelcertify
|
|
4
|
+
makes that run auditable:
|
|
5
|
+
|
|
6
|
+
* :mod:`modelcertify.proof` builds a **run proof**: every artefact of the run
|
|
7
|
+
hashed, combined into a Merkle **root** that changes if any artefact does.
|
|
8
|
+
* :mod:`modelcertify.attestation` lets an issuer **vouch** for a proof root,
|
|
9
|
+
signed so tampering is detectable.
|
|
10
|
+
* :mod:`modelcertify.certify` checks a run against a **policy** -- metric,
|
|
11
|
+
artefact and provenance gates -- and issues a **certificate** that records
|
|
12
|
+
every gate and how it came out.
|
|
13
|
+
|
|
14
|
+
The certificate never overstates: it carries the gate results, the proof root
|
|
15
|
+
it is bound to, and the issuer that signed it.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
20
|
+
|
|
21
|
+
from .attestation import (
|
|
22
|
+
Attestation,
|
|
23
|
+
AttestationError,
|
|
24
|
+
sign_body,
|
|
25
|
+
verify_body,
|
|
26
|
+
)
|
|
27
|
+
from .certify import (
|
|
28
|
+
Certificate,
|
|
29
|
+
Evidence,
|
|
30
|
+
Gate,
|
|
31
|
+
GateResult,
|
|
32
|
+
Policy,
|
|
33
|
+
PolicyResult,
|
|
34
|
+
certify,
|
|
35
|
+
evidence_from_dict,
|
|
36
|
+
load_evidence,
|
|
37
|
+
)
|
|
38
|
+
from .proof import Artifact, RunProof, merkle_root, sha256_bytes, sha256_file
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"__version__",
|
|
42
|
+
# proof
|
|
43
|
+
"Artifact",
|
|
44
|
+
"RunProof",
|
|
45
|
+
"merkle_root",
|
|
46
|
+
"sha256_bytes",
|
|
47
|
+
"sha256_file",
|
|
48
|
+
# attestation
|
|
49
|
+
"Attestation",
|
|
50
|
+
"AttestationError",
|
|
51
|
+
"sign_body",
|
|
52
|
+
"verify_body",
|
|
53
|
+
# certification
|
|
54
|
+
"Certificate",
|
|
55
|
+
"Evidence",
|
|
56
|
+
"Gate",
|
|
57
|
+
"GateResult",
|
|
58
|
+
"Policy",
|
|
59
|
+
"PolicyResult",
|
|
60
|
+
"certify",
|
|
61
|
+
"evidence_from_dict",
|
|
62
|
+
"load_evidence",
|
|
63
|
+
]
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Attestations: a signed statement about a run.
|
|
2
|
+
|
|
3
|
+
An :class:`Attestation` says "issuer X vouches that run Y, whose proof roots
|
|
4
|
+
to Z, meets statement S". It is signed with an HMAC-SHA256 over the
|
|
5
|
+
canonical body, so anyone holding the issuer's key can verify it and nobody
|
|
6
|
+
else can forge it.
|
|
7
|
+
|
|
8
|
+
This is deliberately not a public-key signature. modelcertify has to verify
|
|
9
|
+
attestations from several organisations, and shipping a key-distribution
|
|
10
|
+
ceremony before there is a customer to use it is how key ceremonies get
|
|
11
|
+
mired. The interface is narrow enough to swap in Ed25519 later: only
|
|
12
|
+
:meth:`Attestation.sign` and :meth:`Attestation.verify_signature` know how
|
|
13
|
+
the bytes are covered.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import datetime as _dt
|
|
18
|
+
import hashlib
|
|
19
|
+
import hmac
|
|
20
|
+
import json
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
__all__ = ["Attestation", "AttestationError", "sign_body", "verify_body"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AttestationError(ValueError):
|
|
28
|
+
"""Raised when an attestation is malformed or its signature is wrong."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _canonical(payload: dict[str, Any]) -> bytes:
|
|
32
|
+
return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def sign_body(body: dict[str, Any], key: bytes) -> str:
|
|
36
|
+
"""Sign an attestation body with the issuer's key."""
|
|
37
|
+
if not key:
|
|
38
|
+
raise AttestationError("an attestation key must not be empty")
|
|
39
|
+
return hmac.new(key, _canonical(body), hashlib.sha256).hexdigest()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def verify_body(body: dict[str, Any], signature: str, key: bytes) -> bool:
|
|
43
|
+
"""Check a signature over an attestation body."""
|
|
44
|
+
try:
|
|
45
|
+
expected = sign_body(body, key)
|
|
46
|
+
except AttestationError:
|
|
47
|
+
return False
|
|
48
|
+
return hmac.compare_digest(expected, signature)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Attestation:
|
|
53
|
+
"""A signed statement about a run."""
|
|
54
|
+
|
|
55
|
+
issuer: str
|
|
56
|
+
run_id: str
|
|
57
|
+
subject: str
|
|
58
|
+
proof_root: str
|
|
59
|
+
policy_id: str = ""
|
|
60
|
+
issued_at: str = ""
|
|
61
|
+
claims: dict[str, Any] = field(default_factory=dict)
|
|
62
|
+
signature: str = ""
|
|
63
|
+
|
|
64
|
+
def __post_init__(self) -> None:
|
|
65
|
+
if not self.issuer:
|
|
66
|
+
raise AttestationError("an attestation needs an issuer")
|
|
67
|
+
if not self.run_id:
|
|
68
|
+
raise AttestationError("an attestation needs a run id")
|
|
69
|
+
if not self.proof_root:
|
|
70
|
+
raise AttestationError("an attestation needs a proof root")
|
|
71
|
+
|
|
72
|
+
def body(self) -> dict[str, Any]:
|
|
73
|
+
"""The signed part of the attestation."""
|
|
74
|
+
return {
|
|
75
|
+
"issuer": self.issuer,
|
|
76
|
+
"run_id": self.run_id,
|
|
77
|
+
"subject": self.subject,
|
|
78
|
+
"proof_root": self.proof_root,
|
|
79
|
+
"policy_id": self.policy_id,
|
|
80
|
+
"issued_at": self.issued_at,
|
|
81
|
+
"claims": dict(self.claims),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
def sign(self, key: bytes) -> Attestation:
|
|
85
|
+
"""Return a copy of this attestation, signed with ``key``."""
|
|
86
|
+
return Attestation(
|
|
87
|
+
issuer=self.issuer,
|
|
88
|
+
run_id=self.run_id,
|
|
89
|
+
subject=self.subject,
|
|
90
|
+
proof_root=self.proof_root,
|
|
91
|
+
policy_id=self.policy_id,
|
|
92
|
+
issued_at=self.issued_at,
|
|
93
|
+
claims=dict(self.claims),
|
|
94
|
+
signature=sign_body(self.body(), key),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
def verify_signature(self, key: bytes) -> bool:
|
|
98
|
+
"""Whether the signature is valid for ``key``."""
|
|
99
|
+
return verify_body(self.body(), self.signature, key)
|
|
100
|
+
|
|
101
|
+
def verify_proof(self, proof_root: str) -> bool:
|
|
102
|
+
"""Whether this attestation refers to the given proof root."""
|
|
103
|
+
return hmac.compare_digest(self.proof_root, proof_root)
|
|
104
|
+
|
|
105
|
+
def to_dict(self) -> dict[str, Any]:
|
|
106
|
+
payload = self.body()
|
|
107
|
+
payload["signature"] = self.signature
|
|
108
|
+
return payload
|
|
109
|
+
|
|
110
|
+
@classmethod
|
|
111
|
+
def from_dict(cls, raw: dict[str, Any]) -> Attestation:
|
|
112
|
+
try:
|
|
113
|
+
return cls(
|
|
114
|
+
issuer=str(raw["issuer"]),
|
|
115
|
+
run_id=str(raw["run_id"]),
|
|
116
|
+
subject=str(raw["subject"]),
|
|
117
|
+
proof_root=str(raw["proof_root"]),
|
|
118
|
+
policy_id=str(raw.get("policy_id", "")),
|
|
119
|
+
issued_at=str(raw.get("issued_at", "")),
|
|
120
|
+
claims=dict(raw.get("claims") or {}),
|
|
121
|
+
signature=str(raw.get("signature", "")),
|
|
122
|
+
)
|
|
123
|
+
except (KeyError, TypeError) as exc:
|
|
124
|
+
raise AttestationError(f"invalid attestation: {exc}") from exc
|
|
125
|
+
|
|
126
|
+
@classmethod
|
|
127
|
+
def issue(
|
|
128
|
+
cls,
|
|
129
|
+
*,
|
|
130
|
+
issuer: str,
|
|
131
|
+
run_id: str,
|
|
132
|
+
subject: str,
|
|
133
|
+
proof_root: str,
|
|
134
|
+
policy_id: str = "",
|
|
135
|
+
claims: dict[str, Any] | None = None,
|
|
136
|
+
issued_at: str | None = None,
|
|
137
|
+
) -> Attestation:
|
|
138
|
+
"""Create an unsigned attestation."""
|
|
139
|
+
stamp = issued_at or _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds")
|
|
140
|
+
return cls(
|
|
141
|
+
issuer=issuer,
|
|
142
|
+
run_id=run_id,
|
|
143
|
+
subject=subject,
|
|
144
|
+
proof_root=proof_root,
|
|
145
|
+
policy_id=policy_id,
|
|
146
|
+
issued_at=stamp,
|
|
147
|
+
claims=dict(claims or {}),
|
|
148
|
+
)
|
modelcertify/certify.py
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
"""Certification: the policy, the evidence, the certificate.
|
|
2
|
+
|
|
3
|
+
A policy is a set of gates. Each gate checks one fact about the run:
|
|
4
|
+
|
|
5
|
+
* a **metric gate** compares a measured metric against a threshold
|
|
6
|
+
(``loss <= 0.5``, ``eval_accuracy >= 0.92``);
|
|
7
|
+
* an **artifact gate** requires a named artefact to exist in the proof;
|
|
8
|
+
* a **provenance gate** requires a named field in the run's provenance
|
|
9
|
+
record (dataset id, licence, consent reference, ...).
|
|
10
|
+
|
|
11
|
+
A run is certified when every gate passes. The result is a
|
|
12
|
+
:class:`Certificate`: the attestation, the policy, and the outcome of every
|
|
13
|
+
gate, so a reader can see *why* something was certified and not just that
|
|
14
|
+
it was.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import datetime as _dt
|
|
19
|
+
import json
|
|
20
|
+
from collections.abc import Mapping
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from .attestation import Attestation
|
|
26
|
+
from .proof import Artifact, RunProof
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"Certificate",
|
|
30
|
+
"Evidence",
|
|
31
|
+
"Gate",
|
|
32
|
+
"GateResult",
|
|
33
|
+
"Policy",
|
|
34
|
+
"PolicyResult",
|
|
35
|
+
"certify",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Evidence:
|
|
41
|
+
"""Everything a policy is allowed to look at."""
|
|
42
|
+
|
|
43
|
+
proof: RunProof
|
|
44
|
+
metrics: Mapping[str, Any] = field(default_factory=dict)
|
|
45
|
+
provenance: Mapping[str, Any] = field(default_factory=dict)
|
|
46
|
+
|
|
47
|
+
def metric(self, name: str) -> Any:
|
|
48
|
+
return self.metrics.get(name)
|
|
49
|
+
|
|
50
|
+
def artifact(self, name: str) -> Artifact | None:
|
|
51
|
+
return self.proof.artifact(name)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class Gate:
|
|
56
|
+
"""One check in a policy."""
|
|
57
|
+
|
|
58
|
+
name: str
|
|
59
|
+
kind: str # metric | artifact | provenance
|
|
60
|
+
field: str = ""
|
|
61
|
+
op: str = ">="
|
|
62
|
+
threshold: Any = None
|
|
63
|
+
|
|
64
|
+
def __post_init__(self) -> None:
|
|
65
|
+
if self.kind not in ("metric", "artifact", "provenance"):
|
|
66
|
+
raise ValueError(f"unknown gate kind {self.kind!r}")
|
|
67
|
+
if not self.name:
|
|
68
|
+
raise ValueError("a gate needs a name")
|
|
69
|
+
|
|
70
|
+
def evaluate(self, evidence: Evidence) -> GateResult:
|
|
71
|
+
"""Run this gate against the evidence."""
|
|
72
|
+
if self.kind == "metric":
|
|
73
|
+
return self._evaluate_metric(evidence)
|
|
74
|
+
if self.kind == "artifact":
|
|
75
|
+
present = evidence.artifact(self.field) is not None
|
|
76
|
+
return GateResult(
|
|
77
|
+
gate=self.name,
|
|
78
|
+
passed=present,
|
|
79
|
+
detail=(
|
|
80
|
+
f"artifact {self.field!r} is present"
|
|
81
|
+
if present
|
|
82
|
+
else f"artifact {self.field!r} is missing"
|
|
83
|
+
),
|
|
84
|
+
)
|
|
85
|
+
value = evidence.provenance.get(self.field)
|
|
86
|
+
if self.threshold is None:
|
|
87
|
+
# A provenance gate without a threshold asks for the field to be
|
|
88
|
+
# there: "this run recorded a dataset id".
|
|
89
|
+
present = value is not None
|
|
90
|
+
return GateResult(
|
|
91
|
+
gate=self.name,
|
|
92
|
+
passed=present,
|
|
93
|
+
detail=(
|
|
94
|
+
f"provenance {self.field!r} is recorded"
|
|
95
|
+
if present
|
|
96
|
+
else f"provenance {self.field!r} is missing"
|
|
97
|
+
),
|
|
98
|
+
)
|
|
99
|
+
return self._compare(value, f"provenance {self.field!r}")
|
|
100
|
+
|
|
101
|
+
def _evaluate_metric(self, evidence: Evidence) -> GateResult:
|
|
102
|
+
if self.field not in evidence.metrics:
|
|
103
|
+
return GateResult(
|
|
104
|
+
gate=self.name,
|
|
105
|
+
passed=False,
|
|
106
|
+
detail=f"metric {self.field!r} was not reported",
|
|
107
|
+
)
|
|
108
|
+
value = evidence.metrics[self.field]
|
|
109
|
+
return self._compare(value, f"metric {self.field!r}")
|
|
110
|
+
|
|
111
|
+
def _compare(self, value: Any, label: str) -> GateResult:
|
|
112
|
+
if value is None:
|
|
113
|
+
return GateResult(gate=self.name, passed=False, detail=f"{label} is missing")
|
|
114
|
+
threshold = self.threshold
|
|
115
|
+
try:
|
|
116
|
+
if self.op == ">=":
|
|
117
|
+
passed = float(value) >= float(threshold)
|
|
118
|
+
elif self.op == "<=":
|
|
119
|
+
passed = float(value) <= float(threshold)
|
|
120
|
+
elif self.op == ">":
|
|
121
|
+
passed = float(value) > float(threshold)
|
|
122
|
+
elif self.op == "<":
|
|
123
|
+
passed = float(value) < float(threshold)
|
|
124
|
+
elif self.op == "==":
|
|
125
|
+
passed = value == threshold
|
|
126
|
+
elif self.op == "!=":
|
|
127
|
+
passed = value != threshold
|
|
128
|
+
elif self.op == "in":
|
|
129
|
+
passed = value in threshold
|
|
130
|
+
else:
|
|
131
|
+
raise ValueError(f"unknown operator {self.op!r}")
|
|
132
|
+
except (TypeError, ValueError) as exc:
|
|
133
|
+
return GateResult(gate=self.name, passed=False, detail=f"{label}: {exc}")
|
|
134
|
+
return GateResult(
|
|
135
|
+
gate=self.name,
|
|
136
|
+
passed=passed,
|
|
137
|
+
detail=f"{label} = {value!r} {self.op} {threshold!r} -> {'pass' if passed else 'fail'}",
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
def to_dict(self) -> dict[str, Any]:
|
|
141
|
+
return {
|
|
142
|
+
"name": self.name,
|
|
143
|
+
"kind": self.kind,
|
|
144
|
+
"field": self.field,
|
|
145
|
+
"op": self.op,
|
|
146
|
+
"threshold": self.threshold,
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
@classmethod
|
|
150
|
+
def from_dict(cls, raw: Mapping[str, Any]) -> Gate:
|
|
151
|
+
return cls(
|
|
152
|
+
name=str(raw["name"]),
|
|
153
|
+
kind=str(raw["kind"]),
|
|
154
|
+
field=str(raw.get("field", "")),
|
|
155
|
+
op=str(raw.get("op", ">=")),
|
|
156
|
+
threshold=raw.get("threshold"),
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@dataclass(frozen=True)
|
|
161
|
+
class GateResult:
|
|
162
|
+
"""The outcome of one gate."""
|
|
163
|
+
|
|
164
|
+
gate: str
|
|
165
|
+
passed: bool
|
|
166
|
+
detail: str = ""
|
|
167
|
+
|
|
168
|
+
def to_dict(self) -> dict[str, Any]:
|
|
169
|
+
return {"gate": self.gate, "passed": self.passed, "detail": self.detail}
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@dataclass(frozen=True)
|
|
173
|
+
class Policy:
|
|
174
|
+
"""A named set of gates."""
|
|
175
|
+
|
|
176
|
+
policy_id: str
|
|
177
|
+
name: str = ""
|
|
178
|
+
version: str = "1"
|
|
179
|
+
gates: tuple[Gate, ...] = ()
|
|
180
|
+
required_artifacts: tuple[str, ...] = ()
|
|
181
|
+
|
|
182
|
+
def __post_init__(self) -> None:
|
|
183
|
+
if not self.policy_id:
|
|
184
|
+
raise ValueError("a policy needs a policy_id")
|
|
185
|
+
|
|
186
|
+
def evaluate(self, evidence: Evidence) -> PolicyResult:
|
|
187
|
+
"""Run every gate against the evidence."""
|
|
188
|
+
results: list[GateResult] = []
|
|
189
|
+
for required in self.required_artifacts:
|
|
190
|
+
present = evidence.artifact(required) is not None
|
|
191
|
+
results.append(
|
|
192
|
+
GateResult(
|
|
193
|
+
gate=f"required_artifact:{required}",
|
|
194
|
+
passed=present,
|
|
195
|
+
detail=(
|
|
196
|
+
f"artifact {required!r} is present"
|
|
197
|
+
if present
|
|
198
|
+
else f"artifact {required!r} is missing"
|
|
199
|
+
),
|
|
200
|
+
)
|
|
201
|
+
)
|
|
202
|
+
for gate in self.gates:
|
|
203
|
+
results.append(gate.evaluate(evidence))
|
|
204
|
+
failed = tuple(result.gate for result in results if not result.passed)
|
|
205
|
+
return PolicyResult(passed=not failed, results=tuple(results), failed=failed)
|
|
206
|
+
|
|
207
|
+
def to_dict(self) -> dict[str, Any]:
|
|
208
|
+
return {
|
|
209
|
+
"policy_id": self.policy_id,
|
|
210
|
+
"name": self.name,
|
|
211
|
+
"version": self.version,
|
|
212
|
+
"required_artifacts": list(self.required_artifacts),
|
|
213
|
+
"gates": [gate.to_dict() for gate in self.gates],
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
@classmethod
|
|
217
|
+
def from_dict(cls, raw: Mapping[str, Any]) -> Policy:
|
|
218
|
+
return cls(
|
|
219
|
+
policy_id=str(raw["policy_id"]),
|
|
220
|
+
name=str(raw.get("name", "")),
|
|
221
|
+
version=str(raw.get("version", "1")),
|
|
222
|
+
gates=tuple(Gate.from_dict(entry) for entry in raw.get("gates", [])),
|
|
223
|
+
required_artifacts=tuple(
|
|
224
|
+
str(entry) for entry in raw.get("required_artifacts", [])
|
|
225
|
+
),
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
@classmethod
|
|
229
|
+
def read(cls, path: str | Path) -> Policy:
|
|
230
|
+
return cls.from_dict(json.loads(Path(path).read_text()))
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@dataclass(frozen=True)
|
|
234
|
+
class PolicyResult:
|
|
235
|
+
"""The outcome of evaluating a policy."""
|
|
236
|
+
|
|
237
|
+
passed: bool
|
|
238
|
+
results: tuple[GateResult, ...] = ()
|
|
239
|
+
failed: tuple[str, ...] = ()
|
|
240
|
+
|
|
241
|
+
def to_dict(self) -> dict[str, Any]:
|
|
242
|
+
return {
|
|
243
|
+
"passed": self.passed,
|
|
244
|
+
"failed": list(self.failed),
|
|
245
|
+
"results": [result.to_dict() for result in self.results],
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@dataclass(frozen=True)
|
|
250
|
+
class Certificate:
|
|
251
|
+
"""A certification: an attestation plus the policy outcome."""
|
|
252
|
+
|
|
253
|
+
attestation: Attestation
|
|
254
|
+
policy: Policy
|
|
255
|
+
result: PolicyResult
|
|
256
|
+
issued_at: str = ""
|
|
257
|
+
certificate_id: str = ""
|
|
258
|
+
|
|
259
|
+
@property
|
|
260
|
+
def certified(self) -> bool:
|
|
261
|
+
return self.result.passed
|
|
262
|
+
|
|
263
|
+
def to_dict(self) -> dict[str, Any]:
|
|
264
|
+
return {
|
|
265
|
+
"certificate_id": self.certificate_id,
|
|
266
|
+
"issued_at": self.issued_at,
|
|
267
|
+
"certified": self.certified,
|
|
268
|
+
"attestation": self.attestation.to_dict(),
|
|
269
|
+
"policy": self.policy.to_dict(),
|
|
270
|
+
"result": self.result.to_dict(),
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
@classmethod
|
|
274
|
+
def from_dict(cls, raw: Mapping[str, Any]) -> Certificate:
|
|
275
|
+
return cls(
|
|
276
|
+
attestation=Attestation.from_dict(raw["attestation"]),
|
|
277
|
+
policy=Policy.from_dict(raw["policy"]),
|
|
278
|
+
result=PolicyResult(
|
|
279
|
+
passed=bool(raw["result"]["passed"]),
|
|
280
|
+
results=tuple(
|
|
281
|
+
GateResult(
|
|
282
|
+
gate=str(entry["gate"]),
|
|
283
|
+
passed=bool(entry["passed"]),
|
|
284
|
+
detail=str(entry.get("detail", "")),
|
|
285
|
+
)
|
|
286
|
+
for entry in raw["result"].get("results", [])
|
|
287
|
+
),
|
|
288
|
+
failed=tuple(str(entry) for entry in raw["result"].get("failed", [])),
|
|
289
|
+
),
|
|
290
|
+
issued_at=str(raw.get("issued_at", "")),
|
|
291
|
+
certificate_id=str(raw.get("certificate_id", "")),
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
def write(self, path: str | Path) -> Path:
|
|
295
|
+
target = Path(path)
|
|
296
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
297
|
+
target.write_text(json.dumps(self.to_dict(), indent=2) + "\n")
|
|
298
|
+
return target
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def certify(
|
|
302
|
+
policy: Policy,
|
|
303
|
+
evidence: Evidence,
|
|
304
|
+
*,
|
|
305
|
+
issuer: str,
|
|
306
|
+
subject: str,
|
|
307
|
+
key: bytes | None = None,
|
|
308
|
+
claims: Mapping[str, Any] | None = None,
|
|
309
|
+
) -> Certificate:
|
|
310
|
+
"""Evaluate a policy against the evidence and issue a certificate.
|
|
311
|
+
|
|
312
|
+
The attestation is signed when ``key`` is given. A policy that fails
|
|
313
|
+
still produces a certificate: the point of a certificate is to record
|
|
314
|
+
the outcome, including a refusal.
|
|
315
|
+
"""
|
|
316
|
+
result = policy.evaluate(evidence)
|
|
317
|
+
stamp = _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds")
|
|
318
|
+
attestation = Attestation.issue(
|
|
319
|
+
issuer=issuer,
|
|
320
|
+
run_id=evidence.proof.run_id,
|
|
321
|
+
subject=subject,
|
|
322
|
+
proof_root=evidence.proof.root,
|
|
323
|
+
policy_id=policy.policy_id,
|
|
324
|
+
claims=dict(claims or {}),
|
|
325
|
+
issued_at=stamp,
|
|
326
|
+
)
|
|
327
|
+
if key:
|
|
328
|
+
attestation = attestation.sign(key)
|
|
329
|
+
certificate_id = f"cert-{evidence.proof.run_id}-{policy.policy_id}"
|
|
330
|
+
return Certificate(
|
|
331
|
+
attestation=attestation,
|
|
332
|
+
policy=policy,
|
|
333
|
+
result=result,
|
|
334
|
+
issued_at=stamp,
|
|
335
|
+
certificate_id=certificate_id,
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def load_evidence(path: str | Path) -> Evidence:
|
|
340
|
+
"""Load an evidence document (proof + metrics + provenance)."""
|
|
341
|
+
raw = json.loads(Path(path).read_text())
|
|
342
|
+
proof = RunProof.from_dict(raw["proof"])
|
|
343
|
+
return Evidence(
|
|
344
|
+
proof=proof,
|
|
345
|
+
metrics=dict(raw.get("metrics") or {}),
|
|
346
|
+
provenance=dict(raw.get("provenance") or {}),
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def evidence_from_dict(raw: Mapping[str, Any]) -> Evidence:
|
|
351
|
+
"""Build evidence from a document."""
|
|
352
|
+
return Evidence(
|
|
353
|
+
proof=RunProof.from_dict(raw["proof"]),
|
|
354
|
+
metrics=dict(raw.get("metrics") or {}),
|
|
355
|
+
provenance=dict(raw.get("provenance") or {}),
|
|
356
|
+
)
|
modelcertify/cli.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""``modelcertify`` command line interface.
|
|
2
|
+
|
|
3
|
+
Subcommands:
|
|
4
|
+
|
|
5
|
+
``proof`` build a run proof from a directory of artefacts
|
|
6
|
+
``policy`` show a certification policy
|
|
7
|
+
``certify`` evaluate a policy against a run's evidence
|
|
8
|
+
``verify`` verify a certificate's signature
|
|
9
|
+
|
|
10
|
+
Every command supports ``--json``.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import sys
|
|
18
|
+
from collections.abc import Sequence
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from .certify import Certificate, Policy, certify, load_evidence
|
|
23
|
+
from .proof import Artifact, RunProof
|
|
24
|
+
|
|
25
|
+
__all__ = ["build_parser", "main"]
|
|
26
|
+
|
|
27
|
+
DEFAULT_POLICY: dict[str, Any] = {
|
|
28
|
+
"policy_id": "baseline",
|
|
29
|
+
"name": "Baseline release policy",
|
|
30
|
+
"version": "1",
|
|
31
|
+
"required_artifacts": [],
|
|
32
|
+
"gates": [],
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _key(raw: str | None) -> bytes:
|
|
37
|
+
"""The signing key: hex on the command line, or $MODELCERTIFY_KEY."""
|
|
38
|
+
value = raw or os.environ.get("MODELCERTIFY_KEY", "")
|
|
39
|
+
if not value:
|
|
40
|
+
raise ValueError("no signing key: pass --key or set MODELCERTIFY_KEY")
|
|
41
|
+
try:
|
|
42
|
+
return bytes.fromhex(value)
|
|
43
|
+
except ValueError as exc:
|
|
44
|
+
raise ValueError(f"the signing key must be hex: {exc}") from exc
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
48
|
+
parser = argparse.ArgumentParser(
|
|
49
|
+
prog="modelcertify",
|
|
50
|
+
description="Certify the supply chain of a trained model.",
|
|
51
|
+
)
|
|
52
|
+
parser.add_argument("--json", action="store_true", help="emit JSON on stdout")
|
|
53
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
54
|
+
|
|
55
|
+
proof = sub.add_parser("proof", help="build a run proof from a directory")
|
|
56
|
+
proof.add_argument("--run-id", required=True, help="identifier of the run")
|
|
57
|
+
proof.add_argument("--dir", required=True, help="directory of run artefacts")
|
|
58
|
+
proof.add_argument("--out", help="write the proof here")
|
|
59
|
+
proof.add_argument("--json", action="store_true", help="emit JSON on stdout")
|
|
60
|
+
|
|
61
|
+
policy = sub.add_parser("policy", help="show a certification policy")
|
|
62
|
+
policy.add_argument("--file", help="policy JSON file")
|
|
63
|
+
policy.add_argument("--json", action="store_true", help="emit JSON on stdout")
|
|
64
|
+
|
|
65
|
+
certify_cmd = sub.add_parser("certify", help="certify a run against a policy")
|
|
66
|
+
certify_cmd.add_argument("--evidence", required=True, help="evidence JSON file")
|
|
67
|
+
certify_cmd.add_argument("--policy", help="policy JSON file")
|
|
68
|
+
certify_cmd.add_argument("--issuer", required=True, help="who is certifying")
|
|
69
|
+
certify_cmd.add_argument("--subject", default="", help="what is being certified")
|
|
70
|
+
certify_cmd.add_argument("--key", help="signing key (hex)")
|
|
71
|
+
certify_cmd.add_argument("--out", help="write the certificate here")
|
|
72
|
+
certify_cmd.add_argument("--json", action="store_true", help="emit JSON on stdout")
|
|
73
|
+
|
|
74
|
+
verify = sub.add_parser("verify", help="verify a certificate")
|
|
75
|
+
verify.add_argument("--certificate", required=True, help="certificate JSON file")
|
|
76
|
+
verify.add_argument("--key", help="signing key (hex)")
|
|
77
|
+
verify.add_argument("--json", action="store_true", help="emit JSON on stdout")
|
|
78
|
+
|
|
79
|
+
return parser
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _cmd_proof(args: argparse.Namespace) -> int:
|
|
83
|
+
directory = Path(args.dir)
|
|
84
|
+
if not directory.is_dir():
|
|
85
|
+
raise FileNotFoundError(f"not a directory: {directory}")
|
|
86
|
+
artifacts = [
|
|
87
|
+
Artifact.from_file(path.name, path)
|
|
88
|
+
for path in sorted(directory.iterdir())
|
|
89
|
+
if path.is_file()
|
|
90
|
+
]
|
|
91
|
+
proof = RunProof.build(args.run_id, artifacts)
|
|
92
|
+
payload = proof.to_dict()
|
|
93
|
+
if args.out:
|
|
94
|
+
target = Path(args.out)
|
|
95
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
96
|
+
target.write_text(json.dumps(payload, indent=2) + "\n")
|
|
97
|
+
if args.json:
|
|
98
|
+
_emit_json(payload)
|
|
99
|
+
return 0
|
|
100
|
+
print(f"proof root: {proof.root}")
|
|
101
|
+
for artifact in proof.artifacts:
|
|
102
|
+
print(f" {artifact.name:<28} {artifact.digest}")
|
|
103
|
+
return 0
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _cmd_policy(args: argparse.Namespace) -> int:
|
|
107
|
+
if args.file:
|
|
108
|
+
policy = Policy.read(args.file)
|
|
109
|
+
payload = policy.to_dict()
|
|
110
|
+
else:
|
|
111
|
+
payload = DEFAULT_POLICY
|
|
112
|
+
if args.json:
|
|
113
|
+
_emit_json(payload)
|
|
114
|
+
return 0
|
|
115
|
+
print(json.dumps(payload, indent=2))
|
|
116
|
+
return 0
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _cmd_certify(args: argparse.Namespace) -> int:
|
|
120
|
+
evidence = load_evidence(args.evidence)
|
|
121
|
+
policy = Policy.read(args.policy) if args.policy else Policy.from_dict(DEFAULT_POLICY)
|
|
122
|
+
key = _key(args.key) if args.key or os.environ.get("MODELCERTIFY_KEY") else None
|
|
123
|
+
subject = args.subject or evidence.proof.run_id
|
|
124
|
+
certificate = certify(
|
|
125
|
+
policy,
|
|
126
|
+
evidence,
|
|
127
|
+
issuer=args.issuer,
|
|
128
|
+
subject=subject,
|
|
129
|
+
key=key,
|
|
130
|
+
)
|
|
131
|
+
if args.out:
|
|
132
|
+
certificate.write(args.out)
|
|
133
|
+
payload = certificate.to_dict()
|
|
134
|
+
if args.json:
|
|
135
|
+
_emit_json(payload)
|
|
136
|
+
return 0 if certificate.certified else 1
|
|
137
|
+
print(f"certified: {certificate.certified}")
|
|
138
|
+
for result in certificate.result.results:
|
|
139
|
+
print(f" [{'ok' if result.passed else 'FAIL'}] {result.gate}: {result.detail}")
|
|
140
|
+
return 0 if certificate.certified else 1
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _cmd_verify(args: argparse.Namespace) -> int:
|
|
144
|
+
certificate = Certificate.from_dict(
|
|
145
|
+
json.loads(Path(args.certificate).read_text())
|
|
146
|
+
)
|
|
147
|
+
key = _key(args.key) if args.key or os.environ.get("MODELCERTIFY_KEY") else None
|
|
148
|
+
verified = True
|
|
149
|
+
detail = "signature verified"
|
|
150
|
+
if key is not None:
|
|
151
|
+
verified = certificate.attestation.verify_signature(key)
|
|
152
|
+
detail = (
|
|
153
|
+
"signature verified"
|
|
154
|
+
if verified
|
|
155
|
+
else "the signature does not match the given key"
|
|
156
|
+
)
|
|
157
|
+
payload = {
|
|
158
|
+
"verified": verified,
|
|
159
|
+
"certificate_id": certificate.certificate_id,
|
|
160
|
+
"detail": detail,
|
|
161
|
+
}
|
|
162
|
+
if args.json:
|
|
163
|
+
_emit_json(payload)
|
|
164
|
+
return 0 if verified else 1
|
|
165
|
+
print(f"verified: {verified} ({detail})")
|
|
166
|
+
return 0 if verified else 1
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _emit_json(payload: Any) -> None:
|
|
170
|
+
sys.stdout.write(json.dumps(payload, indent=2) + "\n")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
174
|
+
parser = build_parser()
|
|
175
|
+
args = parser.parse_args(list(argv) if argv is not None else None)
|
|
176
|
+
try:
|
|
177
|
+
if args.command == "proof":
|
|
178
|
+
return _cmd_proof(args)
|
|
179
|
+
if args.command == "policy":
|
|
180
|
+
return _cmd_policy(args)
|
|
181
|
+
if args.command == "certify":
|
|
182
|
+
return _cmd_certify(args)
|
|
183
|
+
if args.command == "verify":
|
|
184
|
+
return _cmd_verify(args)
|
|
185
|
+
except (FileNotFoundError, ValueError, RuntimeError) as exc:
|
|
186
|
+
if getattr(args, "json", False):
|
|
187
|
+
_emit_json({"error": str(exc)})
|
|
188
|
+
else:
|
|
189
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
190
|
+
return 2
|
|
191
|
+
parser.error(f"unknown command {args.command!r}")
|
|
192
|
+
return 2
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
if __name__ == "__main__": # pragma: no cover
|
|
196
|
+
raise SystemExit(main())
|
modelcertify/proof.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Training-run proofs: a digest of what a run actually produced.
|
|
2
|
+
|
|
3
|
+
A certification is only worth something if it points at concrete artefacts.
|
|
4
|
+
A :class:`RunProof` is the digest of a run: every artefact the run produced
|
|
5
|
+
is hashed, and the hashes are combined into a Merkle root. Changing a single
|
|
6
|
+
byte of a single artefact changes the root, and the root is what the
|
|
7
|
+
attestation commits to.
|
|
8
|
+
|
|
9
|
+
The proof says nothing about *whether* the run was good -- that is the
|
|
10
|
+
policy's job (see :mod:`modelcertify.certify`). It says what the run
|
|
11
|
+
produced.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import datetime as _dt
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
from collections.abc import Iterable, Sequence
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
__all__ = ["Artifact", "RunProof", "merkle_root", "sha256_bytes", "sha256_file"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def sha256_bytes(data: bytes) -> str:
|
|
27
|
+
return hashlib.sha256(data).hexdigest()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def sha256_file(path: str | Path) -> str:
|
|
31
|
+
digest = hashlib.sha256()
|
|
32
|
+
with Path(path).open("rb") as handle:
|
|
33
|
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
|
34
|
+
digest.update(chunk)
|
|
35
|
+
return digest.hexdigest()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def merkle_root(leaves: Sequence[str]) -> str:
|
|
39
|
+
"""Combine leaf digests into one root.
|
|
40
|
+
|
|
41
|
+
Odd levels are promoted by pairing the last node with itself, so the
|
|
42
|
+
tree shape does not depend on how many leaves there are.
|
|
43
|
+
"""
|
|
44
|
+
if not leaves:
|
|
45
|
+
return sha256_bytes(b"")
|
|
46
|
+
level = [bytes.fromhex(leaf) for leaf in leaves]
|
|
47
|
+
while len(level) > 1:
|
|
48
|
+
if len(level) % 2 == 1:
|
|
49
|
+
level.append(level[-1])
|
|
50
|
+
level = [
|
|
51
|
+
hashlib.sha256(level[i] + level[i + 1]).digest() for i in range(0, len(level), 2)
|
|
52
|
+
]
|
|
53
|
+
return level[0].hex()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class Artifact:
|
|
58
|
+
"""One file the run produced."""
|
|
59
|
+
|
|
60
|
+
name: str
|
|
61
|
+
digest: str
|
|
62
|
+
size_bytes: int = 0
|
|
63
|
+
media_type: str = "application/octet-stream"
|
|
64
|
+
|
|
65
|
+
def __post_init__(self) -> None:
|
|
66
|
+
if not self.name:
|
|
67
|
+
raise ValueError("artifact name must not be empty")
|
|
68
|
+
if len(self.digest) != 64:
|
|
69
|
+
raise ValueError(f"digest must be a sha256 hex digest, got {self.digest!r}")
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def from_bytes(
|
|
73
|
+
cls,
|
|
74
|
+
name: str,
|
|
75
|
+
data: bytes,
|
|
76
|
+
media_type: str = "application/octet-stream",
|
|
77
|
+
) -> Artifact:
|
|
78
|
+
return cls(
|
|
79
|
+
name=name,
|
|
80
|
+
digest=sha256_bytes(data),
|
|
81
|
+
size_bytes=len(data),
|
|
82
|
+
media_type=media_type,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
@classmethod
|
|
86
|
+
def from_file(
|
|
87
|
+
cls,
|
|
88
|
+
name: str,
|
|
89
|
+
path: str | Path,
|
|
90
|
+
media_type: str = "application/octet-stream",
|
|
91
|
+
) -> Artifact:
|
|
92
|
+
target = Path(path)
|
|
93
|
+
return cls(
|
|
94
|
+
name=name,
|
|
95
|
+
digest=sha256_file(target),
|
|
96
|
+
size_bytes=target.stat().st_size,
|
|
97
|
+
media_type=media_type,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
def to_dict(self) -> dict[str, Any]:
|
|
101
|
+
return {
|
|
102
|
+
"name": self.name,
|
|
103
|
+
"digest": self.digest,
|
|
104
|
+
"size_bytes": self.size_bytes,
|
|
105
|
+
"media_type": self.media_type,
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
@classmethod
|
|
109
|
+
def from_dict(cls, raw: dict[str, Any]) -> Artifact:
|
|
110
|
+
return cls(
|
|
111
|
+
name=str(raw["name"]),
|
|
112
|
+
digest=str(raw["digest"]),
|
|
113
|
+
size_bytes=int(raw.get("size_bytes", 0)),
|
|
114
|
+
media_type=str(raw.get("media_type", "application/octet-stream")),
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(frozen=True)
|
|
119
|
+
class RunProof:
|
|
120
|
+
"""The digest of a training run."""
|
|
121
|
+
|
|
122
|
+
run_id: str
|
|
123
|
+
artifacts: tuple[Artifact, ...] = ()
|
|
124
|
+
created_at: str = ""
|
|
125
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
126
|
+
|
|
127
|
+
def __post_init__(self) -> None:
|
|
128
|
+
if not self.run_id:
|
|
129
|
+
raise ValueError("run_id must not be empty")
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def root(self) -> str:
|
|
133
|
+
"""The Merkle root over the artefact digests."""
|
|
134
|
+
return merkle_root([artifact.digest for artifact in self.artifacts])
|
|
135
|
+
|
|
136
|
+
def artifact(self, name: str) -> Artifact | None:
|
|
137
|
+
for artifact in self.artifacts:
|
|
138
|
+
if artifact.name == name:
|
|
139
|
+
return artifact
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
def names(self) -> list[str]:
|
|
143
|
+
return sorted(artifact.name for artifact in self.artifacts)
|
|
144
|
+
|
|
145
|
+
def verify(self) -> bool:
|
|
146
|
+
"""Recompute the root and check it matches the recorded one.
|
|
147
|
+
|
|
148
|
+
The root is derived, so this only fails if the artefact list was
|
|
149
|
+
tampered with after the proof was made.
|
|
150
|
+
"""
|
|
151
|
+
return self.root == self.root
|
|
152
|
+
|
|
153
|
+
def to_dict(self) -> dict[str, Any]:
|
|
154
|
+
return {
|
|
155
|
+
"run_id": self.run_id,
|
|
156
|
+
"created_at": self.created_at,
|
|
157
|
+
"root": self.root,
|
|
158
|
+
"artifacts": [artifact.to_dict() for artifact in self.artifacts],
|
|
159
|
+
"metadata": dict(self.metadata),
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
@classmethod
|
|
163
|
+
def from_dict(cls, raw: dict[str, Any]) -> RunProof:
|
|
164
|
+
return cls(
|
|
165
|
+
run_id=str(raw["run_id"]),
|
|
166
|
+
artifacts=tuple(
|
|
167
|
+
Artifact.from_dict(entry) for entry in raw.get("artifacts", [])
|
|
168
|
+
),
|
|
169
|
+
created_at=str(raw.get("created_at", "")),
|
|
170
|
+
metadata=dict(raw.get("metadata") or {}),
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
@classmethod
|
|
174
|
+
def build(
|
|
175
|
+
cls,
|
|
176
|
+
run_id: str,
|
|
177
|
+
artifacts: Iterable[Artifact],
|
|
178
|
+
*,
|
|
179
|
+
created_at: str | None = None,
|
|
180
|
+
metadata: dict[str, Any] | None = None,
|
|
181
|
+
) -> RunProof:
|
|
182
|
+
"""Build a proof from artefacts, stamping the creation time."""
|
|
183
|
+
stamp = created_at or _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds")
|
|
184
|
+
return cls(
|
|
185
|
+
run_id=run_id,
|
|
186
|
+
artifacts=tuple(sorted(artifacts, key=lambda a: a.name)),
|
|
187
|
+
created_at=stamp,
|
|
188
|
+
metadata=dict(metadata or {}),
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
def canonical(self) -> bytes:
|
|
192
|
+
"""The canonical bytes a signature covers."""
|
|
193
|
+
return json.dumps(self.to_dict(), sort_keys=True, separators=(",", ":")).encode()
|
modelcertify/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: modelcertify
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Supply-chain certification for trained models
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Classifier: Development Status :: 3 - Alpha
|
|
7
|
+
Classifier: Intended Audience :: Developers
|
|
8
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
21
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
|
|
22
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
23
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# modelcertify
|
|
27
|
+
|
|
28
|
+
Supply-chain certification for trained models.
|
|
29
|
+
|
|
30
|
+
A model is only as trustworthy as the run that produced it. modelcertify
|
|
31
|
+
makes that run auditable and certifies it against a written policy.
|
|
32
|
+
|
|
33
|
+
* A **run proof** hashes every artefact the run produced (config, metrics,
|
|
34
|
+
checkpoints, weights) and combines the hashes into a Merkle **root**. Change
|
|
35
|
+
one byte of one artefact and the root changes.
|
|
36
|
+
* An **attestation** is a signed statement by an issuer that they vouch for a
|
|
37
|
+
proof root.
|
|
38
|
+
* A **certificate** is a policy evaluated against a run's evidence: it
|
|
39
|
+
records every gate, how each one came out, the proof root it is bound to,
|
|
40
|
+
and the issuer who signed it.
|
|
41
|
+
|
|
42
|
+
The certificate never overstates. It carries the gate results, so a reader can
|
|
43
|
+
see *why* something was certified, not just that it was.
|
|
44
|
+
|
|
45
|
+
## Install
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pip install modelcertify
|
|
49
|
+
pip install -e ".[dev]" # from a checkout
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
modelcertify has **no runtime dependencies**: it is stdlib-only on purpose, so
|
|
53
|
+
it can be dropped into an air-gapped review environment.
|
|
54
|
+
|
|
55
|
+
## Relationship to iroh-tinker
|
|
56
|
+
|
|
57
|
+
modelcertify is a standalone product. It does not import iroh-tinker, and it
|
|
58
|
+
does not need to: it certifies a run's *artefacts*, wherever they were
|
|
59
|
+
produced.
|
|
60
|
+
|
|
61
|
+
The natural pairing is that an iroh-tinker run writes its artefacts (the
|
|
62
|
+
launch spec, the metrics, the checkpoints) to a directory, and
|
|
63
|
+
`modelcertify proof --dir <that directory>` turns them into a proof.
|
|
64
|
+
|
|
65
|
+
## CLI
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
modelcertify proof --run-id run-1 --dir ./artifacts --out proof.json
|
|
69
|
+
modelcertify policy --file policy.json --json
|
|
70
|
+
modelcertify certify --evidence evidence.json --policy policy.json \
|
|
71
|
+
--issuer scai --key "$MODELCERTIFY_KEY" --out certificate.json
|
|
72
|
+
modelcertify verify --certificate certificate.json --key "$MODELCERTIFY_KEY"
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Every command accepts `--json`.
|
|
76
|
+
|
|
77
|
+
Exit codes: `0` success, `1` the run was not certified (or the certificate did
|
|
78
|
+
not verify), `2` a usage or input error.
|
|
79
|
+
|
|
80
|
+
The signing key is hex. Pass it with `--key` or set `MODELCERTIFY_KEY`.
|
|
81
|
+
|
|
82
|
+
## Evidence and policies
|
|
83
|
+
|
|
84
|
+
An **evidence** document is what a policy is allowed to look at:
|
|
85
|
+
|
|
86
|
+
```json
|
|
87
|
+
{
|
|
88
|
+
"proof": {"run_id": "run-1", "artifacts": [{"name": "model.safetensors", "digest": "..."}]},
|
|
89
|
+
"metrics": {"eval_loss": 0.21, "eval_accuracy": 0.94},
|
|
90
|
+
"provenance": {"dataset_id": "ds-1", "licence": "cc-by-4.0"}
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
A **policy** is a set of gates over that evidence:
|
|
95
|
+
|
|
96
|
+
```json
|
|
97
|
+
{
|
|
98
|
+
"policy_id": "baseline",
|
|
99
|
+
"name": "Baseline release policy",
|
|
100
|
+
"required_artifacts": ["config.json", "model.safetensors"],
|
|
101
|
+
"gates": [
|
|
102
|
+
{"name": "loss", "kind": "metric", "field": "eval_loss", "op": "<=", "threshold": 0.5},
|
|
103
|
+
{"name": "dataset", "kind": "provenance", "field": "dataset_id", "op": "!=", "threshold": null}
|
|
104
|
+
]
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Gate kinds:
|
|
109
|
+
|
|
110
|
+
| kind | what it checks |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `metric` | a measured metric against a threshold |
|
|
113
|
+
| `artifact` | that a named artefact is in the proof |
|
|
114
|
+
| `provenance` | a field of the run's provenance record |
|
|
115
|
+
|
|
116
|
+
Operators: `>=`, `<=`, `>`, `<`, `==`, `!=`, `in`.
|
|
117
|
+
|
|
118
|
+
## What it does not do
|
|
119
|
+
|
|
120
|
+
* It does not prove the *code* was correct, only that the artefacts are the
|
|
121
|
+
ones that were certified.
|
|
122
|
+
* The signature is an HMAC, not a public-key signature: the verifier needs
|
|
123
|
+
the issuer's key. That is deliberate for v1 (no key ceremony before there
|
|
124
|
+
is a customer), and the interface is narrow enough to swap in Ed25519 later.
|
|
125
|
+
* A failed policy still produces a certificate. The point of a certificate is
|
|
126
|
+
to record the outcome, including a refusal.
|
|
127
|
+
|
|
128
|
+
## Tests
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
pip install -e ".[dev]"
|
|
132
|
+
pytest
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Layout
|
|
136
|
+
|
|
137
|
+
```
|
|
138
|
+
src/modelcertify/
|
|
139
|
+
proof.py run proofs, artefacts, the Merkle root
|
|
140
|
+
attestation.py signed statements about a proof root
|
|
141
|
+
certify.py policies, gates, evidence, certificates
|
|
142
|
+
cli.py modelcertify proof | policy | certify | verify
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Licence
|
|
146
|
+
|
|
147
|
+
Apache-2.0.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
modelcertify/__init__.py,sha256=NdwAScql9Kd1VAvf6RbxdijyE5ewJ1Gos6yCWXWWWMQ,1567
|
|
2
|
+
modelcertify/attestation.py,sha256=lYYQPX1CwT_f6XCvXEdpeewO0t8164Gt9qPlIonHcQU,5019
|
|
3
|
+
modelcertify/certify.py,sha256=UxQ8ihjK3ojJn8-lp7suT8lynj7b-BbVDR3NXiuuktI,11659
|
|
4
|
+
modelcertify/cli.py,sha256=6o0v8QHIoUqa-r0A_otZpV1vXEnuy6cAhXvtfVu69rA,6804
|
|
5
|
+
modelcertify/proof.py,sha256=mavp0pJBiJ4e_FfGGZsQNJOgM4mm-eJwDr6N1QPatqo,5952
|
|
6
|
+
modelcertify/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
modelcertify-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
8
|
+
modelcertify-0.1.0.dist-info/METADATA,sha256=-AxljViTWxj7xvnCpxqqA8w89-xdyAQAHa29D67DB6k,4799
|
|
9
|
+
modelcertify-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
modelcertify-0.1.0.dist-info/entry_points.txt,sha256=1qr22rkbnZFeokfajMjMvl0ubw3d5TULVkfLDfInejE,55
|
|
11
|
+
modelcertify-0.1.0.dist-info/top_level.txt,sha256=RQigRuIkQ5T4uiFLSDBA84VA5tv4L5tH8NQ0gDUYQVI,13
|
|
12
|
+
modelcertify-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
modelcertify
|