lib.rs
cdk-rsx/crates/cdk-rsx-source-policy/src/lib.rs
1//! Build-host fingerprints of explicit production-source interpretation recipes.2#![feature(proc_macro_tracked_path)]34use cdk_rsx_compat as compatibility;5use proc_macro::{Span, TokenStream};6use quote::quote;7use sha2::{Digest, Sha256};8use std::{fs, path::Path};9use syn::{Item, Meta, Token, parse::Parser, punctuated::Punctuated, visit_mut::VisitMut};1011const DOMAIN: &[u8] = b"cdk-rsx-production-source-policy-v3\0";12const MANIFEST: &str = include_str!("../Cargo.toml");1314/// Hash the caller's production source, or explicit files relative to it.15/// Include every implementation/helper that interprets the carrier. Test-only16/// items, comments and documentation are not production interpretation inputs.17#[proc_macro]18pub fn source_policy(arguments: TokenStream) -> TokenStream {19 let result = (|| {20 let caller = Span::call_site()21 .local_file()22 .ok_or("source policy requires a local source file")?;23 let files = Punctuated::<syn::LitStr, Token![,]>::parse_terminated24 .parse(arguments)25 .map_err(|error| error.to_string())?;26 let names: Vec<_> = files.into_iter().map(|file| file.value()).collect();27 let mut inputs = Vec::new();28 if names.is_empty() {29 inputs.push(("source".to_owned(), read(&caller)?));30 } else {31 for name in &names {32 if Path::new(name).is_absolute() {33 return Err("policy paths must be relative".to_owned());34 }35 inputs.push((36 name.clone(),37 read(&caller.parent().ok_or("source parent missing")?.join(name))?,38 ));39 }40 }41 emit_policy(Some((&caller, &names)), source_digest(inputs))42 })();43 finish(result)44}4546/// The producer identity is separate from unchanged normalized owner tokens.47/// No declaration result or token stream is a resolver lookup key.48#[proc_macro]49pub fn declaration_policy(arguments: TokenStream) -> TokenStream {50 finish(51 production(&arguments.to_string())52 .and_then(|tokens| emit_policy(None, declaration_digest(tokens))),53 )54}5556fn emit_policy(source: Option<(&Path, &[String])>, raw_leaf: [u8; 32]) -> Result<Emission, String> {57 let (resolver, packages) = compatibility::proc_macro_inputs()?;58 let raw_producer = producer()?;59 let package = Path::new(env!("CARGO_MANIFEST_DIR"));60 let sdk = compatibility::checkout_sdk_root(package, MANIFEST);61 let producer = producer_identity(62 &resolver,63 raw_producer,64 sdk.is_some() || packages.owns(package),65 );66 let mut records = vec![resolver.record(compatibility::PRODUCER_SCOPE, raw_producer, producer)];67 let scope = match (sdk, source) {68 (Some(root), Some((caller, names))) => compatibility::sdk_scope(root, caller, names)?,69 (None, Some((caller, names))) => match compatibility::tracked_env("CARGO_MANIFEST_DIR")? {70 Some(package) => packages.source_scope(Path::new(&package), caller, names)?,71 None => None,72 },73 _ => None,74 };75 let leaf = if let Some(scope) = scope {76 let identity = resolver.resolve(&scope, raw_leaf);77 records.push(resolver.record(&scope, raw_leaf, identity));78 identity79 } else {80 raw_leaf81 };82 let value = bind_producer(producer, leaf);83 Ok(Emission { value, records })84}8586fn producer_identity(resolver: &compatibility::Resolver, raw: [u8; 32], owned: bool) -> [u8; 32] {87 if owned {88 resolver.resolve(compatibility::PRODUCER_SCOPE, raw)89 } else {90 // Without package ownership, keep the producer and source raw.91 raw92 }93}94fn producer() -> Result<[u8; 32], String> {95 Ok(digest(vec![96 ("kind".to_owned(), b"producer".to_vec()),97 ("recipe/Cargo.toml".to_owned(), MANIFEST.as_bytes().to_vec()),98 (99 "recipe/lib.rs".to_owned(),100 production(include_str!("lib.rs"))?,101 ),102 (103 "recipe/resolver/Cargo.toml".to_owned(),104 compatibility::RECIPE_MANIFEST.as_bytes().to_vec(),105 ),106 (107 "recipe/resolver/src/lib.rs".to_owned(),108 production(compatibility::RECIPE_SOURCE)?,109 ),110 ]))111}112fn source_digest(inputs: Vec<(String, Vec<u8>)>) -> [u8; 32] {113 let mut framed = vec![("kind".to_owned(), b"source".to_vec())];114 framed.extend(115 inputs116 .into_iter()117 .map(|(name, bytes)| (format!("file/{name}"), bytes)),118 );119 digest(framed)120}121fn declaration_digest(tokens: Vec<u8>) -> [u8; 32] {122 digest(vec![123 ("kind".to_owned(), b"declaration".to_vec()),124 ("tokens".to_owned(), tokens),125 ])126}127fn bind_producer(producer: [u8; 32], leaf: [u8; 32]) -> [u8; 32] {128 digest(vec![129 ("kind".to_owned(), b"bound-leaf".to_vec()),130 ("producer".to_owned(), producer.to_vec()),131 ("leaf".to_owned(), leaf.to_vec()),132 ])133}134struct Emission {135 value: [u8; 32],136 records: Vec<String>,137}138impl Emission {139 fn expression(self) -> proc_macro2::TokenStream {140 let values = self.value.iter();141 let records: proc_macro2::TokenStream = compatibility::wasm_record(&self.records.concat())142 .parse()143 .expect("source policy record tokens");144 quote!({145 #records146 [#(#values),*]147 })148 }149}150fn finish(result: Result<Emission, String>) -> TokenStream {151 match result {152 Ok(value) => value.expression().into(),153 Err(error) => format!("compile_error!({error:?})")154 .parse()155 .expect("policy error"),156 }157}158fn read(path: &Path) -> Result<Vec<u8>, String> {159 proc_macro::tracked::path(path);160 read_source(path)161}162fn read_source(path: &Path) -> Result<Vec<u8>, String> {163 let bytes =164 fs::read(path).map_err(|error| format!("policy source {}: {error}", path.display()))?;165 if path.extension().is_some_and(|extension| extension == "rs") {166 production(core::str::from_utf8(&bytes).map_err(|error| error.to_string())?)167 } else {168 Ok(bytes)169 }170}171fn test_only(attrs: &[syn::Attribute]) -> bool {172 attrs.iter().any(|attr| {173 attr.path().is_ident("test")174 || (attr.path().is_ident("cfg")175 && attr176 .parse_args::<Meta>()177 .is_ok_and(|meta| matches!(meta, Meta::Path(path) if path.is_ident("test"))))178 })179}180fn item_attrs(item: &Item) -> &[syn::Attribute] {181 match item {182 Item::Const(x) => &x.attrs,183 Item::Enum(x) => &x.attrs,184 Item::ExternCrate(x) => &x.attrs,185 Item::Fn(x) => &x.attrs,186 Item::ForeignMod(x) => &x.attrs,187 Item::Impl(x) => &x.attrs,188 Item::Macro(x) => &x.attrs,189 Item::Mod(x) => &x.attrs,190 Item::Static(x) => &x.attrs,191 Item::Struct(x) => &x.attrs,192 Item::Trait(x) => &x.attrs,193 Item::TraitAlias(x) => &x.attrs,194 Item::Type(x) => &x.attrs,195 Item::Union(x) => &x.attrs,196 Item::Use(x) => &x.attrs,197 _ => &[],198 }199}200struct Production;201impl VisitMut for Production {202 fn visit_file_mut(&mut self, file: &mut syn::File) {203 file.items.retain(|item| !test_only(item_attrs(item)));204 syn::visit_mut::visit_file_mut(self, file);205 }206 fn visit_item_mod_mut(&mut self, module: &mut syn::ItemMod) {207 if let Some((_, items)) = &mut module.content {208 items.retain(|item| !test_only(item_attrs(item)));209 }210 syn::visit_mut::visit_item_mod_mut(self, module);211 }212 fn visit_item_impl_mut(&mut self, item: &mut syn::ItemImpl) {213 item.items.retain(|item| {214 !test_only(match item {215 syn::ImplItem::Const(x) => &x.attrs,216 syn::ImplItem::Fn(x) => &x.attrs,217 syn::ImplItem::Type(x) => &x.attrs,218 syn::ImplItem::Macro(x) => &x.attrs,219 _ => &[],220 })221 });222 syn::visit_mut::visit_item_impl_mut(self, item);223 }224 fn visit_item_enum_mut(&mut self, item: &mut syn::ItemEnum) {225 item.variants = item226 .variants227 .clone()228 .into_iter()229 .filter(|variant| !test_only(&variant.attrs))230 .collect();231 syn::visit_mut::visit_item_enum_mut(self, item);232 }233 fn visit_fields_named_mut(&mut self, fields: &mut syn::FieldsNamed) {234 fields.named = fields235 .named236 .clone()237 .into_iter()238 .filter(|field| !test_only(&field.attrs))239 .collect();240 syn::visit_mut::visit_fields_named_mut(self, fields);241 }242 fn visit_fields_unnamed_mut(&mut self, fields: &mut syn::FieldsUnnamed) {243 fields.unnamed = fields244 .unnamed245 .clone()246 .into_iter()247 .filter(|field| !test_only(&field.attrs))248 .collect();249 syn::visit_mut::visit_fields_unnamed_mut(self, fields);250 }251 fn visit_block_mut(&mut self, block: &mut syn::Block) {252 block.stmts.retain(253 |statement| !matches!(statement, syn::Stmt::Item(item) if test_only(item_attrs(item))),254 );255 syn::visit_mut::visit_block_mut(self, block);256 }257}258fn without_docs(tokens: proc_macro2::TokenStream) -> proc_macro2::TokenStream {259 use proc_macro2::{Delimiter, Group, TokenTree};260 let mut result = proc_macro2::TokenStream::new();261 let tokens: Vec<_> = tokens.into_iter().collect();262 let mut index = 0;263 while index < tokens.len() {264 let token = tokens[index].clone();265 if matches!(&token, TokenTree::Punct(p) if p.as_char() == '#') {266 let mut attribute = index + 1;267 if matches!(tokens.get(attribute), Some(TokenTree::Punct(p)) if p.as_char() == '!') {268 attribute += 1;269 }270 if let Some(TokenTree::Group(group)) = tokens.get(attribute) {271 if group.delimiter() == Delimiter::Bracket272 && matches!(group.stream().into_iter().next(), Some(TokenTree::Ident(id)) if id == "doc")273 {274 index = attribute + 1;275 continue;276 }277 }278 }279 result.extend([match token {280 TokenTree::Group(group) => {281 TokenTree::Group(Group::new(group.delimiter(), without_docs(group.stream())))282 }283 other => other,284 }]);285 index += 1;286 }287 result288}289fn production(source: &str) -> Result<Vec<u8>, String> {290 let mut file =291 syn::parse_file(source).map_err(|error| format!("invalid policy Rust source: {error}"))?;292 Production.visit_file_mut(&mut file);293 Ok(without_docs(quote!(#file)).to_string().into_bytes())294}295fn digest(mut inputs: Vec<(String, Vec<u8>)>) -> [u8; 32] {296 inputs.sort_unstable_by(|a, b| a.0.cmp(&b.0));297 let mut hash = Sha256::new();298 hash.update(DOMAIN);299 for (name, bytes) in inputs {300 hash.update((name.len() as u64).to_le_bytes());301 hash.update(name.as_bytes());302 hash.update((bytes.len() as u64).to_le_bytes());303 hash.update(bytes);304 }305 hash.finalize().into()306}307308#[cfg(test)]309mod tests {310 use super::*;311 #[test]312 fn sdk_checkout_requires_workspace_inheritance_and_physical_package_layout() {313 let checkout = Path::new("/sdk");314 let workspace = "version.workspace = true";315 let packaged = r#"version = "0.1.0""#;316 assert_eq!(317 compatibility::checkout_sdk_root(&checkout.join("crates/policy"), workspace),318 Some(checkout)319 );320 assert_eq!(321 compatibility::checkout_sdk_root(&checkout.join("crates/policy"), packaged),322 None323 );324 assert_eq!(325 compatibility::checkout_sdk_root(&checkout.join("packages/policy"), workspace),326 None327 );328 }329 #[test]330 fn qualified_producer_never_normalizes_owner_tokens_or_external_file_bytes() {331 let path =332 std::env::temp_dir().join(format!("cdk-rsx-policy-alias-{}.json", std::process::id()));333 let context = compatibility::hex([1; 32]);334 let raw = [2; 32];335 let identity = [3; 32];336 let payload = serde_json::json!({"format":"cdk-rsx-compat-aliases-v1","entries":[{337 "context":context,"scope":compatibility::PRODUCER_SCOPE,338 "raw":compatibility::hex(raw),"identity":compatibility::hex(identity)339 }]});340 fs::write(&path, serde_json::to_vec(&payload).unwrap()).unwrap();341 let resolver = compatibility::Resolver::load(Some(&context), Some(&path)).unwrap();342 let effective = producer_identity(&resolver, raw, true);343 assert_eq!(effective, identity);344 assert_eq!(producer_identity(&resolver, raw, false), raw);345 let unsigned = production("struct Data { value: u64 }").unwrap();346 let signed = production("struct Data { value: i64 }").unwrap();347 // Same-width scalars can have the same physical classification; the348 // untouched owner tokens must still keep their interpretation distinct.349 assert_ne!(350 bind_producer(effective, declaration_digest(unsigned.clone())),351 bind_producer(effective, declaration_digest(signed.clone()))352 );353 assert_eq!(354 bind_producer(effective, declaration_digest(unsigned.clone())),355 bind_producer(identity, declaration_digest(unsigned.clone()))356 );357 assert_ne!(358 source_digest(vec![("source".to_owned(), unsigned.clone())]),359 source_digest(vec![("source".to_owned(), signed)])360 );361 // Producer and actual source require independent exact entries.362 let raw_leaf = source_digest(vec![("lib.rs".to_owned(), unsigned)]);363 assert_ne!(364 bind_producer(raw, raw_leaf),365 bind_producer(effective, raw_leaf)366 );367 assert_eq!(368 resolver.resolve("sdk/crates/example/src/lib.rs:lib.rs", raw_leaf),369 raw_leaf370 );371 fs::remove_file(path).unwrap();372 }373 #[test]374 fn actual_source_and_alias_file_changes_are_read_fresh() {375 let path =376 std::env::temp_dir().join(format!("cdk-rsx-policy-source-{}.rs", std::process::id()));377 fs::write(&path, "struct Data(u64);").unwrap();378 let first = source_digest(vec![("source".to_owned(), read_source(&path).unwrap())]);379 fs::write(&path, "struct Data(i64);").unwrap();380 let second = source_digest(vec![("source".to_owned(), read_source(&path).unwrap())]);381 assert_ne!(first, second);382 fs::remove_file(path).unwrap();383 let path = std::env::temp_dir().join(format!(384 "cdk-rsx-policy-refresh-{}.json",385 std::process::id()386 ));387 let context = compatibility::hex([1; 32]);388 for identity in [[8; 32], [9; 32]] {389 let payload = serde_json::json!({"format":"cdk-rsx-compat-aliases-v1","entries":[{390 "context":context,"scope":compatibility::PRODUCER_SCOPE,391 "raw":compatibility::hex([2;32]),"identity":compatibility::hex(identity)392 }]});393 fs::write(&path, serde_json::to_vec(&payload).unwrap()).unwrap();394 let resolver = compatibility::Resolver::load(Some(&context), Some(&path)).unwrap();395 assert_eq!(396 resolver.resolve(compatibility::PRODUCER_SCOPE, [2; 32]),397 identity398 );399 }400 fs::remove_file(path).unwrap();401 }402 #[test]403 fn records_are_newline_json_in_wasm_only_used_const_statics() {404 let resolver = compatibility::Resolver::load(None, None).unwrap();405 let record = resolver.record(compatibility::PRODUCER_SCOPE, [4; 32], [4; 32]);406 assert!(record.ends_with('\n'));407 let parsed: serde_json::Value = serde_json::from_str(&record).unwrap();408 assert_eq!(parsed["context"], compatibility::hex([0; 32]));409 assert_eq!(parsed.as_object().unwrap().len(), 4);410 let expression = Emission {411 value: [4; 32],412 records: vec![record],413 }414 .expression()415 .to_string();416 assert!(expression.contains("target_family = \"wasm\""));417 assert!(expression.contains("used (compiler)"));418 assert!(expression.contains("icp:private cdk-rsx-compatibility"));419 }420 #[test]421 fn tests_and_docs_do_not_qualify_production() {422 let a = "/// docs\nstruct A(u64); #[cfg(test)] mod tests { fn first() {} }";423 let b = "/// changed\nstruct A(u64); #[cfg(test)] mod tests { fn second() { panic!() } }";424 assert_eq!(production(a).unwrap(), production(b).unwrap());425 assert_ne!(426 production(a).unwrap(),427 production("struct A(u32);").unwrap()428 );429 assert_ne!(430 production("#[cfg(feature=\"x\")] struct A;").unwrap(),431 production("struct A;").unwrap()432 );433 }434}