vomebook commited on
Commit ·
35c2dd7
1
Parent(s): fe5d92c
Strictly type pinned reading catalog
Browse files- backend/reader_v3_catalog.py +28 -24
- pyrightconfig.strict.json +2 -1
- tests/test_reader_v3_catalog.py +14 -0
- tests/test_static_checks.py +4 -0
backend/reader_v3_catalog.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
import hashlib
|
| 3 |
import json
|
| 4 |
import re
|
| 5 |
-
from typing import overload, Literal
|
| 6 |
|
| 7 |
import aiohttp
|
| 8 |
|
|
@@ -14,28 +14,28 @@ POINTER = "reader-index/v3/current.json"
|
|
| 14 |
MAX_BYTES = 8 * 1024 * 1024
|
| 15 |
|
| 16 |
|
| 17 |
-
def sha(value):
|
| 18 |
return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value)
|
| 19 |
|
| 20 |
|
| 21 |
-
def catalog_path(generation):
|
| 22 |
if not sha(generation):
|
| 23 |
raise ValueError("invalid v3 catalog generation")
|
| 24 |
return f"reader-index/v3/generations/{generation}/catalog.json"
|
| 25 |
|
| 26 |
|
| 27 |
-
def decode_catalog(pointer, raw):
|
| 28 |
from backend.reader_assets import READER_BUCKET_PATH_RE
|
| 29 |
if pointer.get("version") != 1 or pointer.get("kind") != "reader-reading-pointer":
|
| 30 |
raise ValueError("invalid v3 pointer")
|
| 31 |
generation = pointer.get("generation")
|
| 32 |
-
ref = pointer.get("catalog", {})
|
| 33 |
if (ref.get("bucket") != BUCKET or ref.get("path") != catalog_path(generation)
|
| 34 |
or ref.get("role") != "runtime" or type(ref.get("bytes")) is not int
|
| 35 |
-
or not 1 <= ref["bytes"] <= MAX_BYTES or not sha(ref.get("sha256"))
|
| 36 |
or len(raw) != ref["bytes"] or hashlib.sha256(raw).hexdigest() != ref["sha256"]):
|
| 37 |
raise ValueError("v3 catalog resource mismatch")
|
| 38 |
-
catalog = json.loads(raw)
|
| 39 |
body = {k: v for k, v in catalog.items() if k != "generation"}
|
| 40 |
digest = hashlib.sha256(json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
|
| 41 |
allow_nan=False).encode()).hexdigest()
|
|
@@ -43,11 +43,12 @@ def decode_catalog(pointer, raw):
|
|
| 43 |
or catalog.get("generation") != generation or digest != generation
|
| 44 |
or not isinstance(catalog.get("files"), dict)):
|
| 45 |
raise ValueError("invalid v3 catalog identity")
|
| 46 |
-
overrides = {}
|
| 47 |
-
for key,
|
| 48 |
-
if not isinstance(key, str) or not key or not isinstance(
|
| 49 |
raise ValueError("invalid v3 source key")
|
| 50 |
-
|
|
|
|
| 51 |
source = entry.get("source_sha256")
|
| 52 |
path = resource.get("path", "")
|
| 53 |
if (not isinstance(source, str) or not sha(source) or not sha(entry.get("reading_generation"))
|
|
@@ -55,7 +56,7 @@ def decode_catalog(pointer, raw):
|
|
| 55 |
or not isinstance(path, str) or not READER_BUCKET_PATH_RE.fullmatch(path)
|
| 56 |
or not path.startswith(f"objects/{source[:2]}/{source}/")
|
| 57 |
or not path.endswith("/reading-manifest.json") or not sha(resource.get("sha256"))
|
| 58 |
-
or type(resource.get("bytes")) is not int or resource["bytes"] < 1):
|
| 59 |
raise ValueError("invalid v3 reading reference")
|
| 60 |
overrides[key] = {"s": 2, "m": "p", "p": path, "b": resource["bucket"]}
|
| 61 |
return {"generation": generation, "catalog_sha256": ref["sha256"],
|
|
@@ -63,23 +64,26 @@ def decode_catalog(pointer, raw):
|
|
| 63 |
**({"base_sidecar_ref": catalog["base_sidecar"]} if catalog.get("base_sidecar") else {})}
|
| 64 |
|
| 65 |
|
| 66 |
-
def validate_base_ref(ref):
|
| 67 |
-
if
|
|
|
|
|
|
|
|
|
|
| 68 |
or not sha(ref.get("sha256")) or ref.get("path") !=
|
| 69 |
f"reader-index/snapshots/{ref['sha256']}/reader_assets.json.gz"
|
| 70 |
-
or type(ref.get("bytes")) is not int or not 1 <= ref["bytes"] <= MAX_BYTES):
|
| 71 |
raise ValueError("invalid unified base sidecar")
|
| 72 |
return ref
|
| 73 |
|
| 74 |
|
| 75 |
-
async def load_reading_catalog(session):
|
| 76 |
@overload
|
| 77 |
async def fetch(path: str, *, missing: Literal[True]) -> bytes | None: ...
|
| 78 |
|
| 79 |
@overload
|
| 80 |
async def fetch(path: str, *, missing: Literal[False] = False) -> bytes: ...
|
| 81 |
|
| 82 |
-
async def fetch(path, *, missing=False):
|
| 83 |
source_url = BASE + path
|
| 84 |
# Validate every redirect hop against the fixed URL or signed storage;
|
| 85 |
# metadata is mutable, so its signed targets are never reused.
|
|
@@ -105,16 +109,16 @@ async def load_reading_catalog(session):
|
|
| 105 |
raw = await fetch(POINTER, missing=True)
|
| 106 |
if raw is None:
|
| 107 |
return None
|
| 108 |
-
pointer = json.loads(raw)
|
| 109 |
# Validate the exact fixed catalog path before starting another request.
|
| 110 |
path = catalog_path(pointer.get("generation"))
|
| 111 |
-
if pointer.get("catalog", {}).get("path") != path:
|
| 112 |
raise ValueError("v3 pointer path mismatch")
|
| 113 |
catalog = await fetch(path)
|
| 114 |
result = decode_catalog(pointer, catalog)
|
| 115 |
if result.get("base_sidecar_ref"):
|
| 116 |
ref = validate_base_ref(result["base_sidecar_ref"])
|
| 117 |
-
packed = await fetch(ref["path"])
|
| 118 |
if len(packed) != ref["bytes"] or hashlib.sha256(packed).hexdigest() != ref["sha256"]:
|
| 119 |
raise ValueError("unified base sidecar checksum mismatch")
|
| 120 |
from backend.reader_assets import decode_reader_assets
|
|
@@ -122,10 +126,10 @@ async def load_reading_catalog(session):
|
|
| 122 |
return result
|
| 123 |
|
| 124 |
|
| 125 |
-
def merge_sidecar(base, catalog):
|
| 126 |
if not catalog:
|
| 127 |
return base
|
| 128 |
-
base = catalog.get("base_sidecar", base)
|
| 129 |
-
return {**base, "f": {**base["f"], **catalog["files"]},
|
| 130 |
"v3": {"generation": catalog["generation"], "catalog_sha256": catalog["catalog_sha256"],
|
| 131 |
-
"files": len(catalog["files"])}}
|
|
|
|
| 2 |
import hashlib
|
| 3 |
import json
|
| 4 |
import re
|
| 5 |
+
from typing import overload, Literal, cast
|
| 6 |
|
| 7 |
import aiohttp
|
| 8 |
|
|
|
|
| 14 |
MAX_BYTES = 8 * 1024 * 1024
|
| 15 |
|
| 16 |
|
| 17 |
+
def sha(value: object) -> re.Match[str] | bool | None:
|
| 18 |
return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value)
|
| 19 |
|
| 20 |
|
| 21 |
+
def catalog_path(generation: object) -> str:
|
| 22 |
if not sha(generation):
|
| 23 |
raise ValueError("invalid v3 catalog generation")
|
| 24 |
return f"reader-index/v3/generations/{generation}/catalog.json"
|
| 25 |
|
| 26 |
|
| 27 |
+
def decode_catalog(pointer: dict[str, object], raw: bytes) -> dict[str, object]:
|
| 28 |
from backend.reader_assets import READER_BUCKET_PATH_RE
|
| 29 |
if pointer.get("version") != 1 or pointer.get("kind") != "reader-reading-pointer":
|
| 30 |
raise ValueError("invalid v3 pointer")
|
| 31 |
generation = pointer.get("generation")
|
| 32 |
+
ref = cast(dict[str, object], pointer.get("catalog", {}))
|
| 33 |
if (ref.get("bucket") != BUCKET or ref.get("path") != catalog_path(generation)
|
| 34 |
or ref.get("role") != "runtime" or type(ref.get("bytes")) is not int
|
| 35 |
+
or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES or not sha(ref.get("sha256"))
|
| 36 |
or len(raw) != ref["bytes"] or hashlib.sha256(raw).hexdigest() != ref["sha256"]):
|
| 37 |
raise ValueError("v3 catalog resource mismatch")
|
| 38 |
+
catalog = cast(dict[str, object], json.loads(raw))
|
| 39 |
body = {k: v for k, v in catalog.items() if k != "generation"}
|
| 40 |
digest = hashlib.sha256(json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
|
| 41 |
allow_nan=False).encode()).hexdigest()
|
|
|
|
| 43 |
or catalog.get("generation") != generation or digest != generation
|
| 44 |
or not isinstance(catalog.get("files"), dict)):
|
| 45 |
raise ValueError("invalid v3 catalog identity")
|
| 46 |
+
overrides: dict[str, dict[str, object]] = {}
|
| 47 |
+
for key, raw_entry in cast(dict[object, object], catalog["files"]).items():
|
| 48 |
+
if not isinstance(key, str) or not key or not isinstance(raw_entry, dict):
|
| 49 |
raise ValueError("invalid v3 source key")
|
| 50 |
+
entry = cast(dict[str, object], raw_entry)
|
| 51 |
+
resource = cast(dict[str, object], entry.get("resource", {}))
|
| 52 |
source = entry.get("source_sha256")
|
| 53 |
path = resource.get("path", "")
|
| 54 |
if (not isinstance(source, str) or not sha(source) or not sha(entry.get("reading_generation"))
|
|
|
|
| 56 |
or not isinstance(path, str) or not READER_BUCKET_PATH_RE.fullmatch(path)
|
| 57 |
or not path.startswith(f"objects/{source[:2]}/{source}/")
|
| 58 |
or not path.endswith("/reading-manifest.json") or not sha(resource.get("sha256"))
|
| 59 |
+
or type(resource.get("bytes")) is not int or cast(int, resource["bytes"]) < 1):
|
| 60 |
raise ValueError("invalid v3 reading reference")
|
| 61 |
overrides[key] = {"s": 2, "m": "p", "p": path, "b": resource["bucket"]}
|
| 62 |
return {"generation": generation, "catalog_sha256": ref["sha256"],
|
|
|
|
| 64 |
**({"base_sidecar_ref": catalog["base_sidecar"]} if catalog.get("base_sidecar") else {})}
|
| 65 |
|
| 66 |
|
| 67 |
+
def validate_base_ref(ref: object) -> dict[str, object]:
|
| 68 |
+
if not isinstance(ref, dict):
|
| 69 |
+
raise ValueError("invalid unified base sidecar")
|
| 70 |
+
ref = cast(dict[str, object], ref)
|
| 71 |
+
if (ref.get("bucket") != BUCKET or ref.get("role") != "runtime"
|
| 72 |
or not sha(ref.get("sha256")) or ref.get("path") !=
|
| 73 |
f"reader-index/snapshots/{ref['sha256']}/reader_assets.json.gz"
|
| 74 |
+
or type(ref.get("bytes")) is not int or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES):
|
| 75 |
raise ValueError("invalid unified base sidecar")
|
| 76 |
return ref
|
| 77 |
|
| 78 |
|
| 79 |
+
async def load_reading_catalog(session: object) -> dict[str, object] | None:
|
| 80 |
@overload
|
| 81 |
async def fetch(path: str, *, missing: Literal[True]) -> bytes | None: ...
|
| 82 |
|
| 83 |
@overload
|
| 84 |
async def fetch(path: str, *, missing: Literal[False] = False) -> bytes: ...
|
| 85 |
|
| 86 |
+
async def fetch(path: str, *, missing: bool = False) -> bytes | None:
|
| 87 |
source_url = BASE + path
|
| 88 |
# Validate every redirect hop against the fixed URL or signed storage;
|
| 89 |
# metadata is mutable, so its signed targets are never reused.
|
|
|
|
| 109 |
raw = await fetch(POINTER, missing=True)
|
| 110 |
if raw is None:
|
| 111 |
return None
|
| 112 |
+
pointer = cast(dict[str, object], json.loads(raw))
|
| 113 |
# Validate the exact fixed catalog path before starting another request.
|
| 114 |
path = catalog_path(pointer.get("generation"))
|
| 115 |
+
if cast(dict[str, object], pointer.get("catalog", {})).get("path") != path:
|
| 116 |
raise ValueError("v3 pointer path mismatch")
|
| 117 |
catalog = await fetch(path)
|
| 118 |
result = decode_catalog(pointer, catalog)
|
| 119 |
if result.get("base_sidecar_ref"):
|
| 120 |
ref = validate_base_ref(result["base_sidecar_ref"])
|
| 121 |
+
packed = await fetch(cast(str, ref["path"]))
|
| 122 |
if len(packed) != ref["bytes"] or hashlib.sha256(packed).hexdigest() != ref["sha256"]:
|
| 123 |
raise ValueError("unified base sidecar checksum mismatch")
|
| 124 |
from backend.reader_assets import decode_reader_assets
|
|
|
|
| 126 |
return result
|
| 127 |
|
| 128 |
|
| 129 |
+
def merge_sidecar(base: dict[str, object], catalog: dict[str, object] | None) -> dict[str, object]:
|
| 130 |
if not catalog:
|
| 131 |
return base
|
| 132 |
+
base = cast(dict[str, object], catalog.get("base_sidecar", base))
|
| 133 |
+
return {**base, "f": {**cast(dict[str, object], base["f"]), **cast(dict[str, object], catalog["files"])},
|
| 134 |
"v3": {"generation": catalog["generation"], "catalog_sha256": catalog["catalog_sha256"],
|
| 135 |
+
"files": len(cast(dict[str, object], catalog["files"]))}}
|
pyrightconfig.strict.json
CHANGED
|
@@ -5,7 +5,8 @@
|
|
| 5 |
"backend/search_indexes.py",
|
| 6 |
"backend/data_formats.py",
|
| 7 |
"backend/proxy_streams.py",
|
| 8 |
-
"backend/reader_assets.py"
|
|
|
|
| 9 |
],
|
| 10 |
"pythonVersion": "3.11",
|
| 11 |
"typeCheckingMode": "strict"
|
|
|
|
| 5 |
"backend/search_indexes.py",
|
| 6 |
"backend/data_formats.py",
|
| 7 |
"backend/proxy_streams.py",
|
| 8 |
+
"backend/reader_assets.py",
|
| 9 |
+
"backend/reader_v3_catalog.py"
|
| 10 |
],
|
| 11 |
"pythonVersion": "3.11",
|
| 12 |
"typeCheckingMode": "strict"
|
tests/test_reader_v3_catalog.py
CHANGED
|
@@ -49,6 +49,20 @@ class CatalogTests(unittest.TestCase):
|
|
| 49 |
with self.assertRaises(ValueError):
|
| 50 |
v3.decode_catalog(pointer, raw + b"x")
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
class Response:
|
| 54 |
def __init__(self, raw, status=200):
|
|
|
|
| 49 |
with self.assertRaises(ValueError):
|
| 50 |
v3.decode_catalog(pointer, raw + b"x")
|
| 51 |
|
| 52 |
+
def test_base_snapshot_reference_checks_type_digest_size_and_identity(self):
|
| 53 |
+
digest = "a" * 64
|
| 54 |
+
ref = {"bucket": v3.BUCKET, "role": "runtime", "sha256": digest,
|
| 55 |
+
"path": f"reader-index/snapshots/{digest}/reader_assets.json.gz", "bytes": 12}
|
| 56 |
+
self.assertIs(v3.validate_base_ref(ref), ref)
|
| 57 |
+
for invalid in (None, [], {**ref, "bytes": True}, {**ref, "bytes": 0},
|
| 58 |
+
{**ref, "bytes": v3.MAX_BYTES + 1}, {**ref, "path": "../other.gz"},
|
| 59 |
+
{**ref, "sha256": "not-a-digest"}, {**ref, "bucket": "foreign/bucket"}):
|
| 60 |
+
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
|
| 61 |
+
v3.validate_base_ref(invalid)
|
| 62 |
+
for invalid in (None, 4, "A" * 64, "a" * 63):
|
| 63 |
+
with self.subTest(generation=invalid), self.assertRaises(ValueError):
|
| 64 |
+
v3.catalog_path(invalid)
|
| 65 |
+
|
| 66 |
|
| 67 |
class Response:
|
| 68 |
def __init__(self, raw, status=200):
|
tests/test_static_checks.py
CHANGED
|
@@ -291,6 +291,10 @@ class StaticGateTests(unittest.TestCase):
|
|
| 291 |
source = self.root / "backend/reader_assets.py"
|
| 292 |
source.write_text(source.read_text() + "\ndef strict_assets_probe(value):\n return value\n")
|
| 293 |
self.assert_check(self.run_check(*check), False, "reportUnknownParameterType")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
|
| 296 |
if __name__ == "__main__":
|
|
|
|
| 291 |
source = self.root / "backend/reader_assets.py"
|
| 292 |
source.write_text(source.read_text() + "\ndef strict_assets_probe(value):\n return value\n")
|
| 293 |
self.assert_check(self.run_check(*check), False, "reportUnknownParameterType")
|
| 294 |
+
shutil.copyfile(ROOT / "backend/reader_assets.py", source)
|
| 295 |
+
source = self.root / "backend/reader_v3_catalog.py"
|
| 296 |
+
source.write_text(source.read_text() + "\ndef strict_catalog_probe(value):\n return value\n")
|
| 297 |
+
self.assert_check(self.run_check(*check), False, "reportUnknownParameterType")
|
| 298 |
|
| 299 |
|
| 300 |
if __name__ == "__main__":
|