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085f660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e0de7c
 
 
 
 
 
 
 
085f660
 
5e0de7c
 
 
 
 
 
085f660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
"""Write a bounded, redacted export of one local detection receipt."""

from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import json
import math
import os
import re
import secrets
import stat
import sys
from pathlib import Path
from typing import Any

RECEIPT_SCHEMA = "lumi-eggcracker.detection-receipt.v2"
EXPORT_SCHEMA = "lumi-eggcracker.redacted-detection-receipt-export.v1"
EXPORT_SCHEMA_V2 = "lumi-eggcracker.redacted-detection-receipt-export.v2"
CLASSIFICATION_BASIS = "COMPLETE_QUALIFIED_LOCAL_PROFILE_MATCH_NOT_AI_IDENTITY"
DETECTOR_SCHEMA = "lumi-eggcracker.detectors.v3"
MAX_INPUT_BYTES = 1_048_576
MAX_OUTPUT_BYTES = 8_192
MAX_JSON_DEPTH = 64
MAX_MONOTONIC_NS = (1 << 63) - 1
_EVENT_ID = re.compile(r"[0-9a-f]{24}\Z")
_SHA256 = re.compile(r"[0-9a-f]{64}\Z")
_COMMIT = re.compile(r"[0-9a-f]{40}\Z")
_SEMVER = re.compile(
    r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)"
    r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
    r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?\Z"
)
_UTC_TIMESTAMP = re.compile(
    r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"
    r"(?:\.[0-9]{1,6})?Z\Z"
)
_PROFILE_TRIGGER = {
    "content.gguf-llama": "UNAPPROVED_AI_MATCH",
    "content.gguf-ollama": "UNAPPROVED_OLLAMA_GGUF",
    "content.safetensors-pytorch": "UNAPPROVED_SAFETENSORS_PYTORCH",
    "content.safetensors-vllm": "UNAPPROVED_VLLM_SAFETENSORS",
}
_CONTAINMENT_PRIMITIVE = "pidfd-stop+cgroup.kill"
_REPARSE_POINT = 0x400


class ExportError(Exception):
    """A deliberately non-specific input, validation, or filesystem failure."""


class OutputAlreadyExistsError(ExportError):
    """A validated export destination is already an ordinary regular file."""

    def __init__(self) -> None:
        super().__init__("OUTPUT_ALREADY_EXISTS")


def _fail() -> None:
    raise ExportError("receipt export could not be completed")


def _pairs_without_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    result: dict[str, Any] = {}
    for key, value in pairs:
        if key in result:
            _fail()
        result[key] = value
    return result


def _parse_int(token: str) -> int:
    if len(token) > 64:
        _fail()
    return int(token)


def _parse_float(token: str) -> float:
    if len(token) > 128:
        _fail()
    value = float(token)
    if not math.isfinite(value):
        _fail()
    mantissa = token.lower().split("e", maxsplit=1)[0]
    if value == 0.0 and any(character in "123456789" for character in mantissa):
        _fail()
    return value


def _reject_constant(_token: str) -> None:
    _fail()


def _check_depth(text: str) -> None:
    depth = 0
    quoted = False
    escaped = False
    for character in text:
        if quoted:
            if escaped:
                escaped = False
            elif character == "\\":
                escaped = True
            elif character == '"':
                quoted = False
        elif character == '"':
            quoted = True
        elif character in "[{":
            depth += 1
            if depth > MAX_JSON_DEPTH:
                _fail()
        elif character in "]}":
            depth -= 1
            if depth < 0:
                _fail()


def _decode_receipt(raw: bytes) -> dict[str, Any]:
    if len(raw) > MAX_INPUT_BYTES:
        _fail()
    try:
        text = raw.decode("utf-8")
        _check_depth(text)
        value = json.loads(
            text,
            object_pairs_hook=_pairs_without_duplicates,
            parse_int=_parse_int,
            parse_float=_parse_float,
            parse_constant=_reject_constant,
        )
    except (UnicodeDecodeError, json.JSONDecodeError, RecursionError, ValueError):
        _fail()
    if not isinstance(value, dict):
        _fail()
    return value


