open-action-record 0.1.1__tar.gz
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.
- open_action_record-0.1.1/LICENSE +55 -0
- open_action_record-0.1.1/PKG-INFO +46 -0
- open_action_record-0.1.1/README.md +24 -0
- open_action_record-0.1.1/pyproject.toml +35 -0
- open_action_record-0.1.1/setup.cfg +4 -0
- open_action_record-0.1.1/src/open_action_record/__init__.py +6 -0
- open_action_record-0.1.1/src/open_action_record/canonical.py +42 -0
- open_action_record-0.1.1/src/open_action_record/cli.py +50 -0
- open_action_record-0.1.1/src/open_action_record/py.typed +0 -0
- open_action_record-0.1.1/src/open_action_record/timestamp.py +216 -0
- open_action_record-0.1.1/src/open_action_record/tsa_roots.json +17 -0
- open_action_record-0.1.1/src/open_action_record/verify.py +369 -0
- open_action_record-0.1.1/src/open_action_record.egg-info/PKG-INFO +46 -0
- open_action_record-0.1.1/src/open_action_record.egg-info/SOURCES.txt +17 -0
- open_action_record-0.1.1/src/open_action_record.egg-info/dependency_links.txt +1 -0
- open_action_record-0.1.1/src/open_action_record.egg-info/entry_points.txt +2 -0
- open_action_record-0.1.1/src/open_action_record.egg-info/requires.txt +6 -0
- open_action_record-0.1.1/src/open_action_record.egg-info/top_level.txt +1 -0
- open_action_record-0.1.1/tests/test_vectors.py +47 -0
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
|
|
5
|
+
http://www.apache.org/licenses/
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
16
|
+
|
|
17
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
18
|
+
|
|
19
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
20
|
+
|
|
21
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
22
|
+
|
|
23
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
24
|
+
|
|
25
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
26
|
+
|
|
27
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
28
|
+
|
|
29
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
30
|
+
|
|
31
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
32
|
+
|
|
33
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
34
|
+
|
|
35
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
36
|
+
|
|
37
|
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
38
|
+
|
|
39
|
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
40
|
+
|
|
41
|
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
42
|
+
|
|
43
|
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: open-action-record
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Verify Open Action Records: signed proof of what an AI agent's action actually changed, and who approved it.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/openactionrecord/oar
|
|
7
|
+
Project-URL: Source, https://github.com/openactionrecord/oar
|
|
8
|
+
Project-URL: Specification, https://github.com/openactionrecord/oar/blob/main/SPEC.md
|
|
9
|
+
Keywords: ai-agents,audit,receipts,verification,provenance,open-action-record,oar
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Security :: Cryptography
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: cryptography>=42
|
|
17
|
+
Requires-Dist: asn1crypto>=1.5
|
|
18
|
+
Requires-Dist: rfc8785>=0.1.4
|
|
19
|
+
Provides-Extra: test
|
|
20
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# open-action-record (Python)
|
|
24
|
+
|
|
25
|
+
Verify [Open Action Records](https://github.com/openactionrecord/oar): signed proof of what an AI agent's action actually changed, and who approved it.
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install open-action-record
|
|
29
|
+
oar-verify evidence.json
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import json
|
|
34
|
+
from open_action_record import verify_bundle, outcomes
|
|
35
|
+
|
|
36
|
+
bundle = json.load(open("evidence.json"))
|
|
37
|
+
report = verify_bundle(bundle) # pass keys=... to check against keys you trust
|
|
38
|
+
print(report.result, report.level) # "pass", "sealed"
|
|
39
|
+
print(outcomes(bundle)) # ["confirmed", "denied", "not_confirmed"]
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
It checks every record's issuer signature, the separate sealing service's seal, each agent's hash chain, checkpoint coverage, outside RFC 3161 timestamps (against the bundled DigiCert roots) and any disclosed values. It reaches the same result as the TypeScript and browser verifiers on every shared test vector.
|
|
43
|
+
|
|
44
|
+
Writing records from Python is planned; today, write them with [`@openactionrecord/core`](https://www.npmjs.com/package/@openactionrecord/core).
|
|
45
|
+
|
|
46
|
+
Apache-2.0.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# open-action-record (Python)
|
|
2
|
+
|
|
3
|
+
Verify [Open Action Records](https://github.com/openactionrecord/oar): signed proof of what an AI agent's action actually changed, and who approved it.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install open-action-record
|
|
7
|
+
oar-verify evidence.json
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
import json
|
|
12
|
+
from open_action_record import verify_bundle, outcomes
|
|
13
|
+
|
|
14
|
+
bundle = json.load(open("evidence.json"))
|
|
15
|
+
report = verify_bundle(bundle) # pass keys=... to check against keys you trust
|
|
16
|
+
print(report.result, report.level) # "pass", "sealed"
|
|
17
|
+
print(outcomes(bundle)) # ["confirmed", "denied", "not_confirmed"]
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
It checks every record's issuer signature, the separate sealing service's seal, each agent's hash chain, checkpoint coverage, outside RFC 3161 timestamps (against the bundled DigiCert roots) and any disclosed values. It reaches the same result as the TypeScript and browser verifiers on every shared test vector.
|
|
21
|
+
|
|
22
|
+
Writing records from Python is planned; today, write them with [`@openactionrecord/core`](https://www.npmjs.com/package/@openactionrecord/core).
|
|
23
|
+
|
|
24
|
+
Apache-2.0.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=69"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "open-action-record"
|
|
7
|
+
version = "0.1.1"
|
|
8
|
+
description = "Verify Open Action Records: signed proof of what an AI agent's action actually changed, and who approved it."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["cryptography>=42", "asn1crypto>=1.5", "rfc8785>=0.1.4"]
|
|
13
|
+
keywords = ["ai-agents", "audit", "receipts", "verification", "provenance", "open-action-record", "oar"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Security :: Cryptography",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://github.com/openactionrecord/oar"
|
|
22
|
+
Source = "https://github.com/openactionrecord/oar"
|
|
23
|
+
Specification = "https://github.com/openactionrecord/oar/blob/main/SPEC.md"
|
|
24
|
+
|
|
25
|
+
[project.scripts]
|
|
26
|
+
oar-verify = "open_action_record.cli:main"
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.packages.find]
|
|
29
|
+
where = ["src"]
|
|
30
|
+
|
|
31
|
+
[tool.setuptools.package-data]
|
|
32
|
+
open_action_record = ["tsa_roots.json", "py.typed"]
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
test = ["pytest>=8"]
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Verify Open Action Records (OAR): signed proof of what an AI agent's action actually changed, and who approved it."""
|
|
2
|
+
|
|
3
|
+
from .verify import BundleError, RecordReport, Report, outcomes, parse_bundle, verify_bundle
|
|
4
|
+
|
|
5
|
+
__all__ = ["BundleError", "RecordReport", "Report", "outcomes", "parse_bundle", "verify_bundle"]
|
|
6
|
+
__version__ = "0.1.1"
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""RFC 8785 canonical JSON, SHA-256 digests and Ed25519 keys, as used by Open Action Records."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import rfc8785
|
|
10
|
+
from cryptography.exceptions import InvalidSignature
|
|
11
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def canonical_bytes(value: Any) -> bytes:
|
|
15
|
+
return rfc8785.dumps(value)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def digest(value: Any) -> str:
|
|
19
|
+
""""sha256:<hex>" of the canonical form of `value`."""
|
|
20
|
+
return "sha256:" + hashlib.sha256(canonical_bytes(value)).hexdigest()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def find_public_key(jwks: dict | None, kid: str) -> Ed25519PublicKey | None:
|
|
24
|
+
for k in (jwks or {}).get("keys", []):
|
|
25
|
+
if k.get("kid") == kid and k.get("kty") == "OKP" and k.get("crv") == "Ed25519":
|
|
26
|
+
try:
|
|
27
|
+
raw = base64.urlsafe_b64decode(k["x"] + "=" * (-len(k["x"]) % 4))
|
|
28
|
+
return Ed25519PublicKey.from_public_bytes(raw) if len(raw) == 32 else None
|
|
29
|
+
except (ValueError, KeyError):
|
|
30
|
+
return None
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def signature_ok(jwks: dict | None, kid: str, value: Any, signature_hex: str) -> bool:
|
|
35
|
+
key = find_public_key(jwks, kid)
|
|
36
|
+
if key is None:
|
|
37
|
+
return False
|
|
38
|
+
try:
|
|
39
|
+
key.verify(bytes.fromhex(signature_hex), canonical_bytes(value))
|
|
40
|
+
return True
|
|
41
|
+
except (InvalidSignature, ValueError, TypeError):
|
|
42
|
+
return False
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""oar-verify: verify an Open Action Record bundle from the command line."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from dataclasses import asdict
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .verify import BundleError, outcomes, verify_bundle
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main(argv: list[str] | None = None) -> int:
|
|
15
|
+
parser = argparse.ArgumentParser(prog="oar-verify", description="Verify an Open Action Record bundle.")
|
|
16
|
+
parser.add_argument("bundle", help="path to the bundle (.json)")
|
|
17
|
+
parser.add_argument("--keys", help='keys you trust: { "issuer": JWKS, "sealer": JWKS }')
|
|
18
|
+
parser.add_argument("--tsa-roots", help="timestamp-authority roots to accept instead of the bundled DigiCert roots")
|
|
19
|
+
parser.add_argument("--require-seal", action="store_true", help="fail records not countersigned by a separate sealing service")
|
|
20
|
+
parser.add_argument("--json", action="store_true", help="print the report as JSON")
|
|
21
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
22
|
+
args = parser.parse_args(argv)
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
with open(args.bundle, encoding="utf-8") as f:
|
|
26
|
+
bundle = json.load(f)
|
|
27
|
+
keys = json.load(open(args.keys, encoding="utf-8")) if args.keys else None
|
|
28
|
+
roots = json.load(open(args.tsa_roots, encoding="utf-8")) if args.tsa_roots else None
|
|
29
|
+
report = verify_bundle(bundle, keys=keys, tsa_roots=roots, require_seal=args.require_seal)
|
|
30
|
+
except (OSError, json.JSONDecodeError, BundleError) as e:
|
|
31
|
+
print(str(e), file=sys.stderr)
|
|
32
|
+
return 2
|
|
33
|
+
|
|
34
|
+
if args.json:
|
|
35
|
+
print(json.dumps({"report": asdict(report), "outcomes": outcomes(bundle)}, indent=2))
|
|
36
|
+
else:
|
|
37
|
+
mark = "✔" if report.result == "pass" else "✘"
|
|
38
|
+
print(f"{mark} {report.messages[0]}")
|
|
39
|
+
for m in report.messages[1:]:
|
|
40
|
+
print(f" {m}")
|
|
41
|
+
for r in report.records:
|
|
42
|
+
if r.result == "fail":
|
|
43
|
+
failed = ", ".join(k for k, v in r.checks.items() if v == "fail")
|
|
44
|
+
print(f" ✘ {r.receipt_id[9:17]} {r.phase} {r.outcome}: {failed} failed")
|
|
45
|
+
print(" Outcomes: " + ", ".join(outcomes(bundle)))
|
|
46
|
+
return 0 if report.result == "pass" else 1
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
if __name__ == "__main__":
|
|
50
|
+
sys.exit(main())
|
|
File without changes
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Checks an RFC 3161 timestamp token over a checkpoint, the same way the TypeScript verifiers do.
|
|
2
|
+
|
|
3
|
+
The token must timestamp the SHA-256 of the signed checkpoint, its signature must verify, and the signing
|
|
4
|
+
certificate must be a timestamping certificate that was valid at the time and chains to an accepted root.
|
|
5
|
+
Certificate revocation is not checked.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from importlib import resources
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from asn1crypto import cms, tsp
|
|
18
|
+
from cryptography import x509
|
|
19
|
+
from cryptography.exceptions import InvalidSignature
|
|
20
|
+
from cryptography.hazmat.primitives import hashes
|
|
21
|
+
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
|
|
22
|
+
from cryptography.x509.oid import ExtendedKeyUsageOID
|
|
23
|
+
|
|
24
|
+
from .canonical import canonical_bytes
|
|
25
|
+
|
|
26
|
+
_HASHES = {"sha256": hashes.SHA256, "sha384": hashes.SHA384, "sha512": hashes.SHA512}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def bundled_roots() -> list[dict[str, str]]:
|
|
30
|
+
"""The DigiCert roots accepted by default (the same list as the TypeScript verifiers)."""
|
|
31
|
+
return json.loads(resources.files(__package__).joinpath("tsa_roots.json").read_text())
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def anchor_digest(cp: dict[str, Any]) -> str:
|
|
35
|
+
"""SHA-256 (hex) of the signed checkpoint: the value the authority timestamps."""
|
|
36
|
+
body = {k: cp[k] for k in ("count", "head_digest", "at", "sealer_kid", "sig")}
|
|
37
|
+
return hashlib.sha256(canonical_bytes(body)).hexdigest()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class TimestampResult:
|
|
42
|
+
ok: bool
|
|
43
|
+
reason: str = ""
|
|
44
|
+
gen_time: str = ""
|
|
45
|
+
tsa: str = ""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _TokenError(Exception):
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def verify_timestamp_token(token: str, imprint_hex: str, roots: list[dict[str, str]] | None = None) -> TimestampResult:
|
|
53
|
+
try:
|
|
54
|
+
return _check(token, imprint_hex, roots if roots is not None else bundled_roots())
|
|
55
|
+
except _TokenError as e:
|
|
56
|
+
return TimestampResult(False, str(e))
|
|
57
|
+
except Exception: # noqa: BLE001 - any parsing failure means the token cannot be read
|
|
58
|
+
return TimestampResult(False, "The timestamp token could not be read.")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _tlv(buf: bytes, pos: int) -> tuple[int, bytes, int]:
|
|
62
|
+
"""One DER/BER element at `pos`: (tag, content, next position). Definite lengths only."""
|
|
63
|
+
tag = buf[pos]
|
|
64
|
+
length = buf[pos + 1]
|
|
65
|
+
p = pos + 2
|
|
66
|
+
if length & 0x80:
|
|
67
|
+
n = length & 0x7F
|
|
68
|
+
if not 1 <= n <= 4:
|
|
69
|
+
raise _TokenError("The timestamp token is not valid DER.")
|
|
70
|
+
length = int.from_bytes(buf[p : p + n], "big")
|
|
71
|
+
p += n
|
|
72
|
+
if p + length > len(buf):
|
|
73
|
+
raise _TokenError("The timestamp token is not valid DER.")
|
|
74
|
+
return tag, buf[p : p + length], p + length
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _octets(tag: int, content: bytes) -> bytes:
|
|
78
|
+
"""An OCTET STRING's bytes; a constructed (chunked) one, as some encoders write, is joined."""
|
|
79
|
+
if tag == 0x04:
|
|
80
|
+
return content
|
|
81
|
+
if tag == 0x24:
|
|
82
|
+
out, p = b"", 0
|
|
83
|
+
while p < len(content):
|
|
84
|
+
t, c, p = _tlv(content, p)
|
|
85
|
+
out += _octets(t, c)
|
|
86
|
+
return out
|
|
87
|
+
raise _TokenError("The timestamp token has an unexpected structure.")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _econtent(encap_contents: bytes) -> bytes:
|
|
91
|
+
"""The TSTInfo bytes inside EncapsulatedContentInfo: SEQUENCE { OID, [0] EXPLICIT OCTET STRING }."""
|
|
92
|
+
_t, _oid, p = _tlv(encap_contents, 0)
|
|
93
|
+
tag, explicit, _ = _tlv(encap_contents, p)
|
|
94
|
+
if tag != 0xA0:
|
|
95
|
+
raise _TokenError("The timestamp token has no content.")
|
|
96
|
+
inner_tag, inner, _ = _tlv(explicit, 0)
|
|
97
|
+
return _octets(inner_tag, inner)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _common_name(cert: x509.Certificate) -> str:
|
|
101
|
+
names = cert.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)
|
|
102
|
+
return str(names[0].value) if names else cert.subject.rfc4514_string()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _valid_at(cert: x509.Certificate, when) -> bool:
|
|
106
|
+
return cert.not_valid_before_utc <= when <= cert.not_valid_after_utc
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _signed_by(cert: x509.Certificate, hash_name: str, signature: bytes, data: bytes) -> bool:
|
|
110
|
+
key = cert.public_key()
|
|
111
|
+
algorithm = _HASHES[hash_name]()
|
|
112
|
+
try:
|
|
113
|
+
if isinstance(key, rsa.RSAPublicKey):
|
|
114
|
+
key.verify(signature, data, padding.PKCS1v15(), algorithm)
|
|
115
|
+
elif isinstance(key, ec.EllipticCurvePublicKey):
|
|
116
|
+
key.verify(signature, data, ec.ECDSA(algorithm))
|
|
117
|
+
else:
|
|
118
|
+
return False
|
|
119
|
+
return True
|
|
120
|
+
except InvalidSignature:
|
|
121
|
+
return False
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _check(token: str, imprint_hex: str, roots: list[dict[str, str]]) -> TimestampResult:
|
|
125
|
+
info = cms.ContentInfo.load(base64.b64decode(token))
|
|
126
|
+
if info["content_type"].dotted != "1.2.840.113549.1.7.2":
|
|
127
|
+
raise _TokenError("This is not a timestamp token.")
|
|
128
|
+
signed = info["content"]
|
|
129
|
+
encap = signed["encap_content_info"]
|
|
130
|
+
if encap["content_type"].dotted != "1.2.840.113549.1.9.16.1.4":
|
|
131
|
+
raise _TokenError("This is not a timestamp token.")
|
|
132
|
+
tst_der = _econtent(encap.contents)
|
|
133
|
+
tst = tsp.TSTInfo.load(tst_der)
|
|
134
|
+
imprint = tst["message_imprint"]
|
|
135
|
+
if imprint["hash_algorithm"]["algorithm"].dotted != "2.16.840.1.101.3.4.2.1":
|
|
136
|
+
raise _TokenError("The timestamp does not use SHA-256.")
|
|
137
|
+
if imprint["hashed_message"].native.hex() != imprint_hex:
|
|
138
|
+
raise _TokenError("The timestamp is for a different checkpoint.")
|
|
139
|
+
gen_time = tst["gen_time"].native
|
|
140
|
+
|
|
141
|
+
certs = [x509.load_der_x509_certificate(c.chosen.dump()) for c in (signed["certificates"] or [])]
|
|
142
|
+
signer_info = signed["signer_infos"][0]
|
|
143
|
+
hash_name = signer_info["digest_algorithm"]["algorithm"].native
|
|
144
|
+
if hash_name not in _HASHES:
|
|
145
|
+
raise _TokenError("The timestamp uses an unsupported hash algorithm.")
|
|
146
|
+
attrs = signer_info["signed_attrs"]
|
|
147
|
+
if not attrs:
|
|
148
|
+
raise _TokenError("The timestamp has no signed attributes.")
|
|
149
|
+
sig_alg = signer_info["signature_algorithm"]["algorithm"].dotted
|
|
150
|
+
if not (sig_alg.startswith("1.2.840.113549.1.1.") or sig_alg.startswith("1.2.840.10045.")) or sig_alg == "1.2.840.113549.1.1.10":
|
|
151
|
+
raise _TokenError("The timestamp uses an unsupported signature algorithm.")
|
|
152
|
+
|
|
153
|
+
digest = next((a["values"][0].native for a in attrs if a["type"].dotted == "1.2.840.113549.1.9.4"), None)
|
|
154
|
+
if digest is None:
|
|
155
|
+
raise _TokenError("The timestamp has no message digest.")
|
|
156
|
+
h = hashlib.new(hash_name)
|
|
157
|
+
h.update(tst_der)
|
|
158
|
+
if digest != h.digest():
|
|
159
|
+
raise _TokenError("The timestamp token was changed after signing.")
|
|
160
|
+
|
|
161
|
+
sid = signer_info["sid"]
|
|
162
|
+
if sid.name == "issuer_and_serial_number":
|
|
163
|
+
serial = sid.chosen["serial_number"].native
|
|
164
|
+
candidates = [c for c in certs if c.serial_number == serial]
|
|
165
|
+
else:
|
|
166
|
+
candidates = certs
|
|
167
|
+
if not candidates:
|
|
168
|
+
raise _TokenError("The timestamp token does not include the authority's certificate.")
|
|
169
|
+
|
|
170
|
+
attrs_der = attrs.dump()
|
|
171
|
+
to_verify = b"\x31" + attrs_der[1:]
|
|
172
|
+
signature = signer_info["signature"].native
|
|
173
|
+
signer = next((c for c in candidates if _signed_by(c, hash_name, signature, to_verify)), None)
|
|
174
|
+
if signer is None:
|
|
175
|
+
raise _TokenError("The timestamp signature does not verify.")
|
|
176
|
+
|
|
177
|
+
try:
|
|
178
|
+
eku = signer.extensions.get_extension_for_class(x509.ExtendedKeyUsage).value
|
|
179
|
+
except x509.ExtensionNotFound:
|
|
180
|
+
eku = []
|
|
181
|
+
if ExtendedKeyUsageOID.TIME_STAMPING not in eku:
|
|
182
|
+
raise _TokenError("The signing certificate is not a timestamping certificate.")
|
|
183
|
+
if not _valid_at(signer, gen_time):
|
|
184
|
+
raise _TokenError("The authority's certificate was not valid at the time of the timestamp.")
|
|
185
|
+
|
|
186
|
+
_chain_to_root(signer, certs, roots, gen_time)
|
|
187
|
+
return TimestampResult(True, gen_time=gen_time.strftime("%Y-%m-%dT%H:%M:%S.") + f"{gen_time.microsecond // 1000:03d}Z", tsa=_common_name(signer))
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _issued_by(cert: x509.Certificate, issuer: x509.Certificate) -> bool:
|
|
191
|
+
try:
|
|
192
|
+
cert.verify_directly_issued_by(issuer)
|
|
193
|
+
return True
|
|
194
|
+
except (ValueError, TypeError, InvalidSignature):
|
|
195
|
+
return False
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _chain_to_root(signer: x509.Certificate, certs: list[x509.Certificate], roots: list[dict[str, str]], when) -> None:
|
|
199
|
+
trusted = [(r, x509.load_der_x509_certificate(base64.b64decode(r["der"]))) for r in roots]
|
|
200
|
+
current = signer
|
|
201
|
+
for _ in range(6):
|
|
202
|
+
fingerprint = current.fingerprint(hashes.SHA256()).hex()
|
|
203
|
+
if any(r["sha256"] == fingerprint for r, _c in trusted):
|
|
204
|
+
return
|
|
205
|
+
anchor = next((c for _r, c in trusted if _issued_by(current, c)), None)
|
|
206
|
+
if anchor is not None:
|
|
207
|
+
if not _valid_at(anchor, when):
|
|
208
|
+
raise _TokenError("The root certificate was not valid at the time of the timestamp.")
|
|
209
|
+
return
|
|
210
|
+
issuer = next((c for c in certs if c is not current and _issued_by(current, c)), None)
|
|
211
|
+
if issuer is None:
|
|
212
|
+
raise _TokenError("The authority's certificate does not chain to a recognised root.")
|
|
213
|
+
if not _valid_at(issuer, when):
|
|
214
|
+
raise _TokenError("A certificate in the chain was not valid at the time of the timestamp.")
|
|
215
|
+
current = issuer
|
|
216
|
+
raise _TokenError("The certificate chain is too long.")
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"name": "DigiCert Trusted Root G4",
|
|
4
|
+
"sha256": "552f7bdcf1a7af9e6ce672017f4f12abf77240c78e761ac203d1d9d20ac89988",
|
|
5
|
+
"der": "MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBiMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3yithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1Ifxp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDVySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiODCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQjdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6MUSaM0C/CNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCiEhtmmnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADMfRyVw4/3IbKyEbe7f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QYuKZ3AeEPlAwhHbJUKSWJbOUOUlFHdL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXKchYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8oR7FwI+isX4KJpn15GkvmB0t9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQADggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2SV1EY+CtnJYYZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd+SeuMIW59mdNOj6PWTkiU0TryF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWcfFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy7zBZLq7gcfJW5GqXb5JQbZaNaHqasjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iahixTXTBmyUEFxPT9NcCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN5r5N0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie4u1Ki7wb/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mIr/OSmbaz5mEP0oUA51Aa5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCmgKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+"
|
|
6
|
+
},
|
|
7
|
+
{
|
|
8
|
+
"name": "DigiCert Assured ID Root CA",
|
|
9
|
+
"sha256": "3e9099b5015e8f486c00bcea9d111ee721faba355a89bcf1df69561e3dc6325c",
|
|
10
|
+
"der": "MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7cJpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYPmDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYunpyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRCdWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTffwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cmNW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPxH2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe+o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g=="
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
"name": "DigiCert Assured ID Root G2",
|
|
14
|
+
"sha256": "7d05ebb682339f8c9451ee094eebfefa7953a114edb2f44949452fab7d2fc185",
|
|
15
|
+
"der": "MIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSAn61UQbVH35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4HteccbiJVMWWXvdMX0h5i89vqbFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9HpEgjAALAcKxHad3A2m67OeYfcgnDmCXRwVWmvo2ifv922ebPynXApVfSr/5Vh88lAbx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OPYLfykqGxvYmJHzDNw6YuYjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+RnlTGNAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBTOw0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPIQW5pJ6d1Ee88hjZv0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I0jJmwYrA8y8678Dj1JGG0VDjA9tzd29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4GnilmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAWhsI6yLETcDbYz+70CjTVW0z9B5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0MjomZmWzwPDCvON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwoIhNzbM8m9Yop5w=="
|
|
16
|
+
}
|
|
17
|
+
]
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"""Verifies an Open Action Record bundle: issuer signatures, seals, chains, checkpoint coverage, outside
|
|
2
|
+
timestamps and disclosures. Mirrors the TypeScript reference verifier and reaches the same result on the
|
|
3
|
+
shared test vectors (vectors/ in the repository)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .canonical import digest, signature_ok
|
|
12
|
+
from .timestamp import TimestampResult, anchor_digest, verify_timestamp_token
|
|
13
|
+
|
|
14
|
+
CHECKS = ("issuer_signature", "seal", "chain", "checkpoint", "disclosures", "timestamp")
|
|
15
|
+
LABELS = {
|
|
16
|
+
"issuer_signature": "Issuer signature",
|
|
17
|
+
"seal": "Seal",
|
|
18
|
+
"chain": "Chain",
|
|
19
|
+
"checkpoint": "Checkpoint coverage",
|
|
20
|
+
"disclosures": "Disclosures",
|
|
21
|
+
"timestamp": "Outside timestamp",
|
|
22
|
+
}
|
|
23
|
+
LEVELS = ("issuer-signed", "sealed", "timestamped")
|
|
24
|
+
LEVEL_LABELS = {
|
|
25
|
+
"issuer-signed": "Issuer-signed",
|
|
26
|
+
"sealed": "Sealed by a separate service",
|
|
27
|
+
"timestamped": "Sealed and timestamped by an outside authority",
|
|
28
|
+
}
|
|
29
|
+
FIELDS = {
|
|
30
|
+
"instance": "instance_commitment",
|
|
31
|
+
"consumption": "consumption_commitment",
|
|
32
|
+
"target_ref": "target_ref_commitment",
|
|
33
|
+
"state_before": "state_before_commitment",
|
|
34
|
+
"state_after": "state_after_commitment",
|
|
35
|
+
}
|
|
36
|
+
FORMATS = ("oar-bundle/0.1", "aar-evidence/0.1")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class BundleError(ValueError):
|
|
40
|
+
"""The input is not a bundle this verifier can read."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class RecordReport:
|
|
45
|
+
receipt_id: str
|
|
46
|
+
agent_id: str
|
|
47
|
+
phase: str
|
|
48
|
+
outcome: str
|
|
49
|
+
checks: dict[str, str]
|
|
50
|
+
result: str = "pass"
|
|
51
|
+
level: str = "issuer-signed"
|
|
52
|
+
messages: list[str] = field(default_factory=list)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class Report:
|
|
57
|
+
result: str
|
|
58
|
+
level: str
|
|
59
|
+
records: list[RecordReport]
|
|
60
|
+
failed_checks: list[str]
|
|
61
|
+
messages: list[str]
|
|
62
|
+
checkpoint: dict | None = None
|
|
63
|
+
timestamp: dict | None = None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class _Entry:
|
|
68
|
+
record: dict
|
|
69
|
+
report: RecordReport
|
|
70
|
+
seal_valid: bool
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def parse_bundle(bundle: Any) -> dict:
|
|
74
|
+
if not isinstance(bundle, dict):
|
|
75
|
+
raise BundleError("Not a bundle: expected a JSON object.")
|
|
76
|
+
problems = []
|
|
77
|
+
if bundle.get("format") not in FORMATS:
|
|
78
|
+
problems.append(f'format: expected "oar-bundle/0.1", got {bundle.get("format")!r}')
|
|
79
|
+
records = bundle.get("records", bundle.get("receipts"))
|
|
80
|
+
if not isinstance(records, list) or not all(isinstance(r, dict) and "payload" in r and "issuer_sig" in r for r in records):
|
|
81
|
+
problems.append("records: expected an array of { payload, issuer_sig, seal? }")
|
|
82
|
+
keys = bundle.get("keys") or {}
|
|
83
|
+
if not isinstance(keys.get("issuer"), dict) or not isinstance(keys["issuer"].get("keys"), list):
|
|
84
|
+
problems.append('keys.issuer: expected a JWK set ({ "keys": [...] })')
|
|
85
|
+
if problems:
|
|
86
|
+
raise BundleError("Not a valid bundle:\n- " + "\n- ".join(problems))
|
|
87
|
+
return {
|
|
88
|
+
**bundle,
|
|
89
|
+
"records": records,
|
|
90
|
+
"disclosures": bundle.get("disclosures") or [],
|
|
91
|
+
"checkpoints": bundle.get("checkpoints") or [],
|
|
92
|
+
"scope": bundle.get("scope") or {"complete": False},
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def verify_bundle(bundle: Any, *, keys: dict | None = None, tsa_roots: list[dict] | None = None, require_seal: bool = False) -> Report:
|
|
97
|
+
"""Verifies a bundle. Pass `keys` you obtained independently to rule out a substituted bundle."""
|
|
98
|
+
b = parse_bundle(bundle)
|
|
99
|
+
use_keys = keys or b["keys"]
|
|
100
|
+
issuer_keys = use_keys.get("issuer")
|
|
101
|
+
sealer_keys = use_keys.get("sealer") or {"keys": []}
|
|
102
|
+
partial = not bool(b["scope"].get("complete"))
|
|
103
|
+
messages: list[str] = []
|
|
104
|
+
|
|
105
|
+
entries: list[_Entry] = []
|
|
106
|
+
for record in b["records"]:
|
|
107
|
+
p = record.get("payload") or {}
|
|
108
|
+
report = RecordReport(
|
|
109
|
+
receipt_id=str(p.get("receipt_id", "unknown")),
|
|
110
|
+
agent_id=str(p.get("agent_id", "unknown")),
|
|
111
|
+
phase=str(p.get("phase", "")),
|
|
112
|
+
outcome=str(p.get("result", "")),
|
|
113
|
+
checks={"issuer_signature": "fail", "seal": "fail", "chain": "not_checked", "checkpoint": "not_checked", "disclosures": "not_checked", "timestamp": "not_checked"},
|
|
114
|
+
)
|
|
115
|
+
sig = record.get("issuer_sig") or {}
|
|
116
|
+
if sig.get("alg") == "EdDSA" and signature_ok(issuer_keys, sig.get("kid", ""), p, sig.get("sig", "")):
|
|
117
|
+
report.checks["issuer_signature"] = "pass"
|
|
118
|
+
else:
|
|
119
|
+
report.messages.append("The issuer signature does not match this record. It was changed after signing or signed with an unknown key.")
|
|
120
|
+
|
|
121
|
+
seal = record.get("seal")
|
|
122
|
+
seal_valid = False
|
|
123
|
+
if seal:
|
|
124
|
+
seal_valid = signature_ok(sealer_keys, seal.get("sealer_kid", ""), {"digest": digest(p), "seq": seal.get("seq"), "sealed_at": seal.get("sealed_at")}, seal.get("sig", ""))
|
|
125
|
+
if seal_valid:
|
|
126
|
+
report.checks["seal"] = "pass"
|
|
127
|
+
else:
|
|
128
|
+
report.messages.append("The seal does not match this record. It was changed after sealing or sealed with an unknown key.")
|
|
129
|
+
elif require_seal:
|
|
130
|
+
report.messages.append("This record has not been sealed.")
|
|
131
|
+
else:
|
|
132
|
+
report.checks["seal"] = "not_checked"
|
|
133
|
+
report.messages.append("Issuer-signed only: not countersigned by a separate sealing service.")
|
|
134
|
+
entries.append(_Entry(record, report, seal_valid))
|
|
135
|
+
|
|
136
|
+
_check_chains(entries, partial)
|
|
137
|
+
cov_failed, cov_messages, checkpoint = _check_checkpoints(entries, b["checkpoints"], sealer_keys, partial)
|
|
138
|
+
messages += cov_messages
|
|
139
|
+
ts_failed, ts_messages, stamp = _check_timestamps(entries, b["checkpoints"], sealer_keys, partial, tsa_roots)
|
|
140
|
+
messages += ts_messages
|
|
141
|
+
messages += _check_disclosures(entries, b["disclosures"])
|
|
142
|
+
|
|
143
|
+
failed_checks: list[str] = []
|
|
144
|
+
lowest = 2
|
|
145
|
+
for e in entries:
|
|
146
|
+
for name in CHECKS:
|
|
147
|
+
if e.report.checks[name] == "fail" and name not in failed_checks:
|
|
148
|
+
failed_checks.append(name)
|
|
149
|
+
e.report.result = "fail" if "fail" in e.report.checks.values() else "pass"
|
|
150
|
+
e.report.level = "timestamped" if e.report.checks["timestamp"] == "pass" else "sealed" if e.report.checks["seal"] == "pass" else "issuer-signed"
|
|
151
|
+
lowest = min(lowest, LEVELS.index(e.report.level))
|
|
152
|
+
if cov_failed and "checkpoint" not in failed_checks:
|
|
153
|
+
failed_checks.append("checkpoint")
|
|
154
|
+
if ts_failed and "timestamp" not in failed_checks:
|
|
155
|
+
failed_checks.append("timestamp")
|
|
156
|
+
level = LEVELS[lowest] if entries else "issuer-signed"
|
|
157
|
+
failed = cov_failed or ts_failed or any(e.report.result == "fail" for e in entries)
|
|
158
|
+
messages.insert(
|
|
159
|
+
0,
|
|
160
|
+
f"Verification failed: {', '.join(LABELS[c] for c in failed_checks)} check failed."
|
|
161
|
+
if failed
|
|
162
|
+
else f"All {len(entries)} records passed verification. Evidence level: {LEVEL_LABELS[level]}.",
|
|
163
|
+
)
|
|
164
|
+
return Report("fail" if failed else "pass", level, [e.report for e in entries], failed_checks, messages, checkpoint, stamp)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _seq(e: _Entry) -> float:
|
|
168
|
+
seal = e.record.get("seal")
|
|
169
|
+
return seal["seq"] if seal and isinstance(seal.get("seq"), int) else math.inf
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _check_chains(entries: list[_Entry], partial: bool) -> None:
|
|
173
|
+
by_agent: dict[str, list[_Entry]] = {}
|
|
174
|
+
for e in entries:
|
|
175
|
+
by_agent.setdefault(e.report.agent_id, []).append(e)
|
|
176
|
+
for items in by_agent.values():
|
|
177
|
+
ordered = sorted(items, key=lambda e: (_seq(e), str(e.record["payload"].get("issued_at"))))
|
|
178
|
+
for i, e in enumerate(ordered):
|
|
179
|
+
prev = e.record["payload"].get("prev_receipt_hash")
|
|
180
|
+
if i == 0:
|
|
181
|
+
if prev is None:
|
|
182
|
+
e.report.checks["chain"] = "pass"
|
|
183
|
+
elif partial:
|
|
184
|
+
e.report.messages.append("The earlier record in the chain is not included, so this link was not checked.")
|
|
185
|
+
else:
|
|
186
|
+
e.report.checks["chain"] = "fail"
|
|
187
|
+
e.report.messages.append("The record before this one in the agent's chain is missing.")
|
|
188
|
+
elif prev is not None and prev == digest(ordered[i - 1].record):
|
|
189
|
+
e.report.checks["chain"] = "pass"
|
|
190
|
+
elif partial and prev is not None:
|
|
191
|
+
e.report.messages.append("The earlier record in the chain is not included, so this link was not checked.")
|
|
192
|
+
else:
|
|
193
|
+
e.report.checks["chain"] = "fail"
|
|
194
|
+
e.report.messages.append("This record does not link to the previous record in the agent's chain. A record was changed, removed or inserted.")
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _checkpoint_ok(cp: dict, sealer_keys: dict) -> bool:
|
|
198
|
+
return signature_ok(sealer_keys, cp.get("sealer_kid", ""), {"count": cp.get("count"), "head_digest": cp.get("head_digest"), "at": cp.get("at")}, cp.get("sig", ""))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _next_head(prev: str | None, seq: int, payload_digest: str, sealed_at: str) -> str:
|
|
202
|
+
return digest({"prev": prev, "digest": payload_digest, "seq": seq, "sealed_at": sealed_at})
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _check_checkpoints(entries, checkpoints, sealer_keys, partial):
|
|
206
|
+
messages: list[str] = []
|
|
207
|
+
failed = False
|
|
208
|
+
valid = [cp for cp in checkpoints if _checkpoint_ok(cp, sealer_keys)]
|
|
209
|
+
if len(valid) < len(checkpoints):
|
|
210
|
+
failed = True
|
|
211
|
+
messages.append(f"{len(checkpoints) - len(valid)} checkpoint(s) have an invalid sealer signature.")
|
|
212
|
+
if not valid:
|
|
213
|
+
for e in entries:
|
|
214
|
+
if e.record.get("seal"):
|
|
215
|
+
e.report.messages.append("No checkpoint is available yet, so coverage was not checked.")
|
|
216
|
+
return failed, messages, None
|
|
217
|
+
latest = max(valid, key=lambda cp: cp["count"])
|
|
218
|
+
summary = {"count": latest["count"], "at": latest["at"]}
|
|
219
|
+
covered = [e for e in entries if e.record.get("seal") and _seq(e) <= latest["count"]]
|
|
220
|
+
|
|
221
|
+
if partial:
|
|
222
|
+
for e in covered:
|
|
223
|
+
e.report.checks["checkpoint"] = "pass" if e.seal_valid else "fail"
|
|
224
|
+
return failed, messages, summary
|
|
225
|
+
|
|
226
|
+
by_seq: dict[int, _Entry] = {}
|
|
227
|
+
duplicates = set()
|
|
228
|
+
for e in covered:
|
|
229
|
+
s = int(_seq(e))
|
|
230
|
+
if s in by_seq:
|
|
231
|
+
duplicates.add(s)
|
|
232
|
+
by_seq[s] = e
|
|
233
|
+
missing = [s for s in range(1, latest["count"] + 1) if s not in by_seq]
|
|
234
|
+
ok = False
|
|
235
|
+
if not missing and not duplicates:
|
|
236
|
+
head = None
|
|
237
|
+
for s in range(1, latest["count"] + 1):
|
|
238
|
+
rec = by_seq[s].record
|
|
239
|
+
head = _next_head(head, s, digest(rec["payload"]), rec["seal"]["sealed_at"])
|
|
240
|
+
ok = head == latest["head_digest"]
|
|
241
|
+
if not ok:
|
|
242
|
+
failed = True
|
|
243
|
+
if missing:
|
|
244
|
+
messages.append(f"{len(missing)} record(s) covered by the latest checkpoint are missing.")
|
|
245
|
+
elif duplicates:
|
|
246
|
+
messages.append("More than one record uses the same seal number.")
|
|
247
|
+
else:
|
|
248
|
+
messages.append("The records do not match the sealer's latest checkpoint.")
|
|
249
|
+
culprits = [e for e in covered if not e.seal_valid] if (not ok and not missing and not duplicates) else []
|
|
250
|
+
for e in covered:
|
|
251
|
+
if ok or (culprits and e.seal_valid):
|
|
252
|
+
e.report.checks["checkpoint"] = "pass"
|
|
253
|
+
else:
|
|
254
|
+
e.report.checks["checkpoint"] = "fail"
|
|
255
|
+
return failed, messages, summary
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _check_timestamps(entries, checkpoints, sealer_keys, partial, tsa_roots):
|
|
259
|
+
messages: list[str] = []
|
|
260
|
+
anchored = sorted((cp for cp in checkpoints if cp.get("anchors") and _checkpoint_ok(cp, sealer_keys)), key=lambda cp: cp["count"])
|
|
261
|
+
heads: dict[int, str] = {}
|
|
262
|
+
if not partial:
|
|
263
|
+
by_seq = {int(_seq(e)): e for e in entries if e.record.get("seal")}
|
|
264
|
+
head = None
|
|
265
|
+
s = 1
|
|
266
|
+
while s in by_seq:
|
|
267
|
+
rec = by_seq[s].record
|
|
268
|
+
head = _next_head(head, s, digest(rec["payload"]), rec["seal"]["sealed_at"])
|
|
269
|
+
heads[s] = head
|
|
270
|
+
s += 1
|
|
271
|
+
results: list[tuple[dict, TimestampResult]] = []
|
|
272
|
+
for cp in anchored:
|
|
273
|
+
anchor = next((a for a in cp["anchors"] if a.get("type") == "rfc3161"), None)
|
|
274
|
+
res = verify_timestamp_token(anchor["token"], anchor_digest(cp), tsa_roots) if anchor else TimestampResult(False, "The timestamp is of an unsupported type.")
|
|
275
|
+
if res.ok and cp["count"] in heads and heads[cp["count"]] != cp["head_digest"]:
|
|
276
|
+
res = TimestampResult(False, "The records do not match the timestamped checkpoint.")
|
|
277
|
+
results.append((cp, res))
|
|
278
|
+
if not res.ok:
|
|
279
|
+
messages.append(f"The outside timestamp on checkpoint {cp['count']} does not verify: {res.reason}")
|
|
280
|
+
|
|
281
|
+
pending = 0
|
|
282
|
+
for e in entries:
|
|
283
|
+
if not e.record.get("seal") or not e.seal_valid:
|
|
284
|
+
continue
|
|
285
|
+
hit = next(((cp, r) for cp, r in results if cp["count"] >= _seq(e)), None)
|
|
286
|
+
if hit is None:
|
|
287
|
+
pending += 1
|
|
288
|
+
e.report.messages.append("Sealed; outside timestamp pending.")
|
|
289
|
+
continue
|
|
290
|
+
e.report.checks["timestamp"] = "pass" if hit[1].ok else "fail"
|
|
291
|
+
if not hit[1].ok:
|
|
292
|
+
e.report.messages.append(f"The outside timestamp covering this record does not verify: {hit[1].reason}")
|
|
293
|
+
good = [(cp, r) for cp, r in results if r.ok]
|
|
294
|
+
stamp = None
|
|
295
|
+
if good:
|
|
296
|
+
cp, r = good[-1]
|
|
297
|
+
stamp = {"tsa": r.tsa, "at": r.gen_time, "count": cp["count"]}
|
|
298
|
+
messages.append(f"Timestamped by {r.tsa} at {r.gen_time}: the records up to seal {cp['count']} existed then and have not changed since.")
|
|
299
|
+
if pending:
|
|
300
|
+
messages.append(f"{pending} record(s) not yet covered by an outside timestamp." if stamp else "No outside timestamp covers these records yet.")
|
|
301
|
+
return any(not r.ok for _cp, r in results), messages, stamp
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _check_disclosures(entries, disclosures) -> list[str]:
|
|
305
|
+
messages: list[str] = []
|
|
306
|
+
by_id = {e.report.receipt_id: e for e in entries}
|
|
307
|
+
for d in disclosures:
|
|
308
|
+
e = by_id.get(d.get("receiptId"))
|
|
309
|
+
if e is None:
|
|
310
|
+
messages.append(f"A disclosure refers to a record that is not included ({d.get('receiptId')}).")
|
|
311
|
+
continue
|
|
312
|
+
commitment = e.record["payload"].get(FIELDS.get(d.get("field"), ""), None)
|
|
313
|
+
salt = d.get("salt", "")
|
|
314
|
+
ok = (
|
|
315
|
+
isinstance(commitment, str)
|
|
316
|
+
and isinstance(salt, str)
|
|
317
|
+
and len(salt) == 64
|
|
318
|
+
and all(c in "0123456789abcdef" for c in salt)
|
|
319
|
+
and commitment == digest({"salt": salt, "value": d.get("value")})
|
|
320
|
+
)
|
|
321
|
+
if ok:
|
|
322
|
+
if e.report.checks["disclosures"] != "fail":
|
|
323
|
+
e.report.checks["disclosures"] = "pass"
|
|
324
|
+
else:
|
|
325
|
+
e.report.checks["disclosures"] = "fail"
|
|
326
|
+
e.report.messages.append(f"The disclosed {str(d.get('field', '')).replace('_', ' ')} details do not match the record.")
|
|
327
|
+
return messages
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def outcomes(bundle: Any) -> list[str]:
|
|
331
|
+
"""The outcome of each action in the bundle, in order: "confirmed", "not_confirmed", "denied", ..."""
|
|
332
|
+
b = parse_bundle(bundle)
|
|
333
|
+
by_id = {r["payload"].get("receipt_id"): r["payload"] for r in b["records"]}
|
|
334
|
+
|
|
335
|
+
def action_key(p: dict) -> str:
|
|
336
|
+
# Follow decision_ref back to the action's first record (instance commitments may be re-salted per record).
|
|
337
|
+
current = p
|
|
338
|
+
for _ in range(16):
|
|
339
|
+
parent = by_id.get(current.get("decision_ref"))
|
|
340
|
+
if parent is None:
|
|
341
|
+
break
|
|
342
|
+
current = parent
|
|
343
|
+
return current.get("decision_ref") or current.get("receipt_id")
|
|
344
|
+
|
|
345
|
+
groups: dict[str, list[dict]] = {}
|
|
346
|
+
for r in b["records"]:
|
|
347
|
+
groups.setdefault(action_key(r["payload"]), []).append(r["payload"])
|
|
348
|
+
result = []
|
|
349
|
+
for items in groups.values():
|
|
350
|
+
def last(pred):
|
|
351
|
+
return next((p for p in reversed(items) if pred(p)), None)
|
|
352
|
+
|
|
353
|
+
dec = last(lambda p: p["phase"] == "decision" and p["result"] in ("allowed", "held", "denied"))
|
|
354
|
+
appr = last(lambda p: p["phase"] == "decision" and p["result"] in ("approved", "rejected", "expired"))
|
|
355
|
+
exe = last(lambda p: p["phase"] == "execution")
|
|
356
|
+
conf = last(lambda p: p["phase"] == "confirmation")
|
|
357
|
+
if conf:
|
|
358
|
+
result.append("confirmed" if conf["result"] == "confirmed" else "not_confirmed")
|
|
359
|
+
elif exe:
|
|
360
|
+
result.append("executed_unconfirmed" if exe["result"] == "executed" else "failed")
|
|
361
|
+
elif appr:
|
|
362
|
+
result.append({"rejected": "rejected", "expired": "expired"}.get(appr["result"], "allowed_not_executed"))
|
|
363
|
+
elif dec and dec["result"] == "denied":
|
|
364
|
+
result.append("denied")
|
|
365
|
+
elif dec and dec["result"] == "held":
|
|
366
|
+
result.append("awaiting_approval")
|
|
367
|
+
else:
|
|
368
|
+
result.append("allowed_not_executed")
|
|
369
|
+
return result
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: open-action-record
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Verify Open Action Records: signed proof of what an AI agent's action actually changed, and who approved it.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/openactionrecord/oar
|
|
7
|
+
Project-URL: Source, https://github.com/openactionrecord/oar
|
|
8
|
+
Project-URL: Specification, https://github.com/openactionrecord/oar/blob/main/SPEC.md
|
|
9
|
+
Keywords: ai-agents,audit,receipts,verification,provenance,open-action-record,oar
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Security :: Cryptography
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: cryptography>=42
|
|
17
|
+
Requires-Dist: asn1crypto>=1.5
|
|
18
|
+
Requires-Dist: rfc8785>=0.1.4
|
|
19
|
+
Provides-Extra: test
|
|
20
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# open-action-record (Python)
|
|
24
|
+
|
|
25
|
+
Verify [Open Action Records](https://github.com/openactionrecord/oar): signed proof of what an AI agent's action actually changed, and who approved it.
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install open-action-record
|
|
29
|
+
oar-verify evidence.json
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import json
|
|
34
|
+
from open_action_record import verify_bundle, outcomes
|
|
35
|
+
|
|
36
|
+
bundle = json.load(open("evidence.json"))
|
|
37
|
+
report = verify_bundle(bundle) # pass keys=... to check against keys you trust
|
|
38
|
+
print(report.result, report.level) # "pass", "sealed"
|
|
39
|
+
print(outcomes(bundle)) # ["confirmed", "denied", "not_confirmed"]
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
It checks every record's issuer signature, the separate sealing service's seal, each agent's hash chain, checkpoint coverage, outside RFC 3161 timestamps (against the bundled DigiCert roots) and any disclosed values. It reaches the same result as the TypeScript and browser verifiers on every shared test vector.
|
|
43
|
+
|
|
44
|
+
Writing records from Python is planned; today, write them with [`@openactionrecord/core`](https://www.npmjs.com/package/@openactionrecord/core).
|
|
45
|
+
|
|
46
|
+
Apache-2.0.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/open_action_record/__init__.py
|
|
5
|
+
src/open_action_record/canonical.py
|
|
6
|
+
src/open_action_record/cli.py
|
|
7
|
+
src/open_action_record/py.typed
|
|
8
|
+
src/open_action_record/timestamp.py
|
|
9
|
+
src/open_action_record/tsa_roots.json
|
|
10
|
+
src/open_action_record/verify.py
|
|
11
|
+
src/open_action_record.egg-info/PKG-INFO
|
|
12
|
+
src/open_action_record.egg-info/SOURCES.txt
|
|
13
|
+
src/open_action_record.egg-info/dependency_links.txt
|
|
14
|
+
src/open_action_record.egg-info/entry_points.txt
|
|
15
|
+
src/open_action_record.egg-info/requires.txt
|
|
16
|
+
src/open_action_record.egg-info/top_level.txt
|
|
17
|
+
tests/test_vectors.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
open_action_record
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""The Python verifier must reach the expected result on every shared test vector."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from open_action_record import outcomes, verify_bundle
|
|
9
|
+
|
|
10
|
+
ROOT = Path(__file__).resolve().parents[2] / "vectors"
|
|
11
|
+
CASES = []
|
|
12
|
+
for folder in (ROOT, ROOT / "compat"):
|
|
13
|
+
manifest = json.loads((folder / "manifest.json").read_text())
|
|
14
|
+
roots = json.loads((folder / manifest["tsa_roots_file"]).read_text())
|
|
15
|
+
for case in manifest["cases"]:
|
|
16
|
+
CASES.append(pytest.param(folder, roots, case, id=f"{folder.name}/{case['file']}{'+require_seal' if case['options'].get('require_seal') else ''}"))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@pytest.mark.parametrize("folder,roots,case", CASES)
|
|
20
|
+
def test_vector(folder, roots, case):
|
|
21
|
+
bundle = json.loads((folder / case["file"]).read_text())
|
|
22
|
+
report = verify_bundle(
|
|
23
|
+
bundle,
|
|
24
|
+
tsa_roots=roots if case["options"].get("tsa_roots") == "test" else None,
|
|
25
|
+
require_seal=bool(case["options"].get("require_seal")),
|
|
26
|
+
)
|
|
27
|
+
expect = case["expect"]
|
|
28
|
+
assert report.result == expect["result"], report.messages
|
|
29
|
+
if "level" in expect:
|
|
30
|
+
assert report.level == expect["level"]
|
|
31
|
+
if "failedChecks" in expect:
|
|
32
|
+
assert sorted(report.failed_checks) == sorted(expect["failedChecks"])
|
|
33
|
+
if "outcomes" in expect:
|
|
34
|
+
assert outcomes(bundle) == expect["outcomes"]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_untrusted_timestamp_root_fails():
|
|
38
|
+
bundle = json.loads((ROOT / "refund-lifecycle.json").read_text())
|
|
39
|
+
report = verify_bundle(bundle) # bundled DigiCert roots: the test authority is not trusted
|
|
40
|
+
assert report.result == "fail"
|
|
41
|
+
assert "timestamp" in report.failed_checks
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_substituted_keys_fail():
|
|
45
|
+
bundle = json.loads((ROOT / "issuer-signed.json").read_text())
|
|
46
|
+
other = {"issuer": {"keys": [{**bundle["keys"]["issuer"]["keys"][0], "x": "A" * 43}]}}
|
|
47
|
+
assert verify_bundle(bundle, keys=other).result == "fail"
|