File size: 9,264 Bytes
e459b62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81d568f
 
e459b62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81d568f
e459b62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read-only process identity for a future coordinated foundation release.



No manifest means unknown, not a repository-head fallback. The sealed build

manifest excludes itself and deployment metadata from its source inventory, so

neither its own digest nor an image digest is defined recursively. The complete

retained image is identified independently by the release controller.

"""
from __future__ import annotations

from dataclasses import dataclass
import hashlib
import importlib.metadata
import json
import os
from pathlib import Path, PurePosixPath
import platform
import re
import sys
import threading

from release_names import is_release_name


MANIFEST = "reader_runtime_manifest.json"
MARKER = "frontend/dist/assets/deploy_provenance.json"
MAX_JSON = 4 * 1024 * 1024
_PROBE_LOCK = threading.Lock()
_HEX64 = re.compile(r"[0-9a-f]{64}\Z")
_HEX40 = re.compile(r"[0-9a-f]{40}\Z")
_IMAGE = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*(?:/[a-z0-9]+(?:[._-][a-z0-9]+)*)*@sha256:[0-9a-f]{64}\Z")


def _require(condition):
    if not condition:
        raise ValueError("reader_identity_unproven")


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()


def digest(value):
    return hashlib.sha256(canonical(value)).hexdigest()


def _unique(pairs):
    result = {}
    for key, value in pairs:
        _require(key not in result)
        result[key] = value
    return result


def _json(raw):
    _require(len(raw) <= MAX_JSON)
    return json.loads(raw, object_pairs_hook=_unique)


def _regular(path):
    for parent in (path, *path.parents):
        _require(not parent.is_symlink() and not (hasattr(parent, "is_junction") and parent.is_junction()))
    _require(path.is_file())
    return path


def _sha(path):
    result, size = hashlib.sha256(), 0
    with _regular(path).open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            size += len(chunk)
            _require(size <= 512 * 1024 * 1024)
            result.update(chunk)
    return result.hexdigest(), size


def _read_metadata(path):
    with _regular(path).open("rb") as stream:
        raw = stream.read(MAX_JSON + 1)
    _require(len(raw) <= MAX_JSON)
    return raw


def measure_files(root, expected):
    _require(isinstance(expected, dict) and 0 < len(expected) <= 20000)
    measured, folded = {}, set()
    for name, identity in sorted(expected.items()):
        _require(isinstance(name, str) and 0 < len(name) <= 240 and name not in {MANIFEST, MARKER})
        path = PurePosixPath(name)
        _require(not path.is_absolute() and path.as_posix() == name and "\\" not in name
                 and all(part not in {".", "..", ".git"} and ":" not in part
                         and not part.casefold().startswith(".env") for part in path.parts)
                 and name.casefold() not in folded)
        folded.add(name.casefold())
        _require(isinstance(identity, dict) and set(identity) == {"sha256", "size_bytes"}
                 and isinstance(identity["sha256"], str) and _HEX64.fullmatch(identity["sha256"])
                 and type(identity["size_bytes"]) is int and identity["size_bytes"] >= 0)
        target = root.joinpath(*path.parts)
        _require(target.resolve().is_relative_to(root))
        checksum, size = _sha(target)
        measured[name] = {"sha256": checksum, "size_bytes": size}
        _require(measured[name] == identity)
    return digest(measured)


def measure_runtime(image, dependencies, configuration):
    _require(isinstance(image, str) and len(image) <= 320 and _IMAGE.fullmatch(image))
    _require(isinstance(configuration, dict) and not set(configuration) - {"LANG", "LC_ALL", "TZ", "PYTHONHASHSEED"})
    _require(all(isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_./:+-]{0,80}", value)
                 and os.environ.get(key) == value for key, value in configuration.items()))
    _require(isinstance(dependencies, dict) and len(dependencies) <= 2000)
    measured = {}
    providers = importlib.metadata.packages_distributions() if dependencies else {}
    for name in sorted(dependencies):
        _require(isinstance(name, str) and re.fullmatch(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*", name, re.ASCII))
        choices = providers.get(name.split(".")[0], [name.replace("_", "-")])
        _require(len(choices) == 1)
        distribution = importlib.metadata.distribution(choices[0])
        files = []
        for item in sorted(distribution.files or [], key=str):
            if "__pycache__" in item.parts or str(item).endswith((".pyc", ".pyo")):
                continue
            # Installed environments can resolve site-packages through a venv
            # link; identify the resolved bytes rather than rejecting that layout.
            path = Path(distribution.locate_file(item)).resolve()
            checksum, size = _sha(path)
            files.append([str(item).replace("\\", "/"), size, checksum])
        _require(bool(files))
        measured[name] = {"version": distribution.version, "sha256": digest(files)}
    architecture = {"x86_64": "amd64", "AMD64": "amd64", "aarch64": "arm64"}.get(platform.machine(), platform.machine().lower())
    return {"format": "sinetti-jobs-runtime/1", "image": image,
            "interpreter": {"implementation": sys.implementation.name, "version": ".".join(map(str, sys.version_info[:3]))},
            "platform": platform.system().lower() + "/" + architecture, "dependencies": measured,
            "configuration_sha256": digest(configuration)}


@dataclass(frozen=True)
class ReaderSnapshot:
    descriptor: bytes
    marker: bytes
    identity: bytes


def _measure(root, descriptor, marker):
    _require(isinstance(descriptor, dict) and set(descriptor) == {
        "format", "source_sha", "release_name", "policy_sha256", "protected_inventory_sha256", "files", "runtime", "configuration"})
    _require(descriptor["format"] == "sinetti-reader-runtime-manifest/1")
    _require(isinstance(descriptor["source_sha"], str) and _HEX40.fullmatch(descriptor["source_sha"]))
    _require(is_release_name(descriptor["release_name"]))
    _require(all(isinstance(descriptor[key], str) and _HEX64.fullmatch(descriptor[key])
                 for key in ("policy_sha256", "protected_inventory_sha256")))
    _require(isinstance(marker, dict) and marker.get("source_head") == descriptor["source_sha"]
             and marker.get("release_name") == descriptor["release_name"]
             and isinstance(marker.get("deployment_id"), str) and re.fullmatch(r"[0-9a-f]{32}", marker["deployment_id"]))
    runtime = descriptor["runtime"]
    _require(isinstance(runtime, dict) and set(runtime) == {
        "format", "image", "interpreter", "platform", "dependencies", "configuration_sha256"})
    measured_runtime = measure_runtime(runtime["image"], runtime["dependencies"], descriptor["configuration"])
    _require(measured_runtime == runtime)
    return {"source_sha": descriptor["source_sha"], "release_name": descriptor["release_name"],
            "deployment_id": marker["deployment_id"], "artifact_sha256": measure_files(root, descriptor["files"]),
            "runtime_sha256": digest(measured_runtime), "policy_sha256": descriptor["policy_sha256"],
            "protected_inventory_sha256": descriptor["protected_inventory_sha256"]}


def capture_reader(root):
    """Capture this process's boot artifact. Missing/unverifiable stays unknown."""
    try:
        root = Path(root).resolve()
        descriptor = _read_metadata(root / MANIFEST)
        marker = _read_metadata(root / MARKER)
        identity = _measure(root, _json(descriptor), _json(marker))
        return ReaderSnapshot(descriptor, marker, canonical(identity))
    except (OSError, ValueError, TypeError, KeyError, RuntimeError, RecursionError, ImportError):
        return None


def observe_reader(root, snapshot, *, nonce=None):
    """Only a new bounded challenge requests current files/runtime remeasurement."""
    challenge = nonce if isinstance(nonce, str) and re.fullmatch(r"[0-9a-f]{32}", nonce) else ""
    unknown = {"format": "sinetti-reader-process/1", "known": False, "fresh": False, "nonce": challenge}
    if not isinstance(snapshot, ReaderSnapshot):
        return unknown
    try:
        if challenge:
            if not _PROBE_LOCK.acquire(blocking=False):
                return unknown
            try:
                root = Path(root).resolve()
                _require(_read_metadata(root / MANIFEST) == snapshot.descriptor
                         and _read_metadata(root / MARKER) == snapshot.marker)
                _require(canonical(_measure(root, _json(snapshot.descriptor), _json(snapshot.marker))) == snapshot.identity)
            finally:
                _PROBE_LOCK.release()
        return {"format": "sinetti-reader-process/1", "known": True, "fresh": bool(challenge),
                "nonce": challenge, **_json(snapshot.identity)}
    except (OSError, ValueError, TypeError, KeyError, RuntimeError, RecursionError, ImportError):
        return unknown