def _path_without_parent_links(value: str | os.PathLike[str]) -> Path:
    try:
        path = Path(value)
        if not path.is_absolute():
            if path.drive:
                _fail()
            path = Path.cwd() / path
        if not path.anchor or any(part == ".." for part in path.parts):
            _fail()
        if path.drive.startswith(("\\\\", "//")):
            _fail()
        return path
    except (OSError, TypeError, ValueError):
        _fail()


def _link_like(info: os.stat_result) -> bool:
    attributes = getattr(info, "st_file_attributes", 0)
    return stat.S_ISLNK(info.st_mode) or bool(attributes & _REPARSE_POINT)


def _check_directory_chain(path: Path) -> None:
    try:
        anchor = Path(path.anchor)
        info = os.lstat(anchor)
        if _link_like(info) or not stat.S_ISDIR(info.st_mode):
            _fail()
        for part in path.parts[len(anchor.parts) :]:
            anchor = anchor / part
            info = os.lstat(anchor)
            if _link_like(info) or not stat.S_ISDIR(info.st_mode):
                _fail()
    except (OSError, ValueError):
        _fail()


def _identity(info: os.stat_result) -> tuple[int, int]:
    return info.st_dev, info.st_ino


def _read_source(path_value: str | os.PathLike[str]) -> bytes:
    path = _path_without_parent_links(path_value)
    _check_directory_chain(path.parent)
    try:
        before = os.lstat(path)
        if _link_like(before) or not stat.S_ISREG(before.st_mode):
            _fail()
        if before.st_size > MAX_INPUT_BYTES:
            _fail()
        flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
        flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
        descriptor = os.open(path, flags)
    except (OSError, ValueError):
        _fail()

    try:
        opened = os.fstat(descriptor)
        if (
            not stat.S_ISREG(opened.st_mode)
            or _identity(opened) != _identity(before)
            or opened.st_size > MAX_INPUT_BYTES
        ):
            _fail()
        chunks: list[bytes] = []
        remaining = MAX_INPUT_BYTES + 1
        while remaining:
            chunk = os.read(descriptor, min(65_536, remaining))
            if not chunk:
                break
            chunks.append(chunk)
            remaining -= len(chunk)
        raw = b"".join(chunks)
        after = os.fstat(descriptor)
        if (
            len(raw) > MAX_INPUT_BYTES
            or len(raw) != opened.st_size
            or after.st_size != opened.st_size
            or after.st_mtime_ns != opened.st_mtime_ns
            or after.st_ctime_ns != opened.st_ctime_ns
        ):
            _fail()
        return raw
    except (OSError, ValueError):
        _fail()
    finally:
        try:
            os.close(descriptor)
        except OSError:
            pass


def _required_object(parent: dict[str, Any], key: str) -> dict[str, Any]:
    value = parent.get(key)
    if not isinstance(value, dict):
        _fail()
    return value


def _required_text(
    parent: dict[str, Any],
    key: str,
    pattern: re.Pattern[str],
    *,
    max_length: int = 128,
) -> str:
    value = parent.get(key)
    if not isinstance(value, str) or len(value) > max_length or not pattern.fullmatch(value):
        _fail()
    return value


def _required_monotonic_ns(parent: dict[str, Any], key: str) -> int:
    value = parent.get(key)
    if type(value) is not int or not 0 <= value <= MAX_MONOTONIC_NS:
        _fail()
    return value


def _required_ms(parent: dict[str, Any], key: str) -> int | float:
    value = parent.get(key)
    if type(value) not in (int, float) or not math.isfinite(value):
        _fail()
    if not 0 <= value <= MAX_MONOTONIC_NS / 1_000_000:
        _fail()
    return value


def _validate_timestamp(value: Any) -> str:
    if not isinstance(value, str) or not _UTC_TIMESTAMP.fullmatch(value):
        _fail()
    try:
        dt.datetime.fromisoformat(value)
    except ValueError:
        _fail()
    return value


