lukuid-sdk 1.0.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.
lukuid_sdk/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ from .luku import (
3
+ LUKU_MIMETYPE,
4
+ Criticality,
5
+ LukuArchive,
6
+ LukuBlock,
7
+ LukuDeviceIdentity,
8
+ LukuFile,
9
+ LukuItemResult,
10
+ LukuManifest,
11
+ LukuParseResult,
12
+ LukuSigner,
13
+ LukuVerifyOptions,
14
+ VerificationIssue,
15
+ )
16
+
17
+ __all__ = [
18
+ "Criticality",
19
+ "LUKU_MIMETYPE",
20
+ "LukuArchive",
21
+ "LukuBlock",
22
+ "LukuDeviceIdentity",
23
+ "LukuFile",
24
+ "LukuItemResult",
25
+ "LukuManifest",
26
+ "LukuParseResult",
27
+ "LukuSigner",
28
+ "LukuVerifyOptions",
29
+ "VerificationIssue",
30
+ ]
@@ -0,0 +1,277 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import tempfile
9
+ from dataclasses import dataclass
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+
13
+
14
+ @dataclass(slots=True)
15
+ class DeviceAttestationInputs:
16
+ id: str
17
+ key: str
18
+ attestation_sig: str
19
+ certificate_chain: str | None = None
20
+ created: int | None = None
21
+ attestation_alg: str | None = None
22
+ attestation_payload_version: int | None = None
23
+ trust_profile: str = os.environ.get("LUKUID_TRUST_PROFILE", "prod")
24
+
25
+
26
+ @dataclass(slots=True)
27
+ class VerificationResult:
28
+ ok: bool
29
+ reason: str | None = None
30
+
31
+
32
+ # Mirrors the current Rust/Android shortcut: strict verification requires a
33
+ # configured trusted root to exist, but does not yet perform full PQC root
34
+ # signature validation in-process.
35
+ TRUSTED_ROOT_CERTS_PEM = ["configured-root-present"]
36
+
37
+ _CERT_PATTERN = re.compile(
38
+ r"-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----"
39
+ )
40
+ _ED25519_SPKI_PREFIX = bytes.fromhex("302a300506032b6570032100")
41
+
42
+
43
+ def verify_device_attestation(inputs: DeviceAttestationInputs) -> VerificationResult:
44
+ if not inputs.attestation_sig:
45
+ return VerificationResult(False, "attestationSig missing")
46
+
47
+ try:
48
+ signature_bytes = base64.b64decode(inputs.attestation_sig, validate=True)
49
+ except Exception:
50
+ return VerificationResult(False, "attestationSig is not valid base64")
51
+
52
+ payload = f"{inputs.id}:{inputs.key}".encode("utf-8")
53
+ leaf_public_key_pem: str | None = None
54
+
55
+ if inputs.certificate_chain:
56
+ certs = _CERT_PATTERN.findall(inputs.certificate_chain)
57
+ if not certs:
58
+ return VerificationResult(False, "Invalid certificate chain PEM")
59
+
60
+ try:
61
+ leaf_meta = _certificate_metadata(certs[0])
62
+ leaf_public_key_pem = leaf_meta["public_key_pem"]
63
+ except Exception as exc:
64
+ return VerificationResult(False, f"Chain processing error: {exc}")
65
+
66
+ required_ou = {
67
+ "dev": "lukuid-dev",
68
+ "test": "lukuid-test",
69
+ "prod": "lukuid-production",
70
+ }.get(inputs.trust_profile, "lukuid-production")
71
+
72
+ has_valid_profile = False
73
+ try:
74
+ for cert_pem in certs[1:]:
75
+ subject = _certificate_metadata(cert_pem)["subject"]
76
+ if required_ou in subject:
77
+ has_valid_profile = True
78
+ break
79
+ except Exception as exc:
80
+ return VerificationResult(False, f"Chain processing error: {exc}")
81
+
82
+ if not has_valid_profile:
83
+ return VerificationResult(
84
+ False,
85
+ f"Certificate chain does not match the requested trust profile: {inputs.trust_profile}",
86
+ )
87
+
88
+ if not TRUSTED_ROOT_CERTS_PEM:
89
+ return VerificationResult(False, "Certificate chain not trusted by any root")
90
+
91
+ if inputs.created is not None:
92
+ try:
93
+ for cert_pem in certs:
94
+ meta = _certificate_metadata(cert_pem)
95
+ valid_from = meta["not_before"]
96
+ valid_to = meta["not_after"]
97
+ if inputs.created < valid_from or inputs.created > valid_to:
98
+ return VerificationResult(
99
+ False,
100
+ f"Temporal birth check failed: created ({inputs.created}) is outside cert window [{valid_from} - {valid_to}]",
101
+ )
102
+ except Exception as exc:
103
+ return VerificationResult(False, f"Chain processing error: {exc}")
104
+
105
+ if leaf_public_key_pem is not None:
106
+ if _verify_signature_with_pem(leaf_public_key_pem, payload, signature_bytes):
107
+ return VerificationResult(True)
108
+ return VerificationResult(False, "Attestation verification failed")
109
+
110
+ for _root in TRUSTED_ROOT_CERTS_PEM:
111
+ return VerificationResult(False, "Attestation verification failed")
112
+
113
+ return VerificationResult(False, "Attestation verification failed")
114
+
115
+
116
+ def verify_detached_signature(public_key_base64: str, payload: bytes, signature_base64: str) -> bool:
117
+ try:
118
+ raw_public_key = base64.b64decode(public_key_base64, validate=True)
119
+ signature = base64.b64decode(signature_base64, validate=True)
120
+ except Exception:
121
+ return False
122
+
123
+ if len(raw_public_key) < 32:
124
+ return False
125
+
126
+ public_key_pem = _ed25519_public_key_pem(raw_public_key[:32])
127
+ return _verify_signature_with_pem(public_key_pem, payload, signature)
128
+
129
+
130
+ def sign_detached(private_key_pem: str, payload: bytes) -> str:
131
+ with tempfile.TemporaryDirectory() as tmpdir:
132
+ key_path = Path(tmpdir) / "key.pem"
133
+ payload_path = Path(tmpdir) / "payload.bin"
134
+ sig_path = Path(tmpdir) / "sig.bin"
135
+ key_path.write_text(private_key_pem, encoding="utf-8")
136
+ payload_path.write_bytes(payload)
137
+ _run(
138
+ [
139
+ "openssl",
140
+ "pkeyutl",
141
+ "-sign",
142
+ "-inkey",
143
+ str(key_path),
144
+ "-rawin",
145
+ "-in",
146
+ str(payload_path),
147
+ "-out",
148
+ str(sig_path),
149
+ ]
150
+ )
151
+ return base64.b64encode(sig_path.read_bytes()).decode("ascii")
152
+
153
+
154
+ def public_key_base64_from_private_key_pem(private_key_pem: str) -> str:
155
+ with tempfile.TemporaryDirectory() as tmpdir:
156
+ key_path = Path(tmpdir) / "key.pem"
157
+ pub_der_path = Path(tmpdir) / "pub.der"
158
+ key_path.write_text(private_key_pem, encoding="utf-8")
159
+ _run(
160
+ [
161
+ "openssl",
162
+ "pkey",
163
+ "-in",
164
+ str(key_path),
165
+ "-pubout",
166
+ "-outform",
167
+ "DER",
168
+ "-out",
169
+ str(pub_der_path),
170
+ ]
171
+ )
172
+ pub_der = pub_der_path.read_bytes()
173
+ if not pub_der.startswith(_ED25519_SPKI_PREFIX):
174
+ raise ValueError("Unexpected Ed25519 public key encoding")
175
+ return base64.b64encode(pub_der[len(_ED25519_SPKI_PREFIX):]).decode("ascii")
176
+
177
+
178
+ def generate_signer() -> tuple[str, str]:
179
+ with tempfile.TemporaryDirectory() as tmpdir:
180
+ key_path = Path(tmpdir) / "key.pem"
181
+ _run(["openssl", "genpkey", "-algorithm", "ED25519", "-out", str(key_path)])
182
+ private_key_pem = key_path.read_text(encoding="utf-8")
183
+ public_key_base64 = public_key_base64_from_private_key_pem(private_key_pem)
184
+ return private_key_pem, public_key_base64
185
+
186
+
187
+ def pem_from_der_string(value: str | None) -> str | None:
188
+ if not value:
189
+ return None
190
+ try:
191
+ der_bytes = base64.b64decode(value, validate=True)
192
+ except Exception:
193
+ return None
194
+ body = base64.encodebytes(der_bytes).decode("ascii").replace("\n", "")
195
+ lines = [body[index:index + 64] for index in range(0, len(body), 64)]
196
+ return "-----BEGIN CERTIFICATE-----\n" + "\n".join(lines) + "\n-----END CERTIFICATE-----\n"
197
+
198
+
199
+ def _verify_signature_with_pem(public_key_pem: str, payload: bytes, signature: bytes) -> bool:
200
+ with tempfile.TemporaryDirectory() as tmpdir:
201
+ pub_path = Path(tmpdir) / "pub.pem"
202
+ payload_path = Path(tmpdir) / "payload.bin"
203
+ sig_path = Path(tmpdir) / "sig.bin"
204
+ pub_path.write_text(public_key_pem, encoding="utf-8")
205
+ payload_path.write_bytes(payload)
206
+ sig_path.write_bytes(signature)
207
+ result = subprocess.run(
208
+ [
209
+ "openssl",
210
+ "pkeyutl",
211
+ "-verify",
212
+ "-pubin",
213
+ "-inkey",
214
+ str(pub_path),
215
+ "-rawin",
216
+ "-in",
217
+ str(payload_path),
218
+ "-sigfile",
219
+ str(sig_path),
220
+ ],
221
+ capture_output=True,
222
+ text=True,
223
+ )
224
+ return result.returncode == 0
225
+
226
+
227
+ def _certificate_metadata(cert_pem: str) -> dict[str, str | int]:
228
+ with tempfile.TemporaryDirectory() as tmpdir:
229
+ cert_path = Path(tmpdir) / "cert.pem"
230
+ cert_path.write_text(cert_pem, encoding="utf-8")
231
+ result = _run(
232
+ [
233
+ "openssl",
234
+ "x509",
235
+ "-in",
236
+ str(cert_path),
237
+ "-noout",
238
+ "-subject",
239
+ "-dates",
240
+ "-pubkey",
241
+ "-nameopt",
242
+ "RFC2253",
243
+ ]
244
+ )
245
+
246
+ lines = [line.strip() for line in result.splitlines() if line.strip()]
247
+ subject_line = next(line for line in lines if line.startswith("subject="))
248
+ not_before_line = next(line for line in lines if line.startswith("notBefore="))
249
+ not_after_line = next(line for line in lines if line.startswith("notAfter="))
250
+ pub_start = lines.index("-----BEGIN PUBLIC KEY-----")
251
+ public_key_pem = "\n".join(lines[pub_start:]) + "\n"
252
+
253
+ return {
254
+ "subject": subject_line.split("=", 1)[1],
255
+ "not_before": _parse_openssl_time(not_before_line.split("=", 1)[1]),
256
+ "not_after": _parse_openssl_time(not_after_line.split("=", 1)[1]),
257
+ "public_key_pem": public_key_pem,
258
+ }
259
+
260
+
261
+ def _parse_openssl_time(value: str) -> int:
262
+ parsed = datetime.strptime(value, "%b %d %H:%M:%S %Y %Z")
263
+ return int(parsed.replace(tzinfo=timezone.utc).timestamp())
264
+
265
+
266
+ def _ed25519_public_key_pem(raw_public_key: bytes) -> str:
267
+ der = _ED25519_SPKI_PREFIX + raw_public_key
268
+ body = base64.encodebytes(der).decode("ascii").replace("\n", "")
269
+ lines = [body[index:index + 64] for index in range(0, len(body), 64)]
270
+ return "-----BEGIN PUBLIC KEY-----\n" + "\n".join(lines) + "\n-----END PUBLIC KEY-----\n"
271
+
272
+
273
+ def _run(cmd: list[str]) -> str:
274
+ result = subprocess.run(cmd, capture_output=True, text=True)
275
+ if result.returncode != 0:
276
+ raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "openssl command failed")
277
+ return result.stdout
lukuid_sdk/luku.py ADDED
@@ -0,0 +1,685 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import hashlib
6
+ import io
7
+ import json
8
+ import time
9
+ import zipfile
10
+ from dataclasses import dataclass, field
11
+ from enum import Enum
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from .attestation import (
16
+ DeviceAttestationInputs,
17
+ generate_signer,
18
+ pem_from_der_string,
19
+ public_key_base64_from_private_key_pem,
20
+ sign_detached,
21
+ verify_detached_signature,
22
+ verify_device_attestation,
23
+ )
24
+
25
+ LUKU_MIMETYPE = "application/vnd.lukuid.package+zip"
26
+
27
+
28
+ class Criticality(str, Enum):
29
+ INFO = "info"
30
+ WARNING = "warning"
31
+ CRITICAL = "critical"
32
+
33
+
34
+ @dataclass(slots=True)
35
+ class VerificationIssue:
36
+ code: str
37
+ message: str
38
+ criticality: Criticality
39
+
40
+
41
+ @dataclass(slots=True)
42
+ class LukuVerifyOptions:
43
+ allow_untrusted_roots: bool = False
44
+ skip_certificate_temporal_checks: bool = False
45
+ trusted_external_fingerprints: list[str] = field(default_factory=list)
46
+ trust_profile: str = "prod"
47
+
48
+
49
+ @dataclass(slots=True)
50
+ class LukuItemResult:
51
+ type: str
52
+ verified: bool
53
+ payload: dict[str, Any]
54
+ errors: list[str] | None = None
55
+
56
+
57
+ @dataclass(slots=True)
58
+ class LukuParseResult:
59
+ verified: bool
60
+ items: list[LukuItemResult]
61
+ issues: list[VerificationIssue]
62
+
63
+
64
+ @dataclass(slots=True)
65
+ class LukuSigner:
66
+ private_key_pem: str
67
+ public_key_base64: str
68
+
69
+ @classmethod
70
+ def generate(cls) -> "LukuSigner":
71
+ private_key_pem, public_key_base64 = generate_signer()
72
+ return cls(private_key_pem=private_key_pem, public_key_base64=public_key_base64)
73
+
74
+ @classmethod
75
+ def from_private_key_pem(cls, private_key_pem: str) -> "LukuSigner":
76
+ return cls(
77
+ private_key_pem=private_key_pem,
78
+ public_key_base64=public_key_base64_from_private_key_pem(private_key_pem),
79
+ )
80
+
81
+
82
+ @dataclass(slots=True)
83
+ class LukuManifest:
84
+ type: str
85
+ version: str
86
+ created_at_utc: int
87
+ description: str
88
+ blocks_hash: str
89
+ extra: dict[str, Any] = field(default_factory=dict)
90
+
91
+ @classmethod
92
+ def from_json(cls, value: dict[str, Any]) -> "LukuManifest":
93
+ extra = dict(value)
94
+ for key in ["type", "version", "created_at_utc", "description", "blocks_hash"]:
95
+ extra.pop(key, None)
96
+ return cls(
97
+ type=str(value.get("type", "")),
98
+ version=str(value.get("version", "")),
99
+ created_at_utc=_uint64(value.get("created_at_utc")) or 0,
100
+ description=str(value.get("description", "")),
101
+ blocks_hash=str(value.get("blocks_hash", "")),
102
+ extra=extra,
103
+ )
104
+
105
+ def json_object(self) -> dict[str, Any]:
106
+ data = dict(self.extra)
107
+ data.update(
108
+ {
109
+ "type": self.type,
110
+ "version": self.version,
111
+ "created_at_utc": self.created_at_utc,
112
+ "description": self.description,
113
+ "blocks_hash": self.blocks_hash,
114
+ }
115
+ )
116
+ return data
117
+
118
+
119
+ @dataclass(slots=True)
120
+ class LukuDeviceIdentity:
121
+ device_id: str
122
+ public_key: str
123
+
124
+ @classmethod
125
+ def from_json(cls, value: dict[str, Any]) -> "LukuDeviceIdentity":
126
+ return cls(
127
+ device_id=str(value.get("device_id", "")),
128
+ public_key=str(value.get("public_key", "")),
129
+ )
130
+
131
+ def json_object(self) -> dict[str, Any]:
132
+ return {"device_id": self.device_id, "public_key": self.public_key}
133
+
134
+
135
+ @dataclass(slots=True)
136
+ class LukuBlock:
137
+ block_id: int
138
+ timestamp_utc: int
139
+ previous_block_hash: str | None
140
+ device: LukuDeviceIdentity
141
+ batch: list[dict[str, Any]]
142
+ batch_hash: str = ""
143
+ block_canonical_string: str = ""
144
+ block_hash: str = ""
145
+ attestation_dac_der: str | None = None
146
+ attestation_manufacturer_der: str | None = None
147
+ attestation_intermediate_der: str | None = None
148
+ attestation_root_fingerprint: str | None = None
149
+ heartbeat_slac_der: str | None = None
150
+ heartbeat_der: str | None = None
151
+ heartbeat_intermediate_der: str | None = None
152
+ heartbeat_root_fingerprint: str | None = None
153
+
154
+ @classmethod
155
+ def from_json(cls, value: dict[str, Any]) -> "LukuBlock":
156
+ return cls(
157
+ block_id=_uint64(value.get("block_id")) or 0,
158
+ timestamp_utc=_uint64(value.get("timestamp_utc")) or 0,
159
+ previous_block_hash=value.get("previous_block_hash"),
160
+ device=LukuDeviceIdentity.from_json(value.get("device") or {}),
161
+ batch=copy.deepcopy(value.get("batch") or []),
162
+ batch_hash=str(value.get("batch_hash", "")),
163
+ block_canonical_string=str(value.get("block_canonical_string", "")),
164
+ block_hash=str(value.get("block_hash", "")),
165
+ attestation_dac_der=value.get("attestation_dac_der"),
166
+ attestation_manufacturer_der=value.get("attestation_manufacturer_der"),
167
+ attestation_intermediate_der=value.get("attestation_intermediate_der"),
168
+ attestation_root_fingerprint=value.get("attestation_root_fingerprint"),
169
+ heartbeat_slac_der=value.get("heartbeat_slac_der"),
170
+ heartbeat_der=value.get("heartbeat_der"),
171
+ heartbeat_intermediate_der=value.get("heartbeat_intermediate_der"),
172
+ heartbeat_root_fingerprint=value.get("heartbeat_root_fingerprint"),
173
+ )
174
+
175
+ def json_object(self) -> dict[str, Any]:
176
+ data: dict[str, Any] = {
177
+ "block_id": self.block_id,
178
+ "timestamp_utc": self.timestamp_utc,
179
+ "device": self.device.json_object(),
180
+ "batch": self.batch,
181
+ "batch_hash": self.batch_hash,
182
+ "block_canonical_string": self.block_canonical_string,
183
+ "block_hash": self.block_hash,
184
+ }
185
+ if self.previous_block_hash is not None:
186
+ data["previous_block_hash"] = self.previous_block_hash
187
+ if self.attestation_dac_der is not None:
188
+ data["attestation_dac_der"] = self.attestation_dac_der
189
+ if self.attestation_manufacturer_der is not None:
190
+ data["attestation_manufacturer_der"] = self.attestation_manufacturer_der
191
+ if self.attestation_intermediate_der is not None:
192
+ data["attestation_intermediate_der"] = self.attestation_intermediate_der
193
+ if self.attestation_root_fingerprint is not None:
194
+ data["attestation_root_fingerprint"] = self.attestation_root_fingerprint
195
+ if self.heartbeat_slac_der is not None:
196
+ data["heartbeat_slac_der"] = self.heartbeat_slac_der
197
+ if self.heartbeat_der is not None:
198
+ data["heartbeat_der"] = self.heartbeat_der
199
+ if self.heartbeat_intermediate_der is not None:
200
+ data["heartbeat_intermediate_der"] = self.heartbeat_intermediate_der
201
+ if self.heartbeat_root_fingerprint is not None:
202
+ data["heartbeat_root_fingerprint"] = self.heartbeat_root_fingerprint
203
+ return data
204
+
205
+
206
+ class LukuArchive:
207
+ def __init__(
208
+ self,
209
+ manifest: LukuManifest,
210
+ manifest_sig: str,
211
+ blocks: list[LukuBlock],
212
+ attachments: dict[str, bytes],
213
+ manifest_raw: str,
214
+ blocks_raw: str,
215
+ ) -> None:
216
+ self.manifest = manifest
217
+ self.manifest_sig = manifest_sig
218
+ self.blocks = blocks
219
+ self.attachments = attachments
220
+ self._manifest_raw = manifest_raw
221
+ self._blocks_raw = blocks_raw
222
+
223
+ def add_attachment(self, content: bytes) -> str:
224
+ checksum = _sha256_hex(content)
225
+ self.attachments[checksum] = content
226
+ return checksum
227
+
228
+ def save_to_bytes(self) -> bytes:
229
+ current_blocks_raw = self._serialized_blocks()
230
+ buffer = io.BytesIO()
231
+ with zipfile.ZipFile(buffer, "w") as archive:
232
+ archive.writestr(
233
+ zipfile.ZipInfo("mimetype"),
234
+ LUKU_MIMETYPE.encode("utf-8"),
235
+ compress_type=zipfile.ZIP_STORED,
236
+ )
237
+ archive.writestr("blocks.jsonl", current_blocks_raw.encode("utf-8"), compress_type=zipfile.ZIP_DEFLATED)
238
+ archive.writestr("manifest.json", self._manifest_raw.encode("utf-8"), compress_type=zipfile.ZIP_DEFLATED)
239
+ archive.writestr("manifest.sig", self.manifest_sig.encode("utf-8"), compress_type=zipfile.ZIP_DEFLATED)
240
+ for checksum, content in self.attachments.items():
241
+ dir1 = checksum[:2] or "00"
242
+ dir2 = checksum[2:4] or "00"
243
+ archive.writestr(f"attachments/{dir1}/{dir2}/{checksum}", content, compress_type=zipfile.ZIP_DEFLATED)
244
+ return buffer.getvalue()
245
+
246
+ def append(
247
+ self,
248
+ records: list[dict[str, Any]],
249
+ device: LukuDeviceIdentity,
250
+ signer: LukuSigner,
251
+ ) -> None:
252
+ block = LukuFile.build_block_from_records(
253
+ block_id=len(self.blocks),
254
+ timestamp_utc=int(time.time()),
255
+ previous_block_hash=self.blocks[-1].block_hash if self.blocks else None,
256
+ default_device=device,
257
+ batch=records,
258
+ common_certs=None,
259
+ )
260
+ self.blocks.append(block)
261
+ self._refresh_manifest_signature(signer)
262
+
263
+ def merge(self, other: "LukuArchive", signer: LukuSigner) -> None:
264
+ for incoming in other.blocks:
265
+ normalized = copy.deepcopy(incoming)
266
+ normalized.block_id = len(self.blocks)
267
+ normalized.previous_block_hash = self.blocks[-1].block_hash if self.blocks else None
268
+ fields = _recompute_block_fields(normalized)
269
+ normalized.batch_hash = fields["batch_hash"]
270
+ normalized.block_canonical_string = fields["block_canonical_string"]
271
+ normalized.block_hash = fields["block_hash"]
272
+ self.blocks.append(normalized)
273
+ self.attachments.update(other.attachments)
274
+ self._refresh_manifest_signature(signer)
275
+
276
+ def verify(self, options: LukuVerifyOptions | None = None) -> list[VerificationIssue]:
277
+ options = options or LukuVerifyOptions()
278
+ issues: list[VerificationIssue] = []
279
+
280
+ exporter_public_key = self.manifest.extra.get("exporter_public_key")
281
+ if not self.manifest_sig.strip():
282
+ issues.append(_issue("MANIFEST_SIGNATURE_MISSING", "The manifest.sig file is empty or missing.", Criticality.CRITICAL))
283
+ elif not exporter_public_key:
284
+ issues.append(_issue("EXPORTER_KEY_MISSING", "Archive does not publish an exporter_public_key; manifest/block signatures cannot be checked offline.", Criticality.WARNING))
285
+ elif not verify_detached_signature(str(exporter_public_key), self._manifest_raw.encode("utf-8"), self.manifest_sig):
286
+ issues.append(_issue("MANIFEST_SIGNATURE_INVALID", "The manifest signature does not verify against the exporter key.", Criticality.CRITICAL))
287
+
288
+ if _sha256_hex(self._blocks_raw.encode("utf-8")) != self.manifest.blocks_hash:
289
+ issues.append(_issue("BLOCKS_HASH_MISMATCH", "The blocks.jsonl file hash does not match the manifest.", Criticality.CRITICAL))
290
+
291
+ previous_block_hash: str | None = None
292
+ for index, block in enumerate(self.blocks):
293
+ if block.block_id != index:
294
+ issues.append(_issue("BLOCK_ID_MISMATCH", f"Block {index} has incorrect block_id {block.block_id}.", Criticality.CRITICAL))
295
+ if block.previous_block_hash != previous_block_hash:
296
+ issues.append(_issue("BLOCK_CHAIN_BROKEN", f"Block {index} previous hash link is broken.", Criticality.CRITICAL))
297
+ fields = _recompute_block_fields(block)
298
+ if block.batch_hash != fields["batch_hash"]:
299
+ issues.append(_issue("BLOCK_BATCH_HASH_INVALID", f"Block {index} batch_hash does not match ordered record signatures.", Criticality.CRITICAL))
300
+ if block.block_canonical_string != fields["block_canonical_string"]:
301
+ issues.append(_issue("BLOCK_CANONICAL_MISMATCH", f"Block {index} canonical string does not match recomputed content.", Criticality.CRITICAL))
302
+ if not block.block_hash:
303
+ issues.append(_issue("BLOCK_HASH_MISSING", f"Block {index} is missing block_hash.", Criticality.CRITICAL))
304
+ elif block.block_hash != fields["block_hash"]:
305
+ issues.append(_issue("BLOCK_HASH_INVALID", f"Block {index} block_hash does not match canonical content.", Criticality.CRITICAL))
306
+ previous_block_hash = block.block_hash
307
+
308
+ record_ids: set[str] = set()
309
+ for block in self.blocks:
310
+ for record in block.batch:
311
+ for key in ["scan_id", "event_id", "attachment_id", "custody_id", "location_id"]:
312
+ value = record.get(key)
313
+ if isinstance(value, str) and value:
314
+ record_ids.add(value)
315
+
316
+ last_counters: dict[str, int] = {}
317
+ last_times: dict[str, int] = {}
318
+ seen_devices: set[str] = set()
319
+
320
+ for block in self.blocks:
321
+ last_signatures: dict[str, str] = {}
322
+ block_dac_chain = "".join(
323
+ entry
324
+ for entry in [
325
+ pem_from_der_string(block.attestation_dac_der),
326
+ pem_from_der_string(block.attestation_manufacturer_der),
327
+ pem_from_der_string(block.attestation_intermediate_der),
328
+ ]
329
+ if entry
330
+ )
331
+
332
+ for record in block.batch:
333
+ record_type = str(record.get("type", "unknown"))
334
+ is_aux = record_type in {"attachment", "location", "custody"}
335
+ is_compat_attachment = bool(record.get("_compat_nested_attachment"))
336
+ payload = record.get("payload") if isinstance(record.get("payload"), dict) else {}
337
+ device_id = str(record.get("device_id") or block.device.device_id)
338
+ public_key = str(record.get("public_key") or block.device.public_key)
339
+ signature = str(record.get("signature", ""))
340
+ previous_signature = str(record.get("previous_signature", ""))
341
+ canonical_string = str(record.get("canonical_string", ""))
342
+ timestamp = _uint64(payload.get("timestamp_utc")) or _uint64(record.get("timestamp_utc"))
343
+ counter = _uint64(payload.get("ctr"))
344
+ genesis_hash = str(payload.get("genesis_hash", ""))
345
+
346
+ if not is_aux and device_id not in seen_devices:
347
+ seen_devices.add(device_id)
348
+ if counter == 0 and genesis_hash and previous_signature != genesis_hash:
349
+ issues.append(_issue("GENESIS_HASH_MISMATCH", f"Genesis record (ctr=0) for device {device_id} has previous_signature that does not match genesis_hash.", Criticality.CRITICAL))
350
+
351
+ if not is_aux:
352
+ if device_id in last_signatures and previous_signature != last_signatures[device_id]:
353
+ issues.append(_issue("RECORD_CHAIN_BROKEN", f"Record chain broken for device {device_id} at record type {record_type}.", Criticality.CRITICAL))
354
+ if device_id in last_counters and counter is not None and counter <= last_counters[device_id]:
355
+ issues.append(_issue("COUNTER_REGRESSION", f"Counter regression detected for device {device_id} ({last_counters[device_id]} -> {counter}).", Criticality.CRITICAL))
356
+ if device_id in last_times and timestamp is not None and timestamp < last_times[device_id]:
357
+ issues.append(_issue("TIME_REGRESSION", f"Time travel detected for device {device_id} ({last_times[device_id]} -> {timestamp}).", Criticality.CRITICAL))
358
+
359
+ if not options.allow_untrusted_roots:
360
+ identity = record.get("identity") if isinstance(record.get("identity"), dict) else {}
361
+ attestation_chain = block_dac_chain
362
+ if identity.get("dac_der"):
363
+ attestation_chain = "".join(
364
+ entry
365
+ for entry in [
366
+ pem_from_der_string(identity.get("dac_der")),
367
+ pem_from_der_string(identity.get("attestation_manufacturer_der")),
368
+ pem_from_der_string(identity.get("attestation_intermediate_der")),
369
+ ]
370
+ if entry
371
+ )
372
+ attestation_sig = str(identity.get("signature", ""))
373
+ if not attestation_chain:
374
+ issues.append(_issue("ATTESTATION_CHAIN_MISSING", f"Missing DAC attestation chain for device {device_id}.", Criticality.WARNING))
375
+ elif not is_aux or attestation_sig:
376
+ result = verify_device_attestation(
377
+ DeviceAttestationInputs(
378
+ id=device_id,
379
+ key=public_key,
380
+ attestation_sig=attestation_sig,
381
+ certificate_chain=attestation_chain,
382
+ created=None if options.skip_certificate_temporal_checks else timestamp,
383
+ trust_profile=options.trust_profile,
384
+ )
385
+ )
386
+ if not result.ok:
387
+ issues.append(_issue("ATTESTATION_FAILED", f"Device {device_id} failed DAC attestation: {result.reason}", Criticality.CRITICAL))
388
+
389
+ if not canonical_string:
390
+ issues.append(_issue("RECORD_CANONICAL_MISSING", f"Record type {record_type} on device {device_id} does not include a canonical_string.", Criticality.WARNING if is_compat_attachment else Criticality.CRITICAL))
391
+ elif not signature:
392
+ issues.append(_issue("RECORD_SIGNATURE_MISSING", f"Record type {record_type} on device {device_id} is missing a signature.", Criticality.WARNING if is_compat_attachment else Criticality.CRITICAL))
393
+ elif not verify_detached_signature(public_key, canonical_string.encode("utf-8"), signature):
394
+ issues.append(_issue("RECORD_SIGNATURE_INVALID", f"Invalid signature for record type {record_type} on device {device_id}.", Criticality.CRITICAL))
395
+
396
+ if not is_aux and signature:
397
+ last_signatures[device_id] = signature
398
+ if not is_aux and counter is not None:
399
+ last_counters[device_id] = counter
400
+ if not is_aux and timestamp is not None:
401
+ last_times[device_id] = timestamp
402
+
403
+ parent_record_id = record.get("parent_record_id")
404
+ if is_aux and isinstance(parent_record_id, str) and parent_record_id and parent_record_id not in record_ids:
405
+ issues.append(_issue("PARENT_RECORD_MISSING", f"Record type {record_type} references missing parent {parent_record_id}.", Criticality.CRITICAL))
406
+
407
+ if record_type == "attachment":
408
+ checksum = record.get("checksum")
409
+ if isinstance(checksum, str) and checksum:
410
+ content = self.attachments.get(checksum)
411
+ if content is None:
412
+ issues.append(_issue("ATTACHMENT_MISSING", f"Attachment with hash {checksum} is missing from archive.", Criticality.CRITICAL))
413
+ elif _sha256_hex(content) != checksum:
414
+ issues.append(_issue("ATTACHMENT_CORRUPT", f"Attachment with hash {checksum} is corrupt (actual hash {_sha256_hex(content)}).", Criticality.CRITICAL))
415
+
416
+ return issues
417
+
418
+ def _refresh_manifest_signature(self, signer: LukuSigner) -> None:
419
+ timestamp = int(time.time())
420
+ self._blocks_raw = self._serialized_blocks()
421
+ self.manifest.blocks_hash = _sha256_hex(self._blocks_raw.encode("utf-8"))
422
+ self.manifest.created_at_utc = timestamp
423
+ self._manifest_raw = _serialize_json(self.manifest.json_object(), pretty=True)
424
+ self.manifest_sig = sign_detached(signer.private_key_pem, self._manifest_raw.encode("utf-8"))
425
+
426
+ def _serialized_blocks(self) -> str:
427
+ return "".join(f"{_serialize_json(block.json_object(), pretty=False)}\n" for block in self.blocks)
428
+
429
+
430
+ class LukuFile:
431
+ @staticmethod
432
+ def open(path: str | Path) -> LukuArchive:
433
+ return LukuFile.open_bytes(Path(path).read_bytes())
434
+
435
+ @staticmethod
436
+ def open_bytes(data: bytes) -> LukuArchive:
437
+ try:
438
+ archive = zipfile.ZipFile(io.BytesIO(data), "r")
439
+ except Exception as exc:
440
+ raise ValueError(f"Failed to open .luku archive: {exc}") from exc
441
+
442
+ try:
443
+ mimetype = archive.read("mimetype").decode("utf-8").strip()
444
+ except KeyError as exc:
445
+ raise ValueError("mimetype file missing") from exc
446
+ if mimetype != LUKU_MIMETYPE:
447
+ raise ValueError(f"Invalid mimetype: expected {LUKU_MIMETYPE}")
448
+
449
+ try:
450
+ manifest_raw = archive.read("manifest.json").decode("utf-8")
451
+ except KeyError as exc:
452
+ raise ValueError("manifest.json missing from archive") from exc
453
+ manifest = LukuManifest.from_json(json.loads(manifest_raw))
454
+
455
+ try:
456
+ blocks_raw = archive.read("blocks.jsonl").decode("utf-8")
457
+ except KeyError as exc:
458
+ raise ValueError("blocks.jsonl missing from archive") from exc
459
+ blocks = [
460
+ LukuBlock.from_json(json.loads(line))
461
+ for line in blocks_raw.splitlines()
462
+ if line.strip()
463
+ ]
464
+
465
+ try:
466
+ manifest_sig = archive.read("manifest.sig").decode("utf-8")
467
+ except KeyError:
468
+ manifest_sig = ""
469
+
470
+ attachments: dict[str, bytes] = {}
471
+ for name in archive.namelist():
472
+ if name.startswith("attachments/") and not name.endswith("/"):
473
+ attachments[Path(name).name] = archive.read(name)
474
+
475
+ return LukuArchive(
476
+ manifest=manifest,
477
+ manifest_sig=manifest_sig,
478
+ blocks=blocks,
479
+ attachments=attachments,
480
+ manifest_raw=manifest_raw,
481
+ blocks_raw=blocks_raw,
482
+ )
483
+
484
+ @staticmethod
485
+ def parse(path: str | Path) -> LukuParseResult:
486
+ return LukuFile.parse_bytes(Path(path).read_bytes())
487
+
488
+ @staticmethod
489
+ def parse_bytes(data: bytes) -> LukuParseResult:
490
+ archive = LukuFile.open_bytes(data)
491
+ issues = archive.verify()
492
+ verified = not any(issue.criticality == Criticality.CRITICAL for issue in issues)
493
+ items = [
494
+ LukuItemResult(type=str(record.get("type", "unknown")), verified=verified, payload=copy.deepcopy(record))
495
+ for block in archive.blocks
496
+ for record in block.batch
497
+ ]
498
+ return LukuParseResult(verified=verified, items=items, issues=issues)
499
+
500
+ @staticmethod
501
+ def export(
502
+ records: list[dict[str, Any]],
503
+ device: LukuDeviceIdentity,
504
+ attachments: dict[str, bytes],
505
+ signer: LukuSigner,
506
+ ) -> LukuArchive:
507
+ return LukuFile.export_with_identity(records, device, attachments, signer)
508
+
509
+ @staticmethod
510
+ def export_with_identity(
511
+ records: list[dict[str, Any]],
512
+ device: LukuDeviceIdentity,
513
+ attachments: dict[str, bytes],
514
+ signer: LukuSigner,
515
+ ) -> LukuArchive:
516
+ blocks: list[LukuBlock] = []
517
+ previous_block_hash: str | None = None
518
+ for index in range(0, len(records), 1000):
519
+ chunk = records[index:index + 1000]
520
+ timestamp = next((_record_timestamp(record) for record in chunk if _record_timestamp(record) is not None), 0) or 0
521
+ block = LukuFile.build_block_from_records(
522
+ block_id=len(blocks),
523
+ timestamp_utc=timestamp,
524
+ previous_block_hash=previous_block_hash,
525
+ default_device=device,
526
+ batch=chunk,
527
+ common_certs=None,
528
+ )
529
+ previous_block_hash = block.block_hash
530
+ blocks.append(block)
531
+ return LukuFile.export_blocks_with_manifest(
532
+ blocks=blocks,
533
+ attachments=attachments,
534
+ description=f"Exported {len(records)} records",
535
+ manifest_extra={},
536
+ signer=signer,
537
+ )
538
+
539
+ @staticmethod
540
+ def export_blocks_with_manifest(
541
+ blocks: list[LukuBlock],
542
+ attachments: dict[str, bytes],
543
+ description: str,
544
+ manifest_extra: dict[str, Any],
545
+ signer: LukuSigner,
546
+ ) -> LukuArchive:
547
+ timestamp = int(time.time())
548
+ normalized_blocks: list[LukuBlock] = []
549
+ previous_block_hash: str | None = None
550
+ for index, block in enumerate(blocks):
551
+ normalized = copy.deepcopy(block)
552
+ normalized.block_id = index
553
+ normalized.previous_block_hash = previous_block_hash
554
+ if normalized.timestamp_utc == 0:
555
+ normalized.timestamp_utc = timestamp
556
+ fields = _recompute_block_fields(normalized)
557
+ normalized.batch_hash = fields["batch_hash"]
558
+ normalized.block_canonical_string = fields["block_canonical_string"]
559
+ normalized.block_hash = fields["block_hash"]
560
+ previous_block_hash = normalized.block_hash
561
+ normalized_blocks.append(normalized)
562
+
563
+ blocks_raw = "".join(f"{_serialize_json(block.json_object(), pretty=False)}\n" for block in normalized_blocks)
564
+ extra = dict(manifest_extra)
565
+ extra.setdefault("exporter_public_key", signer.public_key_base64)
566
+ extra.setdefault("exporter_alg", "ED25519")
567
+ manifest = LukuManifest(
568
+ type="LukuArchive",
569
+ version="1.0",
570
+ created_at_utc=timestamp,
571
+ description=description,
572
+ blocks_hash=_sha256_hex(blocks_raw.encode("utf-8")),
573
+ extra=extra,
574
+ )
575
+ manifest_raw = _serialize_json(manifest.json_object(), pretty=True)
576
+ manifest_sig = sign_detached(signer.private_key_pem, manifest_raw.encode("utf-8"))
577
+ return LukuArchive(
578
+ manifest=manifest,
579
+ manifest_sig=manifest_sig,
580
+ blocks=normalized_blocks,
581
+ attachments=dict(attachments),
582
+ manifest_raw=manifest_raw,
583
+ blocks_raw=blocks_raw,
584
+ )
585
+
586
+ @staticmethod
587
+ def build_block_from_records(
588
+ block_id: int,
589
+ timestamp_utc: int,
590
+ previous_block_hash: str | None,
591
+ default_device: LukuDeviceIdentity,
592
+ batch: list[dict[str, Any]],
593
+ common_certs: dict[str, str] | None,
594
+ ) -> LukuBlock:
595
+ normalized_batch = copy.deepcopy(batch)
596
+ record_device = next(
597
+ (record.get("device") for record in normalized_batch if isinstance(record.get("device"), dict)),
598
+ None,
599
+ ) or {}
600
+ device = LukuDeviceIdentity(
601
+ device_id=str(record_device.get("device_id", default_device.device_id)),
602
+ public_key=str(record_device.get("public_key", default_device.public_key)),
603
+ )
604
+
605
+ def common_identity_value(key: str) -> str | None:
606
+ values = [
607
+ identity[key]
608
+ for identity in (
609
+ record.get("identity") if isinstance(record.get("identity"), dict) else {}
610
+ for record in normalized_batch
611
+ )
612
+ if isinstance(identity.get(key), str)
613
+ ]
614
+ return values[0] if values and all(value == values[0] for value in values) else None
615
+
616
+ block = LukuBlock(
617
+ block_id=block_id,
618
+ timestamp_utc=timestamp_utc,
619
+ previous_block_hash=previous_block_hash,
620
+ device=device,
621
+ attestation_dac_der=common_identity_value("dac_der") or (common_certs or {}).get("dac_der"),
622
+ attestation_manufacturer_der=common_identity_value("attestation_manufacturer_der") or (common_certs or {}).get("attestation_manufacturer_der"),
623
+ attestation_intermediate_der=common_identity_value("attestation_intermediate_der") or (common_certs or {}).get("attestation_intermediate_der"),
624
+ attestation_root_fingerprint=common_identity_value("attestation_root_fingerprint") or (common_certs or {}).get("attestation_root_fingerprint"),
625
+ heartbeat_slac_der=common_identity_value("slac_der") or (common_certs or {}).get("slac_der"),
626
+ heartbeat_der=common_identity_value("heartbeat_der") or (common_certs or {}).get("heartbeat_der"),
627
+ heartbeat_intermediate_der=common_identity_value("heartbeat_intermediate_der") or (common_certs or {}).get("heartbeat_intermediate_der"),
628
+ heartbeat_root_fingerprint=common_identity_value("heartbeat_root_fingerprint") or (common_certs or {}).get("heartbeat_root_fingerprint"),
629
+ batch=normalized_batch,
630
+ )
631
+ fields = _recompute_block_fields(block)
632
+ block.batch_hash = fields["batch_hash"]
633
+ block.block_canonical_string = fields["block_canonical_string"]
634
+ block.block_hash = fields["block_hash"]
635
+ return block
636
+
637
+
638
+ def _recompute_block_fields(block: LukuBlock) -> dict[str, str]:
639
+ batch_hash = _sha256_hex(":".join(str(record.get("signature", "")) for record in block.batch).encode("utf-8"))
640
+ canonical = ":".join(
641
+ [
642
+ str(block.block_id),
643
+ str(block.timestamp_utc),
644
+ block.previous_block_hash or "",
645
+ block.device.device_id,
646
+ block.device.public_key,
647
+ block.attestation_root_fingerprint or "",
648
+ block.heartbeat_root_fingerprint or "",
649
+ batch_hash,
650
+ ]
651
+ )
652
+ return {
653
+ "batch_hash": batch_hash,
654
+ "block_canonical_string": canonical,
655
+ "block_hash": _sha256_hex(canonical.encode("utf-8")),
656
+ }
657
+
658
+
659
+ def _serialize_json(value: dict[str, Any], pretty: bool) -> str:
660
+ if pretty:
661
+ return json.dumps(value, indent=2, sort_keys=True)
662
+ return json.dumps(value, sort_keys=True, separators=(",", ":"))
663
+
664
+
665
+ def _sha256_hex(value: bytes) -> str:
666
+ return hashlib.sha256(value).hexdigest()
667
+
668
+
669
+ def _issue(code: str, message: str, criticality: Criticality) -> VerificationIssue:
670
+ return VerificationIssue(code=code, message=message, criticality=criticality)
671
+
672
+
673
+ def _uint64(value: Any) -> int | None:
674
+ if isinstance(value, bool):
675
+ return None
676
+ if isinstance(value, int):
677
+ return value if value >= 0 else None
678
+ if isinstance(value, float):
679
+ return int(value) if value >= 0 and value.is_integer() else None
680
+ return None
681
+
682
+
683
+ def _record_timestamp(record: dict[str, Any]) -> int | None:
684
+ payload = record.get("payload") if isinstance(record.get("payload"), dict) else {}
685
+ return _uint64(payload.get("timestamp_utc")) or _uint64(record.get("timestamp_utc"))
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.4
2
+ Name: lukuid-sdk
3
+ Version: 1.0.0
4
+ Summary: Python .luku archive support for the LukuID SDK
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/lukuid/sdk
7
+ Project-URL: Repository, https://github.com/lukuid/sdk
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+
11
+ # LukuID SDK for Python
12
+
13
+ Python helpers for opening, exporting, and verifying `.luku` forensic evidence archives.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ python -m pip install lukuid-sdk
19
+ ```
20
+
21
+ Requires Python 3.11 or newer.
22
+
23
+ ## Quick start
24
+
25
+ ```python
26
+ from lukuid_sdk import LukuFile
27
+
28
+ result = LukuFile.parse("identity.luku")
29
+ print(result.verified)
30
+ ```
31
+
32
+ For fuller documentation, see [docs/python.md](../../docs/python.md).
@@ -0,0 +1,8 @@
1
+ lukuid_sdk/__init__.py,sha256=ViSlTo1NX064EnxKwgp_K6EhhSVxrn6Xv0abtQCgO7o,553
2
+ lukuid_sdk/attestation.py,sha256=ETBrBFAp83Hm4xPWuG_S8q5frDDw57QZ8fbL1APLErM,9964
3
+ lukuid_sdk/luku.py,sha256=uLYhKZGSNLd4H8JGLvXIYI3NrFpfefw0yj-4TpzOmrs,30759
4
+ tests/test_luku.py,sha256=cp3Tztz-ysXfNKuaeSLLlkQPmUStkriWxfl4fzu5i6Y,15385
5
+ lukuid_sdk-1.0.0.dist-info/METADATA,sha256=vmqSkgECq1pJ1LgHJtjfxsjPh-tDMO2r3WsXs4IMk9U,718
6
+ lukuid_sdk-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
7
+ lukuid_sdk-1.0.0.dist-info/top_level.txt,sha256=4aMfM2qWwQGCibCjxnMPNn1AdnF-6VxUg919PILRudg,17
8
+ lukuid_sdk-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ lukuid_sdk
2
+ tests
tests/test_luku.py ADDED
@@ -0,0 +1,279 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import io
6
+ import unittest
7
+ import zipfile
8
+ from pathlib import Path
9
+
10
+ from lukuid_sdk import (
11
+ Criticality,
12
+ LUKU_MIMETYPE,
13
+ LukuDeviceIdentity,
14
+ LukuFile,
15
+ LukuSigner,
16
+ LukuVerifyOptions,
17
+ )
18
+
19
+
20
+ class LukuArchiveTests(unittest.TestCase):
21
+ @staticmethod
22
+ def create_test_signer() -> LukuSigner:
23
+ return LukuSigner.generate()
24
+
25
+ @staticmethod
26
+ def sign_canonical(signer: LukuSigner, canonical: str) -> str:
27
+ from lukuid_sdk.attestation import sign_detached
28
+
29
+ return sign_detached(signer.private_key_pem, canonical.encode("utf-8"))
30
+
31
+ @staticmethod
32
+ def build_test_options() -> LukuVerifyOptions:
33
+ return LukuVerifyOptions(
34
+ allow_untrusted_roots=True,
35
+ skip_certificate_temporal_checks=True,
36
+ trusted_external_fingerprints=[],
37
+ trust_profile="dev",
38
+ )
39
+
40
+ @staticmethod
41
+ def sample_path(name: str) -> Path:
42
+ start = Path(__file__).resolve()
43
+ for root in start.parents:
44
+ for version in ("1.0.0", "1.0"):
45
+ candidate = root / "samples" / "dotluku" / "dev" / version / name
46
+ if candidate.exists():
47
+ return candidate
48
+ raise FileNotFoundError(f"Missing sample archive {name} while searching ancestors of {start}")
49
+
50
+ def create_valid_export(self, device_id: str):
51
+ signer = self.create_test_signer()
52
+ identity = LukuDeviceIdentity(device_id=device_id, public_key=signer.public_key_base64)
53
+
54
+ sig1 = self.sign_canonical(signer, "can1")
55
+ sig2 = self.sign_canonical(signer, "can2")
56
+ sig3 = self.sign_canonical(signer, "can3")
57
+
58
+ records = [
59
+ {
60
+ "type": "scan",
61
+ "signature": sig1,
62
+ "previous_signature": "genesis_fake",
63
+ "canonical_string": "can1",
64
+ "payload": {"ctr": 1, "timestamp_utc": 1000, "genesis_hash": "genesis_fake"},
65
+ },
66
+ {
67
+ "type": "scan",
68
+ "signature": sig2,
69
+ "previous_signature": sig1,
70
+ "canonical_string": "can2",
71
+ "payload": {"ctr": 2, "timestamp_utc": 1005, "genesis_hash": "genesis_fake"},
72
+ },
73
+ {
74
+ "type": "scan",
75
+ "signature": sig3,
76
+ "previous_signature": sig2,
77
+ "canonical_string": "can3",
78
+ "payload": {"ctr": 3, "timestamp_utc": 1010, "genesis_hash": "genesis_fake"},
79
+ },
80
+ ]
81
+
82
+ exported = LukuFile.export_with_identity(records, identity, {}, signer)
83
+ reopened = LukuFile.open_bytes(exported.save_to_bytes())
84
+ return reopened, signer
85
+
86
+ @staticmethod
87
+ def has_issue(issues, *codes) -> bool:
88
+ return any(issue.code in codes for issue in issues)
89
+
90
+ def test_exports_and_reopens_archives(self):
91
+ signer = self.create_test_signer()
92
+ identity = LukuDeviceIdentity(device_id="LUK-TEST", public_key=signer.public_key_base64)
93
+ exported = LukuFile.export(
94
+ [
95
+ {
96
+ "type": "scan",
97
+ "signature": self.sign_canonical(signer, "can1"),
98
+ "previous_signature": "genesis_fake",
99
+ "canonical_string": "can1",
100
+ "payload": {"ctr": 1, "timestamp_utc": 1000},
101
+ }
102
+ ],
103
+ identity,
104
+ {},
105
+ signer,
106
+ )
107
+ reopened = LukuFile.open_bytes(exported.save_to_bytes())
108
+ self.assertEqual(reopened.manifest.version, "1.0")
109
+ self.assertEqual(len(reopened.blocks), 1)
110
+ self.assertEqual(len(reopened.blocks[0].batch), 1)
111
+
112
+ def test_builds_block_fallback_cert_fields(self):
113
+ identity = LukuDeviceIdentity(device_id="LUK-TEST", public_key=bytes(32).hex())
114
+ block = LukuFile.build_block_from_records(
115
+ block_id=0,
116
+ timestamp_utc=1000,
117
+ previous_block_hash=None,
118
+ default_device=identity,
119
+ batch=[{"type": "scan", "signature": "sig1", "canonical_string": "can1", "payload": {"ctr": 1, "timestamp_utc": 1000}}],
120
+ common_certs={"dac_der": "mock_dac_der", "attestation_root_fingerprint": "mock_fingerprint"},
121
+ )
122
+ self.assertEqual(block.attestation_dac_der, "mock_dac_der")
123
+ self.assertEqual(block.attestation_root_fingerprint, "mock_fingerprint")
124
+
125
+ def test_verifies_a_valid_archive(self):
126
+ archive, _ = self.create_valid_export("LUK-VALID")
127
+ issues = archive.verify(self.build_test_options())
128
+ self.assertFalse(any(issue.criticality == Criticality.CRITICAL for issue in issues))
129
+
130
+ def test_detects_record_deletion(self):
131
+ archive, _ = self.create_valid_export("LUK-DEL")
132
+ archive.blocks[0].batch.pop(1)
133
+ self.assertTrue(self.has_issue(archive.verify(self.build_test_options()), "RECORD_CHAIN_BROKEN"))
134
+
135
+ def test_detects_record_injection(self):
136
+ archive, _ = self.create_valid_export("LUK-INJ")
137
+ archive.blocks[0].batch.insert(1, {"type": "scan", "signature": "fake_sig", "previous_signature": "doesnt_matter", "payload": {"ctr": 2, "timestamp_utc": 1002}})
138
+ self.assertTrue(self.has_issue(archive.verify(self.build_test_options()), "RECORD_CHAIN_BROKEN", "RECORD_SIGNATURE_INVALID"))
139
+
140
+ def test_detects_time_regression(self):
141
+ archive, _ = self.create_valid_export("LUK-TIME")
142
+ archive.blocks[0].batch[1]["payload"]["timestamp_utc"] = 999
143
+ self.assertTrue(self.has_issue(archive.verify(self.build_test_options()), "TIME_REGRESSION"))
144
+
145
+ def test_detects_counter_regression(self):
146
+ archive, _ = self.create_valid_export("LUK-CTR")
147
+ archive.blocks[0].batch[1]["payload"]["ctr"] = 1
148
+ self.assertTrue(self.has_issue(archive.verify(self.build_test_options()), "COUNTER_REGRESSION"))
149
+
150
+ def test_detects_export_tampering(self):
151
+ archive, _ = self.create_valid_export("LUK-EXP")
152
+ archive.blocks[0].block_id = 999
153
+ tampered = LukuFile.open_bytes(archive.save_to_bytes())
154
+ self.assertTrue(self.has_issue(tampered.verify(self.build_test_options()), "BLOCKS_HASH_MISMATCH"))
155
+
156
+ def test_detects_attachment_corruption(self):
157
+ archive, _ = self.create_valid_export("LUK-ATT")
158
+ checksum = archive.add_attachment(b"valid_data")
159
+ archive.blocks[0].batch.append({"type": "attachment", "checksum": checksum, "payload": {"ctr": 3}})
160
+ archive.attachments[checksum] = b"tampered_data"
161
+ self.assertTrue(self.has_issue(archive.verify(self.build_test_options()), "ATTACHMENT_CORRUPT"))
162
+
163
+ def test_keeps_attested_attachments_out_of_the_native_chain(self):
164
+ signer = self.create_test_signer()
165
+ device_id = "LUK-ATTEST"
166
+ attachment_bytes = b"desktop-added-attachment"
167
+ checksum = hashlib.sha256(attachment_bytes).hexdigest()
168
+ scan_sig = self.sign_canonical(signer, "attested-scan")
169
+ block = LukuFile.build_block_from_records(
170
+ block_id=0,
171
+ timestamp_utc=1003,
172
+ previous_block_hash=None,
173
+ default_device=LukuDeviceIdentity(device_id=device_id, public_key=signer.public_key_base64),
174
+ batch=[
175
+ {"type": "scan", "scan_id": "SCAN-ATTEST-1", "device_id": device_id, "public_key": signer.public_key_base64, "signature": scan_sig, "previous_signature": "genesis_fake", "canonical_string": "attested-scan", "payload": {"ctr": 1, "timestamp_utc": 1000, "genesis_hash": "genesis_fake"}},
176
+ {"type": "attachment", "attachment_id": "ATT-ATTEST-1", "parent_record_id": "SCAN-ATTEST-1", "device_id": device_id, "public_key": signer.public_key_base64, "signature": self.sign_canonical(signer, "attested-attachment"), "parent_signature": scan_sig, "canonical_string": "attested-attachment", "timestamp_utc": 1001, "checksum": checksum, "mime": "text/plain", "title": "Desktop Note"},
177
+ {"type": "environment", "event_id": "ENV-ATTEST-1", "device_id": device_id, "public_key": signer.public_key_base64, "signature": self.sign_canonical(signer, "attested-environment"), "previous_signature": scan_sig, "canonical_string": "attested-environment", "payload": {"ctr": 2, "timestamp_utc": 1002}},
178
+ ],
179
+ common_certs=None,
180
+ )
181
+ exported = LukuFile.export_blocks_with_manifest([block], {checksum: attachment_bytes}, "Attested attachment export", {}, signer)
182
+ reopened = LukuFile.open_bytes(exported.save_to_bytes())
183
+ issues = reopened.verify(self.build_test_options())
184
+ self.assertFalse(any(issue.criticality == Criticality.CRITICAL for issue in issues))
185
+ self.assertFalse(self.has_issue(issues, "RECORD_CHAIN_BROKEN"))
186
+
187
+ def test_keeps_attested_custody_records_out_of_the_native_chain(self):
188
+ signer = self.create_test_signer()
189
+ device_id = "LUK-CUSTODY"
190
+ scan_sig = self.sign_canonical(signer, "custody-scan")
191
+ block = LukuFile.build_block_from_records(
192
+ block_id=0,
193
+ timestamp_utc=1003,
194
+ previous_block_hash=None,
195
+ default_device=LukuDeviceIdentity(device_id=device_id, public_key=signer.public_key_base64),
196
+ batch=[
197
+ {"type": "scan", "scan_id": "SCAN-CUSTODY-1", "device_id": device_id, "public_key": signer.public_key_base64, "signature": scan_sig, "previous_signature": "genesis_fake", "canonical_string": "custody-scan", "payload": {"ctr": 1, "timestamp_utc": 1000, "genesis_hash": "genesis_fake"}},
198
+ {"type": "custody", "custody_id": "CUSTODY-1", "parent_record_id": "SCAN-CUSTODY-1", "device_id": device_id, "public_key": signer.public_key_base64, "signature": self.sign_canonical(signer, "custody-checkpoint"), "parent_signature": scan_sig, "canonical_string": "custody-checkpoint", "timestamp_utc": 1001, "payload": {"event": "handoff", "status": "received", "context_ref": "shipment-123"}},
199
+ {"type": "environment", "event_id": "ENV-CUSTODY-1", "device_id": device_id, "public_key": signer.public_key_base64, "signature": self.sign_canonical(signer, "custody-environment"), "previous_signature": scan_sig, "canonical_string": "custody-environment", "payload": {"ctr": 2, "timestamp_utc": 1002}},
200
+ ],
201
+ common_certs=None,
202
+ )
203
+ exported = LukuFile.export_blocks_with_manifest([block], {}, "Attested custody export", {}, signer)
204
+ reopened = LukuFile.open_bytes(exported.save_to_bytes())
205
+ issues = reopened.verify(self.build_test_options())
206
+ self.assertFalse(any(issue.criticality == Criticality.CRITICAL for issue in issues))
207
+ self.assertFalse(self.has_issue(issues, "RECORD_CHAIN_BROKEN"))
208
+
209
+ def test_fails_strict_attestation_when_the_chain_is_fake(self):
210
+ archive, _ = self.create_valid_export("LUK-STRICT")
211
+ archive.blocks[0].attestation_dac_der = b"fake_der_data".hex()
212
+ issues = archive.verify(LukuVerifyOptions(allow_untrusted_roots=False, skip_certificate_temporal_checks=True, trust_profile="dev"))
213
+ self.assertTrue(self.has_issue(issues, "ATTESTATION_FAILED", "ATTESTATION_CHAIN_MISSING"))
214
+
215
+ def test_rejects_structurally_invalid_archives(self):
216
+ with self.assertRaises(Exception):
217
+ LukuFile.open_bytes(b"just random garbage bytes")
218
+
219
+ wrong_mime = io.BytesIO()
220
+ with zipfile.ZipFile(wrong_mime, "w") as archive:
221
+ archive.writestr("mimetype", b"application/pdf", compress_type=zipfile.ZIP_STORED)
222
+ with self.assertRaisesRegex(Exception, "Invalid mimetype"):
223
+ LukuFile.open_bytes(wrong_mime.getvalue())
224
+
225
+ missing_manifest = io.BytesIO()
226
+ with zipfile.ZipFile(missing_manifest, "w") as archive:
227
+ archive.writestr("mimetype", LUKU_MIMETYPE.encode("utf-8"), compress_type=zipfile.ZIP_STORED)
228
+ with self.assertRaisesRegex(Exception, "manifest.json missing"):
229
+ LukuFile.open_bytes(missing_manifest.getvalue())
230
+
231
+ def test_mutates_real_sample_archives_in_memory(self):
232
+ sample_bytes = self.sample_path("first-passable-verification-sample.luku").read_bytes()
233
+ original = LukuFile.open_bytes(sample_bytes)
234
+ self.assertFalse(any(issue.criticality == Criticality.CRITICAL for issue in original.verify(self.build_test_options())))
235
+
236
+ invalid_signature = LukuFile.open_bytes(sample_bytes)
237
+ invalid_signature.blocks[0].batch[0]["signature"] = "not_base64_data!!!"
238
+ self.assertTrue(self.has_issue(invalid_signature.verify(self.build_test_options()), "RECORD_SIGNATURE_INVALID", "ATTESTATION_FAILED"))
239
+
240
+ mutated_canonical = LukuFile.open_bytes(sample_bytes)
241
+ mutated_canonical.blocks[0].batch[0]["canonical_string"] += "X"
242
+ self.assertTrue(self.has_issue(mutated_canonical.verify(self.build_test_options()), "RECORD_SIGNATURE_INVALID"))
243
+
244
+ if len(original.blocks[0].batch) > 1:
245
+ broken_chain = LukuFile.open_bytes(sample_bytes)
246
+ broken_chain.blocks[0].batch[1]["previous_signature"] = "broken_link"
247
+ self.assertTrue(self.has_issue(broken_chain.verify(self.build_test_options()), "RECORD_CHAIN_BROKEN"))
248
+
249
+ if len(original.blocks) > 1:
250
+ floating_anchor = LukuFile.open_bytes(sample_bytes)
251
+ floating_anchor.blocks[1].batch[0]["previous_signature"] = "floating_anchor_test"
252
+ self.assertFalse(self.has_issue(floating_anchor.verify(self.build_test_options()), "RECORD_CHAIN_BROKEN"))
253
+
254
+ if len(original.blocks[0].batch) > 1:
255
+ regressed_counter = LukuFile.open_bytes(sample_bytes)
256
+ regressed_counter.blocks[0].batch[1]["payload"]["ctr"] = 0
257
+ self.assertTrue(self.has_issue(regressed_counter.verify(self.build_test_options()), "COUNTER_REGRESSION"))
258
+
259
+ def test_verifies_the_shipped_sample_directory(self):
260
+ passable = LukuFile.open(self.sample_path("first-passable-verification-sample.luku"))
261
+ self.assertFalse(any(issue.criticality == Criticality.CRITICAL for issue in passable.verify(self.build_test_options())))
262
+
263
+ mismatch = LukuFile.open(self.sample_path("signature-mismatch.luku"))
264
+ mismatch_issues = mismatch.verify(LukuVerifyOptions(allow_untrusted_roots=False, skip_certificate_temporal_checks=True, trust_profile="dev"))
265
+ self.assertTrue(self.has_issue(mismatch_issues, "ATTESTATION_FAILED", "RECORD_SIGNATURE_INVALID", "ATTESTATION_CHAIN_MISSING"))
266
+
267
+ invalid_chain = LukuFile.open(self.sample_path("invalid-chain.luku"))
268
+ invalid_chain_issues = invalid_chain.verify(self.build_test_options())
269
+ self.assertTrue(self.has_issue(invalid_chain_issues, "RECORD_CHAIN_BROKEN", "BLOCKS_HASH_MISMATCH", "ATTESTATION_FAILED"))
270
+
271
+ dev_issues = passable.verify(LukuVerifyOptions(allow_untrusted_roots=False, skip_certificate_temporal_checks=True, trust_profile="dev"))
272
+ self.assertFalse(any(issue.code == "ATTESTATION_FAILED" and "trust profile" in issue.message for issue in dev_issues))
273
+
274
+ prod_issues = passable.verify(LukuVerifyOptions(allow_untrusted_roots=False, skip_certificate_temporal_checks=True, trust_profile="prod"))
275
+ self.assertTrue(any(issue.code == "ATTESTATION_FAILED" and "trust profile" in issue.message for issue in prod_issues))
276
+
277
+
278
+ if __name__ == "__main__":
279
+ unittest.main()