ffi_provenance.py (7839B)
1 """Generate or check staged producer evidence, separate from installed artifacts.""" 2 3 from __future__ import annotations 4 5 import argparse 6 import hashlib 7 import json 8 import os 9 import sys 10 import tempfile 11 from pathlib import Path 12 from typing import Any 13 14 import ffi_source as source 15 import ffi_native as native 16 import ffi_notices as notices 17 import package_contract as contract 18 19 20 def capture(root: Path, target: str) -> dict[str, Any]: 21 source.reject_build_overrides() 22 source.reject_cargo_configuration(root) 23 config = source.producer_contract(root) 24 build = config["build"] 25 if target not in build["targets"]: 26 raise source.ProvenanceError("producer target is not governed") 27 snapshot = source.source_snapshot(root, config["source_inputs"]) 28 native_target = native.capture(root, target) 29 native_host = native.capture(root, build["host"]) 30 environment = native.inspection_environment() 31 rustc = ( 32 source.command(root, ["rustc", "-Vv"], environment=environment).decode().strip() 33 ) 34 if f"release: {build['rust_version']}\n" not in rustc + "\n": 35 raise source.ProvenanceError( 36 "active Rust compiler differs from producer contract" 37 ) 38 if f"host: {build['host']}\n" not in rustc + "\n": 39 raise source.ProvenanceError("active Rust host differs from producer contract") 40 result = { 41 "schema": "tera.producer-source.v2", 42 "repository": config["repository"], 43 "source": snapshot, 44 "foundation": contract._read_toml(root / config["foundation_lock"]), 45 "redistribution": notices.capture( 46 root, contract._read_toml(root / config["foundation_lock"]) 47 ), 48 "cargo_lock_sha256": hashlib.sha256( 49 source.read_source(root, "Cargo.lock") 50 ).hexdigest(), 51 "build": { 52 **config["ffi"], 53 "target": target, 54 "profile": build["profile"], 55 "ios_deployment_target": build["ios_deployment_target"], 56 "rust_flags": build["rust_flags"], 57 "package_rust_flags": source.library_rust_flags(build, target), 58 "source_date_epoch": build["source_date_epoch"], 59 "rustc": rustc, 60 "symbol_reader_identity": native.file_identity( 61 symbol_reader(root, build["host"]) 62 ), 63 "symbol_reader": source.command( 64 root, 65 [str(symbol_reader(root, build["host"])), "--version"], 66 environment=environment, 67 ) 68 .decode() 69 .strip(), 70 "apple_toolchain": apple_toolchain(root), 71 "native": native_target, 72 "feature_graph": source.feature_graph( 73 root, 74 config["ffi"]["package"], 75 target, 76 environment=environment, 77 ), 78 }, 79 "generator": { 80 **config["generator"], 81 "target": build["host"], 82 "profile": "dev", 83 "profile_overrides": source.allowed_profile_overrides(), 84 "native": native_host, 85 "feature_graph": source.feature_graph( 86 root, 87 config["generator"]["package"], 88 build["host"], 89 environment=environment, 90 ), 91 }, 92 "disposition": "local_staged_source_only", 93 } 94 if source.source_snapshot(root, config["source_inputs"]) != snapshot: 95 raise source.ProvenanceError("producer source changed during capture") 96 native.verify(root, native_target) 97 native.verify(root, native_host) 98 return result 99 100 101 def symbol_reader(root: Path, host: str) -> Path: 102 sysroot = Path( 103 source.command( 104 root, 105 ["rustc", "--print", "sysroot"], 106 environment=native.inspection_environment(), 107 ) 108 .decode() 109 .strip() 110 ) 111 reader = sysroot / "lib/rustlib" / host / "bin/llvm-nm" 112 if not reader.is_file() or not os.access(reader, os.X_OK): 113 raise source.ProvenanceError("Rust toolchain llvm-tools component is required") 114 return reader 115 116 117 def apple_toolchain(root: Path) -> dict[str, str]: 118 commands = { 119 "xcode": ["xcodebuild", "-version"], 120 "swift": ["xcrun", "swiftc", "--version"], 121 "swiftformat": ["swiftformat", "--version"], 122 "iphoneos_sdk": ["xcrun", "--sdk", "iphoneos", "--show-sdk-build-version"], 123 "iphonesimulator_sdk": [ 124 "xcrun", 125 "--sdk", 126 "iphonesimulator", 127 "--show-sdk-build-version", 128 ], 129 } 130 return { 131 name: source.command(root, argv, environment=native.inspection_environment()) 132 .decode() 133 .strip() 134 for name, argv in commands.items() 135 } 136 137 138 def encoded(value: dict[str, Any]) -> bytes: 139 return (json.dumps(value, sort_keys=True, indent=2) + "\n").encode() 140 141 142 def verify_record(actual: bytes, expected: dict[str, Any]) -> None: 143 if actual != encoded(expected): 144 raise source.ProvenanceError( 145 "producer provenance differs from the exact source/build tuple" 146 ) 147 148 149 def output_path(root: Path, target: str, requested: str | None) -> Path: 150 external = os.environ.get("EXT_BUILD_PROJECT_DIR") 151 if not external or not os.environ.get("EXT_BUILD_RUN_ACTIVE"): 152 raise source.ProvenanceError("producer provenance requires extbuild") 153 base = Path(external).resolve() 154 path = ( 155 Path(requested) 156 if requested 157 else base / "target/tera_ffi/source" / f"{target}.json" 158 ) 159 path = path.absolute() 160 if not path.is_relative_to(base) or path.is_relative_to(root): 161 raise source.ProvenanceError("producer evidence must use external build output") 162 if path.resolve() != path or path.is_symlink(): 163 raise source.ProvenanceError("producer evidence output contains a symlink") 164 return path 165 166 167 def write_atomic(path: Path, data: bytes) -> None: 168 path.parent.mkdir(parents=True, exist_ok=True) 169 temporary: str | None = None 170 try: 171 with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle: 172 temporary = handle.name 173 handle.write(data) 174 handle.flush() 175 os.fsync(handle.fileno()) 176 os.replace(temporary, path) 177 temporary = None 178 finally: 179 if temporary: 180 Path(temporary).unlink(missing_ok=True) 181 182 183 def main() -> int: 184 parser = argparse.ArgumentParser(description=__doc__) 185 parser.add_argument("mode", choices=("contract-check", "write", "check")) 186 parser.add_argument("--target") 187 parser.add_argument( 188 "--repo-root", type=Path, default=Path(__file__).resolve().parent.parent 189 ) 190 parser.add_argument("--output") 191 args = parser.parse_args() 192 try: 193 root = args.repo_root.resolve() 194 if args.mode == "contract-check": 195 source.producer_contract(root) 196 print( 197 "FFI producer contract verified; installed artifacts remain separately governed" 198 ) 199 return 0 200 if not args.target: 201 raise source.ProvenanceError("producer target is required") 202 path = output_path(root, args.target, args.output) 203 record = capture(root, args.target) 204 if args.mode == "write": 205 write_atomic(path, encoded(record)) 206 verify_record(contract._read_regular(path), record) 207 except ( 208 source.ProvenanceError, 209 contract.PackageContractError, 210 OSError, 211 ValueError, 212 KeyError, 213 ) as error: 214 print(f"FFI producer provenance: {error}", file=sys.stderr) 215 return 1 216 print( 217 f"FFI producer source {args.mode}: {args.target}; tree={record['source']['tree']}; local staged source only" 218 ) 219 return 0 220 221 222 if __name__ == "__main__": 223 raise SystemExit(main())