def _project_receipt(receipt: dict[str, Any], expected_event_id: str) -> dict[str, Any]:
    if receipt.get("schema_version") != RECEIPT_SCHEMA:
        _fail()
    event_id = receipt.get("event_id")
    if not isinstance(event_id, str) or not _EVENT_ID.fullmatch(event_id):
        _fail()
    if event_id != expected_event_id:
        _fail()

    source_commit = _required_text(receipt, "source_commit", _COMMIT)
    version = _required_text(receipt, "version", _SEMVER, max_length=64)
    catalogue_sha256 = _required_text(receipt, "catalogue_sha256", _SHA256)
    receipt_written_utc = _validate_timestamp(receipt.get("receipt_written_utc"))

    detector = _required_object(receipt, "detector")
    profile = detector.get("profile")
    if not isinstance(profile, str) or profile not in _PROFILE_TRIGGER:
        _fail()
    detection_path = detector.get("detection_path")
    catalogue_schema = detector.get("catalogue_schema")
    if detection_path != "CONTENT" or catalogue_schema != DETECTOR_SCHEMA:
        _fail()

    trigger = _required_object(receipt, "trigger")
    trigger_kind = trigger.get("kind")
    if trigger_kind != _PROFILE_TRIGGER[profile]:
        _fail()

    result = receipt.get("result")
    if result not in ("TERMINATED", "CONTAINMENT_FAILED"):
        _fail()

    projection: dict[str, Any] = {
        "schema_version": RECEIPT_SCHEMA,
        "event_id": event_id,
        "source_commit": source_commit,
        "version": version,
        "catalogue_sha256": catalogue_sha256,
        "receipt_written_utc": receipt_written_utc,
        "detector": {
            "profile": profile,
            "detection_path": detection_path,
            "catalogue_schema": catalogue_schema,
        },
        "trigger": {"kind": trigger_kind},
        "recorded_result": result,
    }

    if result == "CONTAINMENT_FAILED":
        if "containment" in receipt or "error" not in receipt:
            _fail()
        return projection

    if "error" in receipt:
        _fail()
    containment = _required_object(receipt, "containment")
    if containment.get("primitive") != _CONTAINMENT_PRIMITIVE:
        _fail()
    root_populated = containment.get("root_populated")
    surviving_pids = containment.get("surviving_pids")
    if type(root_populated) is not int or root_populated != 0:
        _fail()
    if type(surviving_pids) is not list or surviving_pids:
        _fail()

    first_stop_ns = _required_monotonic_ns(containment, "first_stop_monotonic_ns")
    kill_started_ns = _required_monotonic_ns(containment, "kill_write_started_monotonic_ns")
    kill_completed_ns = _required_monotonic_ns(containment, "kill_write_completed_monotonic_ns")
    empty_ns = _required_monotonic_ns(containment, "empty_verified_monotonic_ns")
    observed_ns = _required_monotonic_ns(trigger, "observed_monotonic_ns")
    if not first_stop_ns <= kill_started_ns <= kill_completed_ns <= empty_ns:
        _fail()
    if observed_ns != first_stop_ns:
        _fail()

    qualification_to_first_stop_ms = _required_ms(
        containment, "qualification_to_first_stop_ms"
    )
    trigger_to_empty_ms = _required_ms(containment, "trigger_to_empty_ms")
    expected_trigger_to_empty_ms = (empty_ns - first_stop_ns) / 1_000_000
    if not math.isclose(
        trigger_to_empty_ms, expected_trigger_to_empty_ms, rel_tol=0.0, abs_tol=1e-9
    ):
        _fail()

    projection["recorded_empty_evidence"] = {
        "empty_verified_monotonic_ns": empty_ns,
        "first_stop_monotonic_ns": first_stop_ns,
        "kill_write_completed_monotonic_ns": kill_completed_ns,
        "kill_write_started_monotonic_ns": kill_started_ns,
        "primitive": _CONTAINMENT_PRIMITIVE,
        "qualification_to_first_stop_ms": qualification_to_first_stop_ms,
        "root_populated": 0,
        "surviving_pids": [],
        "trigger_to_empty_ms": trigger_to_empty_ms,
    }
    return projection


def _unlink_if_owned(path: Path, identity: tuple[int, int] | None) -> None:
    if identity is None:
        return
    try:
        current = os.lstat(path)
        if (
            not _link_like(current)
            and stat.S_ISREG(current.st_mode)
            and _identity(current) == identity
        ):
            os.unlink(path)
    except OSError:
        pass


