field_ios

In-the-field app for Radroots on iOS
git clone https://radroots.dev/git/field_ios.git
Log | Files | Refs | README | LICENSE

ffi_notices.py (6722B)


      1 """Complete, bounded redistribution material from the exact Cargo provider."""
      2 
      3 from __future__ import annotations
      4 
      5 import hashlib
      6 import os
      7 import re
      8 import stat
      9 from pathlib import Path
     10 from typing import Any
     11 
     12 import ffi_source as source
     13 import package_contract as contract
     14 
     15 ARTIFACT_PATH = "redistribution/shared_data_NOTICE.txt"
     16 INSTALLED_PATH = "Tera/Resources/SharedDataNOTICE.txt"
     17 MAX_BYTES = 65_536
     18 CONTRACT = {
     19     "package": "radroots_domain",
     20     "version": "0.1.0-alpha",
     21     "source_file": "NOTICE",
     22     "sha256": "4376b5764456a4fa5f74fd712390adeb897d1ccdd62d5f818b2bcd767003760a",
     23     "maximum_bytes": MAX_BYTES,
     24     "artifact_path": ARTIFACT_PATH,
     25     "installed_path": INSTALLED_PATH,
     26 }
     27 
     28 
     29 def validate_contract(value: Any) -> None:
     30     contract._exact(value, CONTRACT, "redistribution material authority")
     31 
     32 
     33 def read_material(path: Path) -> bytes:
     34     try:
     35         descriptor = os.open(
     36             path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW | os.O_NONBLOCK
     37         )
     38         with os.fdopen(descriptor, "rb") as stream:
     39             before = os.fstat(stream.fileno())
     40             if not stat.S_ISREG(before.st_mode) or not 0 < before.st_size <= MAX_BYTES:
     41                 raise source.ProvenanceError("redistribution material is not bounded")
     42             data = stream.read(MAX_BYTES + 1)
     43             after = os.fstat(stream.fileno())
     44         current = path.lstat()
     45     except OSError as error:
     46         raise source.ProvenanceError(
     47             "redistribution material is unavailable"
     48         ) from error
     49     if (
     50         len(data) != before.st_size
     51         or identity(before) != identity(after)
     52         or identity(current) != identity(after)
     53     ):
     54         raise source.ProvenanceError("redistribution material changed while reading")
     55     try:
     56         data.decode("utf-8")
     57     except UnicodeDecodeError as error:
     58         raise source.ProvenanceError("redistribution material is not UTF-8") from error
     59     return data
     60 
     61 
     62 def identity(value: os.stat_result) -> tuple[int, ...]:
     63     return (
     64         value.st_dev,
     65         value.st_ino,
     66         value.st_mode,
     67         value.st_size,
     68         value.st_mtime_ns,
     69         value.st_ctime_ns,
     70     )
     71 
     72 
     73 def provider_path(root: Path, foundation: dict[str, Any]) -> Path:
     74     document = contract._cargo_workspace(root, resolved=True)
     75     packages = [
     76         value
     77         for value in document.get("packages", [])
     78         if value.get("name") == CONTRACT["package"]
     79     ]
     80     if len(packages) != 1:
     81         raise source.ProvenanceError("redistribution provider is ambiguous")
     82     package = packages[0]
     83     revision = foundation["revision"]
     84     sources = {
     85         f"git+{repository}?rev={revision}#{revision}"
     86         for repository in (foundation["repository"], foundation["repository"] + ".git")
     87     }
     88     if (
     89         package.get("version") != CONTRACT["version"]
     90         or package.get("source") not in sources
     91     ):
     92         raise source.ProvenanceError("redistribution provider identity differs")
     93     manifest = Path(package.get("manifest_path", ""))
     94     if (
     95         not manifest.is_absolute()
     96         or manifest.name != "Cargo.toml"
     97         or manifest.resolve() != manifest
     98     ):
     99         raise source.ProvenanceError("redistribution provider path is invalid")
    100     return manifest.parent / CONTRACT["source_file"]
    101 
    102 
    103 def validate_binding(value: dict[str, Any]) -> None:
    104     value = contract._mapping(value, "redistribution binding")
    105     expected = {
    106         "schema",
    107         "package",
    108         "version",
    109         "repository",
    110         "revision",
    111         "bytes",
    112         "sha256",
    113         "artifact_path",
    114         "installed_path",
    115     }
    116     contract._exact(set(value), expected, "redistribution binding fields")
    117     for key, expected_value in {
    118         "schema": "tera.redistribution.v1",
    119         "package": CONTRACT["package"],
    120         "version": CONTRACT["version"],
    121         "repository": contract.LIB_REMOTE,
    122         "artifact_path": ARTIFACT_PATH,
    123         "installed_path": INSTALLED_PATH,
    124     }.items():
    125         contract._exact(value[key], expected_value, "redistribution binding identity")
    126     if not isinstance(value["revision"], str) or not re.fullmatch(
    127         r"[0-9a-f]{40}", value["revision"]
    128     ):
    129         raise source.ProvenanceError("redistribution revision is invalid")
    130     if not isinstance(value["sha256"], str) or not re.fullmatch(
    131         r"[0-9a-f]{64}", value["sha256"]
    132     ):
    133         raise source.ProvenanceError("redistribution digest is invalid")
    134     if type(value["bytes"]) is not int or not 0 < value["bytes"] <= MAX_BYTES:
    135         raise source.ProvenanceError("redistribution size is invalid")
    136 
    137 
    138 def verify_expected(
    139     value: dict[str, Any], foundation: dict[str, Any], config: dict[str, Any]
    140 ) -> None:
    141     validate_binding(value)
    142     for key in ("repository", "revision"):
    143         contract._exact(
    144             value[key], foundation[key], "redistribution foundation identity"
    145         )
    146     contract._exact(value["sha256"], config["sha256"], "redistribution contract digest")
    147 
    148 
    149 def verify_material(path: Path, binding: dict[str, Any]) -> bytes:
    150     validate_binding(binding)
    151     data = read_material(path)
    152     if (
    153         len(data) != binding["bytes"]
    154         or hashlib.sha256(data).hexdigest() != binding["sha256"]
    155     ):
    156         raise source.ProvenanceError("redistribution material differs from its binding")
    157     return data
    158 
    159 
    160 def verify_inventory(
    161     files: list[dict[str, Any]], binding: dict[str, Any], relative: str
    162 ) -> None:
    163     validate_binding(binding)
    164     selected = [item for item in files if item.get("path") == relative]
    165     contract._exact(
    166         selected,
    167         [{"path": relative, "bytes": binding["bytes"], "sha256": binding["sha256"]}],
    168         "redistribution inventory binding",
    169     )
    170 
    171 
    172 def capture(root: Path, foundation: dict[str, Any]) -> dict[str, Any]:
    173     data = read_material(provider_path(root, foundation))
    174     result = {
    175         "schema": "tera.redistribution.v1",
    176         "package": CONTRACT["package"],
    177         "version": CONTRACT["version"],
    178         "repository": foundation["repository"],
    179         "revision": foundation["revision"],
    180         "bytes": len(data),
    181         "sha256": hashlib.sha256(data).hexdigest(),
    182         "artifact_path": ARTIFACT_PATH,
    183         "installed_path": INSTALLED_PATH,
    184     }
    185     verify_expected(result, foundation, CONTRACT)
    186     return result
    187 
    188 
    189 def install(
    190     root: Path, bundle: Path, binding: dict[str, Any], foundation: dict[str, Any]
    191 ) -> None:
    192     verify_expected(binding, foundation, CONTRACT)
    193     data = verify_material(provider_path(root, foundation), binding)
    194     destination = bundle / ARTIFACT_PATH
    195     destination.parent.mkdir(parents=True, exist_ok=True)
    196     destination.write_bytes(data)
    197     verify_material(destination, binding)