tests/test_timestamp.py
311 lines · 11075 bytes
18 symbols in this file
issue_tokenissue_signed_tokenmanifesttest_build_request_carries_the_idtest_parse_token_fieldstest_apply_and_verify_roundtriptest_apply_accepts_bare_tokentest_apply_refuses_token_for_other_idtest_timestamp_does_not_change_manifest_idtest_verify_fails_if_id_changed_after_stampingtest_verify_unstamped_manifesttest_submit_rejects_non_http_urltest_full_signature_verifiestest_full_signature_via_verify_timestamptest_full_signature_wrong_cert_rejectedtest_full_signature_missing_eku_rejectedtest_full_signature_gen_time_outside_validity_rejectedtest_full_signature_tampered_content_rejected
1"""Tests for RFC 3161 timestamping (skipped if asn1crypto is absent).
2
3These build tokens locally (acting as a TSA) so the whole flow is exercised
4offline — no network and no real Time-Stamp Authority.
5"""
6
7from datetime import datetime, timezone
8
9import pytest
10
11pytest.importorskip("asn1crypto")
12
13from asn1crypto import algos, cms, core, tsp
14
15from evidence_seal.manifest import build_manifest, compute_id
16from evidence_seal.timestamp import (
17 apply_timestamp,
18 build_request,
19 parse_token,
20 submit,
21 verify_timestamp,
22)
23
24
25def issue_token(imprint_hex: str, gen_time=None, as_response=True) -> bytes:
26 """Mint a timestamp token over *imprint_hex*, as a local TSA would."""
27 gen_time = gen_time or datetime(2026, 8, 6, 9, 0, tzinfo=timezone.utc)
28 tst = tsp.TSTInfo(
29 {
30 "version": "v1",
31 "policy": "1.2.3.4.5",
32 "message_imprint": tsp.MessageImprint(
33 {
34 "hash_algorithm": algos.DigestAlgorithm({"algorithm": "sha256"}),
35 "hashed_message": bytes.fromhex(imprint_hex),
36 }
37 ),
38 "serial_number": 7,
39 "gen_time": gen_time,
40 }
41 )
42 token = cms.ContentInfo(
43 {
44 "content_type": "signed_data",
45 "content": cms.SignedData(
46 {
47 "version": "v3",
48 "digest_algorithms": [],
49 "encap_content_info": cms.EncapsulatedContentInfo(
50 {"content_type": "tst_info", "content": core.ParsableOctetString(tst.dump())}
51 ),
52 "signer_infos": [],
53 }
54 ),
55 }
56 )
57 if not as_response:
58 return token.dump()
59 return tsp.TimeStampResp(
60 {"status": {"status": "granted"}, "time_stamp_token": token}
61 ).dump()
62
63
64def issue_signed_token(imprint_hex, gen_time=None, timestamping_eku=True, validity=None):
65 """Mint a genuinely CMS-signed token; return ``(response_der, cert_pem)``.
66
67 Acts as a real (self-signed) TSA so full signature verification can be
68 exercised offline.
69 """
70 import datetime
71
72 from asn1crypto import x509 as a1x509
73 from cryptography import x509
74 from cryptography.hazmat.primitives import hashes, serialization
75 from cryptography.hazmat.primitives.asymmetric import padding, rsa
76 from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
77
78 gen_time = gen_time or datetime.datetime(2026, 8, 6, 9, 0, tzinfo=datetime.timezone.utc)
79 not_before, not_after = validity or (
80 datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc),
81 datetime.datetime(2030, 1, 1, tzinfo=datetime.timezone.utc),
82 )
83 key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
84 name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Test TSA")])
85 builder = (
86 x509.CertificateBuilder()
87 .subject_name(name)
88 .issuer_name(name)
89 .public_key(key.public_key())
90 .serial_number(4242)
91 .not_valid_before(not_before)
92 .not_valid_after(not_after)
93 )
94 if timestamping_eku:
95 builder = builder.add_extension(
96 x509.ExtendedKeyUsage([ExtendedKeyUsageOID.TIME_STAMPING]), critical=True
97 )
98 cert = builder.sign(key, hashes.SHA256())
99 cert_der = cert.public_bytes(serialization.Encoding.DER)
100 cert_pem = cert.public_bytes(serialization.Encoding.PEM)
101
102 imprint = tsp.MessageImprint(
103 {
104 "hash_algorithm": algos.DigestAlgorithm({"algorithm": "sha256"}),
105 "hashed_message": bytes.fromhex(imprint_hex),
106 }
107 )
108 tst = tsp.TSTInfo(
109 {
110 "version": "v1",
111 "policy": "1.2.3.4.5",
112 "message_imprint": imprint,
113 "serial_number": 7,
114 "gen_time": gen_time,
115 }
116 )
117 econtent = tst.dump()
118
119 import hashlib
120
121 signed_attrs = cms.CMSAttributes(
122 [
123 cms.CMSAttribute({"type": "content_type", "values": ["tst_info"]}),
124 cms.CMSAttribute(
125 {"type": "message_digest", "values": [core.OctetString(hashlib.sha256(econtent).digest())]}
126 ),
127 ]
128 )
129 signature = key.sign(signed_attrs.untag().dump(), padding.PKCS1v15(), hashes.SHA256())
130 signer_info = cms.SignerInfo(
131 {
132 "version": "v1",
133 "sid": cms.SignerIdentifier(
134 {
135 "issuer_and_serial_number": cms.IssuerAndSerialNumber(
136 {"issuer": a1x509.Certificate.load(cert_der).issuer, "serial_number": 4242}
137 )
138 }
139 ),
140 "digest_algorithm": algos.DigestAlgorithm({"algorithm": "sha256"}),
141 "signed_attrs": signed_attrs,
142 "signature_algorithm": algos.SignedDigestAlgorithm({"algorithm": "rsassa_pkcs1v15"}),
143 "signature": signature,
144 }
145 )
146 signed_data = cms.SignedData(
147 {
148 "version": "v3",
149 "digest_algorithms": [algos.DigestAlgorithm({"algorithm": "sha256"})],
150 "encap_content_info": cms.EncapsulatedContentInfo(
151 {"content_type": "tst_info", "content": core.ParsableOctetString(econtent)}
152 ),
153 "certificates": [a1x509.Certificate.load(cert_der)],
154 "signer_infos": [signer_info],
155 }
156 )
157 token = cms.ContentInfo({"content_type": "signed_data", "content": signed_data})
158 response = tsp.TimeStampResp({"status": {"status": "granted"}, "time_stamp_token": token})
159 return response.dump(), cert_pem
160
161
162@pytest.fixture
163def manifest(tmp_path):
164 d = tmp_path / "pkg"
165 d.mkdir()
166 (d / "a.csv").write_text("x\n", encoding="utf-8")
167 return build_manifest(d)
168
169
170def test_build_request_carries_the_id(manifest):
171 der = build_request(manifest["id"])
172 req = tsp.TimeStampReq.load(der)
173 assert req["message_imprint"]["hashed_message"].native.hex() == manifest["id"]
174 assert req["message_imprint"]["hash_algorithm"]["algorithm"].native == "sha256"
175
176
177def test_parse_token_fields(manifest):
178 fields = parse_token(issue_token(manifest["id"]))
179 assert fields["imprint"] == manifest["id"]
180 assert fields["imprint_algorithm"] == "sha256"
181 assert fields["gen_time"] == "2026-08-06T09:00:00Z"
182 assert fields["serial_number"] == "7"
183
184
185def test_apply_and_verify_roundtrip(manifest):
186 stamped = apply_timestamp(manifest, issue_token(manifest["id"]))
187 assert stamped["timestamp"]["gen_time"] == "2026-08-06T09:00:00Z"
188 ok, message = verify_timestamp(stamped)
189 assert ok
190 assert "2026-08-06T09:00:00Z" in message
191
192
193def test_apply_accepts_bare_token(manifest):
194 stamped = apply_timestamp(manifest, issue_token(manifest["id"], as_response=False))
195 assert verify_timestamp(stamped)[0]
196
197
198def test_apply_refuses_token_for_other_id(manifest):
199 wrong = "0" * 64
200 token = issue_token(wrong)
201 with pytest.raises(ValueError, match="does not timestamp this manifest"):
202 apply_timestamp(manifest, token)
203
204
205def test_timestamp_does_not_change_manifest_id(manifest):
206 before = manifest["id"]
207 stamped = apply_timestamp(manifest, issue_token(manifest["id"]))
208 # The timestamp block is excluded from the id, so the id is unchanged.
209 assert compute_id(stamped) == before
210
211
212def test_verify_fails_if_id_changed_after_stamping(manifest):
213 stamped = apply_timestamp(manifest, issue_token(manifest["id"]))
214 # Simulate a re-seal after tampering: the id moves, orphaning the timestamp.
215 stamped["id"] = "1" * 64
216 ok, message = verify_timestamp(stamped)
217 assert not ok
218 assert "does not match the manifest id" in message
219
220
221def test_verify_unstamped_manifest(manifest):
222 ok, message = verify_timestamp(manifest)
223 assert not ok
224 assert "not timestamped" in message
225
226
227def test_submit_rejects_non_http_url(manifest, tmp_path):
228 target = tmp_path / "tsa.tsr"
229 target.write_bytes(b"")
230 with pytest.raises(ValueError, match="http or https"):
231 submit(build_request(manifest["id"]), target.as_uri())
232
233
234# --- full CMS signature verification (needs cryptography) ---
235
236
237def test_full_signature_verifies(manifest):
238 pytest.importorskip("cryptography")
239 from evidence_seal.timestamp import verify_token_signature
240
241 token, cert_pem = issue_signed_token(manifest["id"])
242 ok, message = verify_token_signature(token, cert_pem)
243 assert ok
244 assert "valid" in message
245 assert "Test TSA" in message
246
247
248def test_full_signature_via_verify_timestamp(manifest):
249 pytest.importorskip("cryptography")
250 token, cert_pem = issue_signed_token(manifest["id"])
251 stamped = apply_timestamp(manifest, token)
252 ok, message = verify_timestamp(stamped, tsa_cert=cert_pem)
253 assert ok
254 assert "TSA signature valid" in message
255
256
257def test_full_signature_wrong_cert_rejected(manifest):
258 pytest.importorskip("cryptography")
259 from evidence_seal.timestamp import verify_token_signature
260
261 token, _cert = issue_signed_token(manifest["id"])
262 _other_token, other_cert = issue_signed_token(manifest["id"])
263 # A different cert (different key, but same serial in our helper) must fail
264 # either the signer match or the cryptographic check.
265 ok, message = verify_token_signature(token, other_cert)
266 assert not ok
267 assert "TSA signature" in message
268
269
270def test_full_signature_missing_eku_rejected(manifest):
271 pytest.importorskip("cryptography")
272 from evidence_seal.timestamp import verify_token_signature
273
274 token, cert_pem = issue_signed_token(manifest["id"], timestamping_eku=False)
275 ok, message = verify_token_signature(token, cert_pem)
276 assert not ok
277 assert "timeStamping" in message
278
279
280def test_full_signature_gen_time_outside_validity_rejected(manifest):
281 import datetime
282
283 pytest.importorskip("cryptography")
284 from evidence_seal.timestamp import verify_token_signature
285
286 # gen_time in 2026 but the cert is only valid in 2020.
287 token, cert_pem = issue_signed_token(
288 manifest["id"],
289 validity=(
290 datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
291 datetime.datetime(2021, 1, 1, tzinfo=datetime.timezone.utc),
292 ),
293 )
294 ok, message = verify_token_signature(token, cert_pem)
295 assert not ok
296 assert "validity window" in message
297
298
299def test_full_signature_tampered_content_rejected(manifest):
300 pytest.importorskip("cryptography")
301 from evidence_seal.timestamp import verify_token_signature
302
303 # A token whose imprint is for a different id: the signature is valid over
304 # its own content, but apply_timestamp would refuse it, and here we confirm
305 # the signature itself is bound to the (wrong) content it was issued for.
306 token, cert_pem = issue_signed_token("a" * 64)
307 ok, _message = verify_token_signature(token, cert_pem)
308 assert ok # signature is valid for its own content...
309 # ...but it does not bind to this manifest, which apply enforces.
310 with pytest.raises(ValueError, match="does not timestamp"):
311 apply_timestamp(manifest, token)