compiler_preparation.rs (11218B)
1 //! Current SDK compiler requirements; validation does not qualify execution. 2 3 use std::{fmt, fs, io::Read as _, path::Path}; 4 5 use serde::Deserialize; 6 use sha2::{Digest as _, Sha256}; 7 8 use crate::service_source_lock_v4::{RUST_VERSION, validate_lib_compiler_inputs}; 9 10 const CONTRACT: &str = "contracts/architecture/decisions/shared_sdk_compiler_preparation.v1.json"; 11 const MAX_CONTRACT_BYTES: usize = 65_536; 12 const BOUND_INPUTS: [(&str, &str); 3] = [ 13 ( 14 "contracts/architecture/decisions/shared_sdk_refactor.v1.json", 15 "cc9906ff7c811b80100a0a1a1d363a7a58fb301b901b3f059eee3cb259e95e9e", 16 ), 17 ( 18 "contracts/architecture/decisions/services_hardening_source_lock.v4.json", 19 "133057de55c3691badcc3a29a9cc7009e1adb62564e4608b7441f6a2d42373bd", 20 ), 21 ( 22 "contracts/architecture/decisions/services_hardening_release_artifacts.v5.json", 23 "b535c9c891889681c07031a3a6e3d3f7372501f2a233e20eb2cb2d79c9101fee", 24 ), 25 ]; 26 const COMPONENTS: [&str; 4] = ["clippy", "rust-analyzer", "rust-src", "rustfmt"]; 27 const DECLARED_TARGETS: [&str; 1] = ["wasm32-unknown-unknown"]; 28 const NATIVE_TARGETS: [&str; 2] = ["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"]; 29 const APPLE_TARGETS: [&str; 2] = ["aarch64-apple-ios", "aarch64-apple-ios-sim"]; 30 const NIX_SYSTEMS: [&str; 2] = ["aarch64-darwin", "x86_64-linux"]; 31 32 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 33 enum PreparationError { 34 InvalidContract, 35 InvalidInput, 36 } 37 38 impl fmt::Display for PreparationError { 39 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 40 formatter.write_str(match self { 41 Self::InvalidContract => "current compiler preparation contract is invalid", 42 Self::InvalidInput => "current compiler preparation input is invalid", 43 }) 44 } 45 } 46 47 impl std::error::Error for PreparationError {} 48 49 #[derive(Debug, Deserialize)] 50 #[serde(deny_unknown_fields)] 51 struct Decision { 52 schema: String, 53 contract_version: u32, 54 state: String, 55 stable: String, 56 msrv: String, 57 edition: String, 58 source_inputs: Vec<BoundInput>, 59 required_declared_components: Vec<String>, 60 required_declared_targets: Vec<String>, 61 native_targets: Vec<String>, 62 apple_artifact_targets: Vec<String>, 63 nix_systems: Vec<String>, 64 dedicated_toolchains_separate: bool, 65 historical_receipts_immutable: bool, 66 declaration_validation_proves_execution: bool, 67 execution_evidence: String, 68 publication_authorized: bool, 69 candidate_activation_authorized: bool, 70 } 71 72 #[derive(Debug, Deserialize)] 73 #[serde(deny_unknown_fields)] 74 struct BoundInput { 75 path: String, 76 sha256: String, 77 } 78 79 pub(crate) fn validate_contract(root: &Path) -> Result<(), String> { 80 validate(root).map_err(|error| error.to_string()) 81 } 82 83 fn validate(root: &Path) -> Result<(), PreparationError> { 84 let bytes = read_bounded( 85 root, 86 CONTRACT, 87 MAX_CONTRACT_BYTES, 88 PreparationError::InvalidContract, 89 )?; 90 let decision: Decision = 91 serde_json::from_slice(&bytes).map_err(|_| PreparationError::InvalidContract)?; 92 validate_decision(&decision)?; 93 validate_bound_inputs(root)?; 94 validate_current_inputs(root) 95 } 96 97 fn validate_decision(value: &Decision) -> Result<(), PreparationError> { 98 let exact = value.schema == "radroots.shared_sdk.compiler_preparation.v1" 99 && value.contract_version == 1 100 && value.state == "active_requirements_execution_unclaimed" 101 && value.stable == RUST_VERSION 102 && value.msrv == RUST_VERSION 103 && value.edition == "2024" 104 && value.source_inputs.len() == BOUND_INPUTS.len() 105 && value 106 .source_inputs 107 .iter() 108 .zip(BOUND_INPUTS) 109 .all(|(input, (path, digest))| input.path == path && input.sha256 == digest) 110 && value.required_declared_components == COMPONENTS 111 && value.required_declared_targets == DECLARED_TARGETS 112 && value.native_targets == NATIVE_TARGETS 113 && value.apple_artifact_targets == APPLE_TARGETS 114 && value.nix_systems == NIX_SYSTEMS 115 && value.dedicated_toolchains_separate 116 && value.historical_receipts_immutable 117 && !value.declaration_validation_proves_execution 118 && value.execution_evidence == "separate_source_scoped_receipts" 119 && !value.publication_authorized 120 && !value.candidate_activation_authorized; 121 if exact { 122 Ok(()) 123 } else { 124 Err(PreparationError::InvalidContract) 125 } 126 } 127 128 fn validate_bound_inputs(root: &Path) -> Result<(), PreparationError> { 129 for (path, expected) in BOUND_INPUTS { 130 let bytes = read_bounded( 131 root, 132 path, 133 MAX_CONTRACT_BYTES, 134 PreparationError::InvalidContract, 135 )?; 136 if hex::encode(Sha256::digest(&bytes)) != expected { 137 return Err(PreparationError::InvalidContract); 138 } 139 } 140 Ok(()) 141 } 142 143 fn validate_current_inputs(root: &Path) -> Result<(), PreparationError> { 144 let read = |path, limit| read_bounded(root, path, limit, PreparationError::InvalidInput); 145 let manifest = read("Cargo.toml", 1_048_576)?; 146 let toolchain = read("rust-toolchain.toml", 65_536)?; 147 let catalog = read("contracts/crates/catalog.v2.toml", 4_194_304)?; 148 validate_lib_compiler_inputs(&manifest, &toolchain, &catalog) 149 .map_err(|_| PreparationError::InvalidInput)?; 150 let toolchain = std::str::from_utf8(&toolchain).map_err(|_| PreparationError::InvalidInput)?; 151 let toolchain: toml::Value = 152 toml::from_str(toolchain).map_err(|_| PreparationError::InvalidInput)?; 153 for (field, required) in [ 154 ("components", COMPONENTS.as_slice()), 155 ("targets", DECLARED_TARGETS.as_slice()), 156 ] { 157 let declared = toolchain 158 .get("toolchain") 159 .and_then(|value| value.get(field)) 160 .and_then(toml::Value::as_array) 161 .ok_or(PreparationError::InvalidInput)?; 162 let declared = declared 163 .iter() 164 .map(toml::Value::as_str) 165 .collect::<Option<Vec<_>>>() 166 .ok_or(PreparationError::InvalidInput)?; 167 if !required.iter().all(|value| declared.contains(value)) { 168 return Err(PreparationError::InvalidInput); 169 } 170 } 171 Ok(()) 172 } 173 174 fn read_bounded( 175 root: &Path, 176 relative: &str, 177 maximum: usize, 178 error: PreparationError, 179 ) -> Result<Vec<u8>, PreparationError> { 180 let path = root.join(relative); 181 let metadata = fs::symlink_metadata(&path).map_err(|_| error)?; 182 if metadata.file_type().is_symlink() || !metadata.is_file() || metadata.len() > maximum as u64 { 183 return Err(error); 184 } 185 let mut bytes = Vec::new(); 186 fs::File::open(path) 187 .map_err(|_| error)? 188 .take(maximum as u64 + 1) 189 .read_to_end(&mut bytes) 190 .map_err(|_| error)?; 191 if bytes.len() > maximum { 192 Err(error) 193 } else { 194 Ok(bytes) 195 } 196 } 197 198 #[cfg(test)] 199 mod tests { 200 use super::*; 201 use serde_json::json; 202 use tempfile::TempDir; 203 204 fn root() -> &'static Path { 205 Path::new(env!("CARGO_MANIFEST_DIR")) 206 .parent() 207 .and_then(Path::parent) 208 .expect("workspace root") 209 } 210 211 fn copy_inputs(paths: &[&str]) -> TempDir { 212 let destination = TempDir::new().expect("input fixture"); 213 for path in paths { 214 let target = destination.path().join(path); 215 fs::create_dir_all(target.parent().expect("parent")).expect("parent"); 216 fs::copy(root().join(path), target).expect("copy input"); 217 } 218 destination 219 } 220 221 #[test] 222 fn current_requirements_and_bound_source_inputs_validate() { 223 validate(root()).expect("current compiler requirements"); 224 } 225 226 #[test] 227 fn independent_contract_drift_cannot_change_compiler_matrix_or_claims() { 228 let bytes = fs::read(root().join(CONTRACT)).expect("contract"); 229 let canonical: serde_json::Value = serde_json::from_slice(&bytes).expect("JSON"); 230 for (pointer, replacement) in [ 231 ("/schema", json!("other")), 232 ("/contract_version", json!(2)), 233 ("/state", json!("qualified")), 234 ("/stable", json!("1.97.1")), 235 ("/msrv", json!("1.98.0")), 236 ("/edition", json!("2021")), 237 ("/source_inputs/0/path", json!("../other")), 238 ("/source_inputs/1/sha256", json!("0".repeat(64))), 239 ("/required_declared_components", json!([])), 240 ("/required_declared_targets", json!([])), 241 ("/native_targets", json!([])), 242 ("/apple_artifact_targets", json!([])), 243 ("/nix_systems", json!([])), 244 ("/dedicated_toolchains_separate", json!(false)), 245 ("/historical_receipts_immutable", json!(false)), 246 ("/declaration_validation_proves_execution", json!(true)), 247 ("/execution_evidence", json!("embedded_in_contract")), 248 ("/publication_authorized", json!(true)), 249 ("/candidate_activation_authorized", json!(true)), 250 ] { 251 let mut changed = canonical.clone(); 252 *changed.pointer_mut(pointer).expect("governed field") = replacement; 253 let decision = serde_json::from_value(changed).expect("structurally valid drift"); 254 assert_eq!( 255 validate_decision(&decision), 256 Err(PreparationError::InvalidContract), 257 "{pointer}" 258 ); 259 } 260 let mut extra = canonical; 261 extra["unrecognized_claim"] = json!(true); 262 assert!(serde_json::from_value::<Decision>(extra).is_err()); 263 } 264 265 #[test] 266 fn exact_bound_contract_bytes_cannot_be_substituted() { 267 let paths: Vec<_> = BOUND_INPUTS.iter().map(|(path, _)| *path).collect(); 268 for path in paths.iter() { 269 let fixture = copy_inputs(&paths); 270 validate_bound_inputs(fixture.path()).expect("original inputs"); 271 fs::write(fixture.path().join(path), b"{}\n").expect("substitute input"); 272 assert_eq!( 273 validate_bound_inputs(fixture.path()), 274 Err(PreparationError::InvalidContract) 275 ); 276 } 277 } 278 279 #[test] 280 fn current_inputs_require_the_compiler_components_and_wasm_declaration() { 281 for from in [ 282 "1.99.0", 283 "clippy", 284 "rust-analyzer", 285 "rust-src", 286 "rustfmt", 287 "wasm32-unknown-unknown", 288 ] { 289 let fixture = copy_inputs(&[ 290 "Cargo.toml", 291 "rust-toolchain.toml", 292 "contracts/crates/catalog.v2.toml", 293 ]); 294 validate_current_inputs(fixture.path()).expect("current input fixture"); 295 let path = fixture.path().join("rust-toolchain.toml"); 296 let original = fs::read_to_string(&path).expect("selector"); 297 assert!(original.contains(from)); 298 fs::write(path, original.replace(from, "other")).expect("selector drift"); 299 assert_eq!( 300 validate_current_inputs(fixture.path()), 301 Err(PreparationError::InvalidInput), 302 "{from}" 303 ); 304 } 305 } 306 }