def _write_new_output(path_value: str | os.PathLike[str], payload: bytes) -> None:
    output = _path_without_parent_links(path_value)
    _check_directory_chain(output.parent)
    try:
        existing = os.lstat(output)
    except FileNotFoundError:
        pass
    except (OSError, ValueError):
        _fail()
    else:
        if not _link_like(existing) and stat.S_ISREG(existing.st_mode):
            raise OutputAlreadyExistsError()
        _fail()

    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)
    flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
    temporary: Path | None = None
    identity: tuple[int, int] | None = None
    descriptor: int | None = None
    published = False
    complete = False
    try:
        for _ in range(8):
            candidate = output.parent / f".lumi-eggcracker-export-{secrets.token_hex(12)}.tmp"
            try:
                descriptor = os.open(candidate, flags, 0o666)
                temporary = candidate
                break
            except FileExistsError:
                continue
        if descriptor is None or temporary is None:
            _fail()

        created = os.fstat(descriptor)
        identity = _identity(created)
        if not stat.S_ISREG(created.st_mode):
            _fail()
        view = memoryview(payload)
        while view:
            written = os.write(descriptor, view)
            if written <= 0:
                _fail()
            view = view[written:]
        os.fsync(descriptor)
        os.close(descriptor)
        descriptor = None

        current_temporary = os.lstat(temporary)
        if (
            _link_like(current_temporary)
            or not stat.S_ISREG(current_temporary.st_mode)
            or _identity(current_temporary) != identity
        ):
            _fail()
        os.link(temporary, output, follow_symlinks=False)
        published = True
        current_output = os.lstat(output)
        if (
            _link_like(current_output)
            or not stat.S_ISREG(current_output.st_mode)
            or _identity(current_output) != identity
        ):
            _fail()
        complete = True
    except ExportError:
        raise
    except Exception:  # noqa: BLE001 - keep OS and path details out of diagnostics.
        _fail()
    finally:
        if descriptor is not None:
            try:
                os.close(descriptor)
            except OSError:
                pass
        if published and not complete:
            _unlink_if_owned(output, identity)
        if temporary is not None:
            _unlink_if_owned(temporary, identity)


def export_receipt(
    input_path: str | os.PathLike[str],
    expected_event_id: str,
    output_path: str | os.PathLike[str],
    *,
    export_version: int = 1,
) -> None:
    """Export one validated event; the output contains no unallowlisted fields."""
    if type(export_version) is not int or export_version not in (1, 2):
        _fail()
    if not isinstance(expected_event_id, str) or not _EVENT_ID.fullmatch(expected_event_id):
        _fail()
    raw = _read_source(input_path)
    receipt = _decode_receipt(raw)
    projected = _project_receipt(receipt, expected_event_id)
    if export_version == 2:
        projected["classification_basis"] = CLASSIFICATION_BASIS
    document = {
        "export_schema": EXPORT_SCHEMA_V2 if export_version == 2 else EXPORT_SCHEMA,
        "source_sha256": hashlib.sha256(raw).hexdigest(),
        "authentication": "NOT_AUTHENTICATED",
        "live_verification": "NOT_PERFORMED",
        "receipt": projected,
    }
    encoded = (
        json.dumps(document, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n"
    ).encode("utf-8")
    if len(encoded) > MAX_OUTPUT_BYTES:
        _fail()
    _write_new_output(output_path, encoded)


class _QuietArgumentParser(argparse.ArgumentParser):
    def error(self, _message: str) -> None:
        self.print_usage(sys.stderr)
        self.exit(2, f"{self.prog}: invalid command line\n")


def main(argv: list[str] | None = None) -> int:
    parser = _QuietArgumentParser(
        prog="export_detection_receipt.py",
        description="Write a bounded redacted export of one local detection receipt.",
    )
    parser.add_argument("--input", required=True, help="path to a detection receipt JSON file")
    parser.add_argument("--expected-event-id", required=True, help="24 lowercase hex characters")
    parser.add_argument("--output", required=True, help="new output JSON path")
    parser.add_argument(
        "--export-version",
        type=int,
        choices=(1, 2),
        default=1,
        metavar="VERSION",
        help="redacted export contract version (default: 1)",
    )
    args = parser.parse_args(argv)
    try:
        export_receipt(
            args.input,
            args.expected_event_id,
            args.output,
            export_version=args.export_version,
        )
    except OutputAlreadyExistsError:
        print(
            "export failed: OUTPUT_ALREADY_EXISTS; choose a new output filename",
            file=sys.stderr,
        )
        return 1
    except Exception:  # noqa: BLE001 - never echo untrusted input or OS error text.
        print("export failed: invalid receipt or filesystem path", file=sys.stderr)
        return 1
    print("detection receipt export complete")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())