lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

service_source_lock_v4.rs (27244B)


      1 use std::fmt;
      2 
      3 use serde::Deserialize;
      4 
      5 use crate::service_source_lock::{ContractVersions, LIB_REPOSITORY};
      6 use crate::service_source_lock_parts::{
      7     RawArtifactContract, RawSourceArchiveContract, RawSqliteContract,
      8 };
      9 
     10 pub(crate) const LOCK_FILENAME: &str = "radroots.service.source_lock.v4.toml";
     11 pub(crate) const PREDECESSOR_LOCK_FILENAME: &str = "radroots.service.source-lock.v3.toml";
     12 pub(crate) const PREDECESSOR_LOCK_FILENAMES: [&str; 3] = [
     13     "radroots.service.source-lock.v1.toml",
     14     "radroots.service.source-lock.v2.toml",
     15     PREDECESSOR_LOCK_FILENAME,
     16 ];
     17 pub(crate) const MAX_LOCK_BYTES: usize = 16 * 1024;
     18 const ARCHITECTURE: &str = "radroots.crates.release.v2";
     19 const LIB_VERSION: &str = "0.1.0-alpha";
     20 pub(crate) const RUST_VERSION: &str = "1.99.0";
     21 const HOST_FEATURE_PROFILE: &str = "service-host";
     22 
     23 #[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
     24 #[serde(deny_unknown_fields)]
     25 struct RawPublicInputLock {
     26     path: String,
     27     sha256: String,
     28     binding: String,
     29     mutable_reference: String,
     30     lib_input: String,
     31 }
     32 
     33 #[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
     34 #[serde(deny_unknown_fields)]
     35 struct RawParentResult {
     36     embedded_in_public_input_lock: bool,
     37     embedded_in_source_lock: bool,
     38     storage: String,
     39 }
     40 
     41 #[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
     42 #[serde(deny_unknown_fields)]
     43 struct RawBoundNix {
     44     material: String,
     45     lib_revision: String,
     46     supported_systems: Vec<String>,
     47     public_input_lock: RawPublicInputLock,
     48     parent_result: RawParentResult,
     49 }
     50 
     51 #[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
     52 #[serde(deny_unknown_fields)]
     53 struct RawServiceSourceLockV4 {
     54     schema: String,
     55     contract_version: u32,
     56     service: String,
     57     repository: String,
     58     revision: String,
     59     architecture: String,
     60     workspace_catalog_sha256: String,
     61     version: String,
     62     source_archive_sha256: String,
     63     source_archive_contract: RawSourceArchiveContract,
     64     cargo_lock_sha256: String,
     65     rust_version: String,
     66     host_feature_profile: String,
     67     nix: RawBoundNix,
     68     artifact_contract: RawArtifactContract,
     69     sqlite: RawSqliteContract,
     70     contract_versions: ContractVersions,
     71 }
     72 
     73 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     74 pub(crate) enum ServiceSourceLockV4Error {
     75     TooLarge,
     76     Malformed,
     77     Noncanonical,
     78     Invalid,
     79 }
     80 
     81 impl fmt::Display for ServiceSourceLockV4Error {
     82     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
     83         formatter.write_str(match self {
     84             Self::TooLarge => "service source lock v4 exceeds its byte limit",
     85             Self::Malformed => "service source lock v4 is malformed",
     86             Self::Noncanonical => "service source lock v4 is not canonical",
     87             Self::Invalid => "service source lock v4 is invalid",
     88         })
     89     }
     90 }
     91 
     92 impl std::error::Error for ServiceSourceLockV4Error {}
     93 
     94 #[derive(Clone, Eq, PartialEq)]
     95 pub(crate) struct ServiceSourceLockV4 {
     96     raw: RawServiceSourceLockV4,
     97     canonical: Box<[u8]>,
     98 }
     99 
    100 pub(crate) struct ServiceSourceLockV4Parts<'a> {
    101     pub(crate) service: &'a str,
    102     pub(crate) revision: &'a str,
    103     pub(crate) workspace_catalog_sha256: &'a str,
    104     pub(crate) source_archive_sha256: &'a str,
    105     pub(crate) cargo_lock_sha256: &'a str,
    106     pub(crate) flake_lock_sha256: &'a str,
    107     pub(crate) artifact_contract_sha256: &'a str,
    108     pub(crate) contract_versions: ContractVersions,
    109 }
    110 
    111 impl fmt::Debug for ServiceSourceLockV4 {
    112     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    113         formatter
    114             .debug_struct("ServiceSourceLockV4")
    115             .finish_non_exhaustive()
    116     }
    117 }
    118 
    119 impl ServiceSourceLockV4 {
    120     pub(crate) fn from_canonical_bytes(bytes: &[u8]) -> Result<Self, ServiceSourceLockV4Error> {
    121         if bytes.len() > MAX_LOCK_BYTES {
    122             return Err(ServiceSourceLockV4Error::TooLarge);
    123         }
    124         let text = std::str::from_utf8(bytes).map_err(|_| ServiceSourceLockV4Error::Malformed)?;
    125         let raw = toml::from_str::<RawServiceSourceLockV4>(text)
    126             .map_err(|_| ServiceSourceLockV4Error::Malformed)?;
    127         validate(&raw)?;
    128         let canonical = canonical_bytes(&raw);
    129         if bytes != canonical.as_slice() {
    130             return Err(ServiceSourceLockV4Error::Noncanonical);
    131         }
    132         Ok(Self {
    133             raw,
    134             canonical: canonical.into_boxed_slice(),
    135         })
    136     }
    137 
    138     pub(crate) fn canonical_bytes(&self) -> &[u8] {
    139         &self.canonical
    140     }
    141 
    142     pub(crate) fn service(&self) -> &str {
    143         &self.raw.service
    144     }
    145 
    146     pub(crate) fn revision(&self) -> &str {
    147         &self.raw.revision
    148     }
    149 
    150     pub(crate) fn workspace_catalog_sha256(&self) -> &str {
    151         &self.raw.workspace_catalog_sha256
    152     }
    153 
    154     pub(crate) fn source_archive_sha256(&self) -> &str {
    155         &self.raw.source_archive_sha256
    156     }
    157 
    158     pub(crate) fn cargo_lock_sha256(&self) -> &str {
    159         &self.raw.cargo_lock_sha256
    160     }
    161 
    162     pub(crate) fn flake_lock_sha256(&self) -> &str {
    163         &self.raw.nix.public_input_lock.sha256
    164     }
    165 
    166     pub(crate) fn artifact_contract_path(&self) -> &str {
    167         &self.raw.artifact_contract.path
    168     }
    169 
    170     pub(crate) fn artifact_contract_sha256(&self) -> &str {
    171         &self.raw.artifact_contract.sha256
    172     }
    173 
    174     pub(crate) const fn contract_versions(&self) -> ContractVersions {
    175         self.raw.contract_versions
    176     }
    177 
    178     pub(crate) fn new(
    179         parts: ServiceSourceLockV4Parts<'_>,
    180     ) -> Result<Self, ServiceSourceLockV4Error> {
    181         let ServiceSourceLockV4Parts {
    182             service,
    183             revision,
    184             workspace_catalog_sha256,
    185             source_archive_sha256,
    186             cargo_lock_sha256,
    187             flake_lock_sha256,
    188             artifact_contract_sha256,
    189             contract_versions,
    190         } = parts;
    191         let artifact_path = format!("contracts/release/{service}-artifact-contract.v4.json");
    192         let raw = RawServiceSourceLockV4 {
    193             schema: "radroots.service.source_lock.v4".to_owned(),
    194             contract_version: 4,
    195             service: service.to_owned(),
    196             repository: LIB_REPOSITORY.to_owned(),
    197             revision: revision.to_owned(),
    198             architecture: ARCHITECTURE.to_owned(),
    199             workspace_catalog_sha256: workspace_catalog_sha256.to_owned(),
    200             version: LIB_VERSION.to_owned(),
    201             source_archive_sha256: source_archive_sha256.to_owned(),
    202             source_archive_contract: RawSourceArchiveContract {
    203                 binding: "sha256_of_canonical_exact_lib_revision_tree_archive".to_owned(),
    204                 format: "ustar".to_owned(),
    205                 compression: "none".to_owned(),
    206                 compression_timestamp: "not_applicable".to_owned(),
    207                 entry_order: "bytewise_git_path".to_owned(),
    208                 path_prefix: "none".to_owned(),
    209                 file_mode: "git_index_100644_or_100755".to_owned(),
    210                 uid: 0,
    211                 gid: 0,
    212                 uname: String::new(),
    213                 gname: String::new(),
    214                 mtime: "lib_revision_commit_timestamp".to_owned(),
    215                 pax_headers: "forbidden".to_owned(),
    216                 directory_entries: "omitted".to_owned(),
    217                 symlinks: "forbidden".to_owned(),
    218                 hardlinks: "forbidden".to_owned(),
    219                 submodules: "forbidden".to_owned(),
    220                 trailer: "two_zero_blocks".to_owned(),
    221             },
    222             cargo_lock_sha256: cargo_lock_sha256.to_owned(),
    223             rust_version: RUST_VERSION.to_owned(),
    224             host_feature_profile: HOST_FEATURE_PROFILE.to_owned(),
    225             nix: RawBoundNix {
    226                 material: "bound".to_owned(),
    227                 lib_revision: revision.to_owned(),
    228                 supported_systems: vec!["aarch64-darwin".to_owned(), "x86_64-linux".to_owned()],
    229                 public_input_lock: RawPublicInputLock {
    230                     path: "flake.lock".to_owned(),
    231                     sha256: flake_lock_sha256.to_owned(),
    232                     binding: "exact_regular_file_bytes".to_owned(),
    233                     mutable_reference: "forbidden".to_owned(),
    234                     lib_input: "lib".to_owned(),
    235                 },
    236                 parent_result: RawParentResult {
    237                     embedded_in_public_input_lock: false,
    238                     embedded_in_source_lock: false,
    239                     storage: "separate_source_scoped_execution_evidence".to_owned(),
    240                 },
    241             },
    242             artifact_contract: RawArtifactContract {
    243                 path: artifact_path,
    244                 sha256: artifact_contract_sha256.to_owned(),
    245                 binding: "exact_regular_file_bytes_in_same_source_revision".to_owned(),
    246             },
    247             sqlite: RawSqliteContract {
    248                 high_level_authority: "sqlx_only".to_owned(),
    249                 second_pool_connection_query_transaction_migration_authority: "forbidden"
    250                     .to_owned(),
    251                 incremental_backup_adapter: "sealed_native_sqlx_owned_locked_handle_only"
    252                     .to_owned(),
    253                 native_linkage_count: 1,
    254             },
    255             contract_versions,
    256         };
    257         validate(&raw)?;
    258         let canonical = canonical_bytes(&raw).into_boxed_slice();
    259         Ok(Self { raw, canonical })
    260     }
    261 }
    262 
    263 fn validate(raw: &RawServiceSourceLockV4) -> Result<(), ServiceSourceLockV4Error> {
    264     let expected_artifact = match raw.service.as_str() {
    265         "myc" => "contracts/release/myc-artifact-contract.v4.json",
    266         "rhi" => "contracts/release/rhi-artifact-contract.v4.json",
    267         _ => return Err(ServiceSourceLockV4Error::Invalid),
    268     };
    269     let archive = &raw.source_archive_contract;
    270     if raw.schema != "radroots.service.source_lock.v4"
    271         || raw.contract_version != 4
    272         || raw.repository != LIB_REPOSITORY
    273         || !valid_lower_hex(&raw.revision, 40)
    274         || raw.architecture != ARCHITECTURE
    275         || !valid_lower_hex(&raw.workspace_catalog_sha256, 64)
    276         || raw.version != LIB_VERSION
    277         || !valid_lower_hex(&raw.source_archive_sha256, 64)
    278         || !valid_lower_hex(&raw.cargo_lock_sha256, 64)
    279         || raw.rust_version != RUST_VERSION
    280         || raw.host_feature_profile != HOST_FEATURE_PROFILE
    281         || archive.binding != "sha256_of_canonical_exact_lib_revision_tree_archive"
    282         || archive.format != "ustar"
    283         || archive.compression != "none"
    284         || archive.compression_timestamp != "not_applicable"
    285         || archive.entry_order != "bytewise_git_path"
    286         || archive.path_prefix != "none"
    287         || archive.file_mode != "git_index_100644_or_100755"
    288         || archive.uid != 0
    289         || archive.gid != 0
    290         || !archive.uname.is_empty()
    291         || !archive.gname.is_empty()
    292         || archive.mtime != "lib_revision_commit_timestamp"
    293         || archive.pax_headers != "forbidden"
    294         || archive.directory_entries != "omitted"
    295         || archive.symlinks != "forbidden"
    296         || archive.hardlinks != "forbidden"
    297         || archive.submodules != "forbidden"
    298         || archive.trailer != "two_zero_blocks"
    299         || raw.nix.material != "bound"
    300         || raw.nix.lib_revision != raw.revision
    301         || raw.nix.supported_systems != ["aarch64-darwin", "x86_64-linux"]
    302         || raw.nix.public_input_lock.path != "flake.lock"
    303         || !valid_lower_hex(&raw.nix.public_input_lock.sha256, 64)
    304         || raw.nix.public_input_lock.binding != "exact_regular_file_bytes"
    305         || raw.nix.public_input_lock.mutable_reference != "forbidden"
    306         || raw.nix.public_input_lock.lib_input != "lib"
    307         || raw.nix.parent_result.embedded_in_public_input_lock
    308         || raw.nix.parent_result.embedded_in_source_lock
    309         || raw.nix.parent_result.storage != "separate_source_scoped_execution_evidence"
    310         || raw.artifact_contract.path != expected_artifact
    311         || !valid_lower_hex(&raw.artifact_contract.sha256, 64)
    312         || raw.artifact_contract.binding != "exact_regular_file_bytes_in_same_source_revision"
    313         || raw.sqlite.high_level_authority != "sqlx_only"
    314         || raw
    315             .sqlite
    316             .second_pool_connection_query_transaction_migration_authority
    317             != "forbidden"
    318         || raw.sqlite.incremental_backup_adapter != "sealed_native_sqlx_owned_locked_handle_only"
    319         || raw.sqlite.native_linkage_count != 1
    320         || !contract_versions_valid(raw.contract_versions)
    321     {
    322         Err(ServiceSourceLockV4Error::Invalid)
    323     } else {
    324         Ok(())
    325     }
    326 }
    327 
    328 fn contract_versions_valid(versions: ContractVersions) -> bool {
    329     versions.config() != 0
    330         && versions.state() != 0
    331         && versions.admin() != 0
    332         && versions.status() != 0
    333         && versions.provider() != 0
    334 }
    335 
    336 fn canonical_bytes(raw: &RawServiceSourceLockV4) -> Vec<u8> {
    337     format!(
    338         concat!(
    339             "schema = \"radroots.service.source_lock.v4\"\n",
    340             "contract_version = 4\n",
    341             "service = \"{}\"\n",
    342             "repository = \"https://github.com/radrootslabs/lib\"\n",
    343             "revision = \"{}\"\n",
    344             "architecture = \"radroots.crates.release.v2\"\n",
    345             "workspace_catalog_sha256 = \"{}\"\n",
    346             "version = \"0.1.0-alpha\"\n",
    347             "source_archive_sha256 = \"{}\"\n",
    348             "cargo_lock_sha256 = \"{}\"\n",
    349             "rust_version = \"1.99.0\"\n",
    350             "host_feature_profile = \"service-host\"\n\n",
    351             "[source_archive_contract]\n",
    352             "binding = \"sha256_of_canonical_exact_lib_revision_tree_archive\"\n",
    353             "format = \"ustar\"\n",
    354             "compression = \"none\"\n",
    355             "compression_timestamp = \"not_applicable\"\n",
    356             "entry_order = \"bytewise_git_path\"\n",
    357             "path_prefix = \"none\"\n",
    358             "file_mode = \"git_index_100644_or_100755\"\n",
    359             "uid = 0\n",
    360             "gid = 0\n",
    361             "uname = \"\"\n",
    362             "gname = \"\"\n",
    363             "mtime = \"lib_revision_commit_timestamp\"\n",
    364             "pax_headers = \"forbidden\"\n",
    365             "directory_entries = \"omitted\"\n",
    366             "symlinks = \"forbidden\"\n",
    367             "hardlinks = \"forbidden\"\n",
    368             "submodules = \"forbidden\"\n",
    369             "trailer = \"two_zero_blocks\"\n\n",
    370             "[nix]\n",
    371             "material = \"bound\"\n",
    372             "lib_revision = \"{}\"\n",
    373             "supported_systems = [\"aarch64-darwin\", \"x86_64-linux\"]\n\n",
    374             "[nix.public_input_lock]\n",
    375             "path = \"flake.lock\"\n",
    376             "sha256 = \"{}\"\n",
    377             "binding = \"exact_regular_file_bytes\"\n",
    378             "mutable_reference = \"forbidden\"\n",
    379             "lib_input = \"lib\"\n\n",
    380             "[nix.parent_result]\n",
    381             "embedded_in_public_input_lock = false\n",
    382             "embedded_in_source_lock = false\n",
    383             "storage = \"separate_source_scoped_execution_evidence\"\n\n",
    384             "[artifact_contract]\n",
    385             "path = \"{}\"\n",
    386             "sha256 = \"{}\"\n",
    387             "binding = \"exact_regular_file_bytes_in_same_source_revision\"\n\n",
    388             "[sqlite]\n",
    389             "high_level_authority = \"sqlx_only\"\n",
    390             "second_pool_connection_query_transaction_migration_authority = \"forbidden\"\n",
    391             "incremental_backup_adapter = \"sealed_native_sqlx_owned_locked_handle_only\"\n",
    392             "native_linkage_count = 1\n\n",
    393             "[contract_versions]\n",
    394             "config = {}\n",
    395             "state = {}\n",
    396             "admin = {}\n",
    397             "status = {}\n",
    398             "provider = {}\n"
    399         ),
    400         raw.service,
    401         raw.revision,
    402         raw.workspace_catalog_sha256,
    403         raw.source_archive_sha256,
    404         raw.cargo_lock_sha256,
    405         raw.nix.lib_revision,
    406         raw.nix.public_input_lock.sha256,
    407         raw.artifact_contract.path,
    408         raw.artifact_contract.sha256,
    409         raw.contract_versions.config(),
    410         raw.contract_versions.state(),
    411         raw.contract_versions.admin(),
    412         raw.contract_versions.status(),
    413         raw.contract_versions.provider(),
    414     )
    415     .into_bytes()
    416 }
    417 
    418 pub(crate) fn validate_toolchain_bytes(bytes: &[u8]) -> Result<(), ServiceSourceLockV4Error> {
    419     let text = std::str::from_utf8(bytes).map_err(|_| ServiceSourceLockV4Error::Malformed)?;
    420     let value: toml::Value =
    421         toml::from_str(text).map_err(|_| ServiceSourceLockV4Error::Malformed)?;
    422     if value
    423         .get("toolchain")
    424         .and_then(|v| v.get("channel"))
    425         .and_then(toml::Value::as_str)
    426         == Some(RUST_VERSION)
    427     {
    428         Ok(())
    429     } else {
    430         Err(ServiceSourceLockV4Error::Invalid)
    431     }
    432 }
    433 
    434 pub(crate) fn validate_lib_compiler_inputs(
    435     manifest: &[u8],
    436     toolchain: &[u8],
    437     catalog: &[u8],
    438 ) -> Result<(), ServiceSourceLockV4Error> {
    439     validate_toolchain_bytes(toolchain)?;
    440     let parse = |bytes: &[u8]| -> Result<toml::Value, ServiceSourceLockV4Error> {
    441         let text = std::str::from_utf8(bytes).map_err(|_| ServiceSourceLockV4Error::Malformed)?;
    442         toml::from_str(text).map_err(|_| ServiceSourceLockV4Error::Malformed)
    443     };
    444     let manifest = parse(manifest)?;
    445     let catalog = parse(catalog)?;
    446     let package = manifest
    447         .get("workspace")
    448         .and_then(|v| v.get("package"))
    449         .ok_or(ServiceSourceLockV4Error::Invalid)?;
    450     if package.get("rust-version").and_then(toml::Value::as_str) != Some(RUST_VERSION)
    451         || package.get("edition").and_then(toml::Value::as_str) != Some("2024")
    452         || package.get("version").and_then(toml::Value::as_str) != Some(LIB_VERSION)
    453         || catalog.get("schema").and_then(toml::Value::as_str)
    454             != Some("radroots.workspace.catalog.v2")
    455         || catalog.get("architecture").and_then(toml::Value::as_str) != Some(ARCHITECTURE)
    456         || catalog.get("version").and_then(toml::Value::as_str) != Some(LIB_VERSION)
    457         || catalog.get("rust_version").and_then(toml::Value::as_str) != Some(RUST_VERSION)
    458         || catalog.get("edition").and_then(toml::Value::as_str) != Some("2024")
    459         || catalog.get("resolver").and_then(toml::Value::as_str) != Some("3")
    460     {
    461         Err(ServiceSourceLockV4Error::Invalid)
    462     } else {
    463         Ok(())
    464     }
    465 }
    466 
    467 fn valid_lower_hex(value: &str, length: usize) -> bool {
    468     value.len() == length
    469         && value
    470             .bytes()
    471             .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    472 }
    473 
    474 #[cfg(test)]
    475 mod tests {
    476     use super::*;
    477 
    478     const MYC_LOCK: &[u8] = br#"schema = "radroots.service.source_lock.v4"
    479 contract_version = 4
    480 service = "myc"
    481 repository = "https://github.com/radrootslabs/lib"
    482 revision = "1111111111111111111111111111111111111111"
    483 architecture = "radroots.crates.release.v2"
    484 workspace_catalog_sha256 = "2222222222222222222222222222222222222222222222222222222222222222"
    485 version = "0.1.0-alpha"
    486 source_archive_sha256 = "3333333333333333333333333333333333333333333333333333333333333333"
    487 cargo_lock_sha256 = "4444444444444444444444444444444444444444444444444444444444444444"
    488 rust_version = "1.99.0"
    489 host_feature_profile = "service-host"
    490 
    491 [source_archive_contract]
    492 binding = "sha256_of_canonical_exact_lib_revision_tree_archive"
    493 format = "ustar"
    494 compression = "none"
    495 compression_timestamp = "not_applicable"
    496 entry_order = "bytewise_git_path"
    497 path_prefix = "none"
    498 file_mode = "git_index_100644_or_100755"
    499 uid = 0
    500 gid = 0
    501 uname = ""
    502 gname = ""
    503 mtime = "lib_revision_commit_timestamp"
    504 pax_headers = "forbidden"
    505 directory_entries = "omitted"
    506 symlinks = "forbidden"
    507 hardlinks = "forbidden"
    508 submodules = "forbidden"
    509 trailer = "two_zero_blocks"
    510 
    511 [nix]
    512 material = "bound"
    513 lib_revision = "1111111111111111111111111111111111111111"
    514 supported_systems = ["aarch64-darwin", "x86_64-linux"]
    515 
    516 [nix.public_input_lock]
    517 path = "flake.lock"
    518 sha256 = "5555555555555555555555555555555555555555555555555555555555555555"
    519 binding = "exact_regular_file_bytes"
    520 mutable_reference = "forbidden"
    521 lib_input = "lib"
    522 
    523 [nix.parent_result]
    524 embedded_in_public_input_lock = false
    525 embedded_in_source_lock = false
    526 storage = "separate_source_scoped_execution_evidence"
    527 
    528 [artifact_contract]
    529 path = "contracts/release/myc-artifact-contract.v4.json"
    530 sha256 = "6666666666666666666666666666666666666666666666666666666666666666"
    531 binding = "exact_regular_file_bytes_in_same_source_revision"
    532 
    533 [sqlite]
    534 high_level_authority = "sqlx_only"
    535 second_pool_connection_query_transaction_migration_authority = "forbidden"
    536 incremental_backup_adapter = "sealed_native_sqlx_owned_locked_handle_only"
    537 native_linkage_count = 1
    538 
    539 [contract_versions]
    540 config = 1
    541 state = 2
    542 admin = 3
    543 status = 4
    544 provider = 5
    545 "#;
    546 
    547     #[test]
    548     fn canonical_v4_lock_round_trips_and_exposes_exact_bindings() {
    549         let lock = ServiceSourceLockV4::from_canonical_bytes(MYC_LOCK).expect("v4 lock");
    550         assert_eq!(lock.canonical_bytes(), MYC_LOCK);
    551         assert_eq!(lock.service(), "myc");
    552         assert_eq!(lock.revision(), "1".repeat(40));
    553         assert_eq!(
    554             lock.artifact_contract_path(),
    555             "contracts/release/myc-artifact-contract.v4.json"
    556         );
    557         assert_eq!(
    558             lock.contract_versions(),
    559             ContractVersions::new(1, 2, 3, 4, 5)
    560         );
    561     }
    562 
    563     #[test]
    564     fn v4_lock_rejects_noncanonical_and_independent_semantic_drift() {
    565         let noncanonical = String::from_utf8(MYC_LOCK.to_vec())
    566             .expect("UTF-8")
    567             .replace("schema =", "schema  =");
    568         assert!(ServiceSourceLockV4::from_canonical_bytes(noncanonical.as_bytes()).is_err());
    569         for (from, to) in [
    570             ("service = \"myc\"", "service = \"other\""),
    571             ("material = \"bound\"", "material = \"deferred\""),
    572             ("native_linkage_count = 1", "native_linkage_count = 2"),
    573             ("trailer = \"two_zero_blocks\"", "trailer = \"other\""),
    574         ] {
    575             let drifted = String::from_utf8(MYC_LOCK.to_vec())
    576                 .expect("UTF-8")
    577                 .replace(from, to);
    578             assert!(
    579                 ServiceSourceLockV4::from_canonical_bytes(drifted.as_bytes()).is_err(),
    580                 "{from}"
    581             );
    582         }
    583     }
    584 
    585     #[test]
    586     fn current_constructor_and_json_schema_agree_for_both_services() {
    587         let original = ServiceSourceLockV4::from_canonical_bytes(MYC_LOCK).expect("input");
    588         let schema: serde_json::Value = serde_json::from_str(include_str!(
    589             "../../../contracts/architecture/decisions/services_hardening_source_lock.v4.json"
    590         ))
    591         .expect("schema");
    592         let validator = jsonschema::validator_for(&schema).expect("schema validator");
    593         for service in ["myc", "rhi"] {
    594             let lock = ServiceSourceLockV4::new(ServiceSourceLockV4Parts {
    595                 service,
    596                 revision: original.revision(),
    597                 workspace_catalog_sha256: original.workspace_catalog_sha256(),
    598                 source_archive_sha256: original.source_archive_sha256(),
    599                 cargo_lock_sha256: original.cargo_lock_sha256(),
    600                 flake_lock_sha256: original.flake_lock_sha256(),
    601                 artifact_contract_sha256: original.artifact_contract_sha256(),
    602                 contract_versions: original.contract_versions(),
    603             })
    604             .expect("current constructor");
    605             assert_eq!(
    606                 ServiceSourceLockV4::from_canonical_bytes(lock.canonical_bytes())
    607                     .expect("canonical round trip"),
    608                 lock
    609             );
    610             let document: toml::Value =
    611                 toml::from_str(std::str::from_utf8(lock.canonical_bytes()).expect("UTF-8"))
    612                     .expect("TOML");
    613             assert!(validator.is_valid(&serde_json::to_value(document).expect("JSON model")));
    614         }
    615     }
    616 
    617     #[test]
    618     fn current_parser_rejects_oversize_malformed_unknown_and_predecessor_bytes() {
    619         assert_eq!(
    620             ServiceSourceLockV4::from_canonical_bytes(&vec![b' '; MAX_LOCK_BYTES + 1]),
    621             Err(ServiceSourceLockV4Error::TooLarge)
    622         );
    623         assert_eq!(
    624             ServiceSourceLockV4::from_canonical_bytes(b"\xff"),
    625             Err(ServiceSourceLockV4Error::Malformed)
    626         );
    627         let valid = std::str::from_utf8(MYC_LOCK).expect("UTF-8");
    628         for invalid in [
    629             valid.replace("schema =", "extra = true\nschema ="),
    630             valid.replace(
    631                 "contract_version = 4",
    632                 "contract_version = 4\ncontract_version = 4",
    633             ),
    634             valid.replace("rust_version = \"1.99.0\"", "rust_version = \"1.97.1\""),
    635             valid.replace("material = \"bound\"", "material = \"qualified\""),
    636             valid.replace(
    637                 "radroots.service.source_lock.v4",
    638                 "radroots.service.source-lock.v3",
    639             ),
    640             valid.replace(
    641                 "lib_revision = \"1111111111111111111111111111111111111111\"",
    642                 "lib_revision = \"9999999999999999999999999999999999999999\"",
    643             ),
    644             valid.replace("myc-artifact-contract.v4", "rhi-artifact-contract.v4"),
    645         ] {
    646             assert!(ServiceSourceLockV4::from_canonical_bytes(invalid.as_bytes()).is_err());
    647         }
    648         let mut padded = MYC_LOCK.to_vec();
    649         padded.resize(MAX_LOCK_BYTES, b' ');
    650         assert_eq!(
    651             ServiceSourceLockV4::from_canonical_bytes(&padded),
    652             Err(ServiceSourceLockV4Error::Noncanonical)
    653         );
    654     }
    655 
    656     #[test]
    657     fn compiler_input_policy_rejects_independent_manifest_selector_and_catalog_drift() {
    658         let manifest = "[workspace.package]\nversion = \"0.1.0-alpha\"\nrust-version = \"1.99.0\"\nedition = \"2024\"\n";
    659         let toolchain = "[toolchain]\nchannel = \"1.99.0\"\n";
    660         let catalog = "schema = \"radroots.workspace.catalog.v2\"\narchitecture = \"radroots.crates.release.v2\"\nversion = \"0.1.0-alpha\"\nrust_version = \"1.99.0\"\nedition = \"2024\"\nresolver = \"3\"\n";
    661         validate_lib_compiler_inputs(
    662             manifest.as_bytes(),
    663             toolchain.as_bytes(),
    664             catalog.as_bytes(),
    665         )
    666         .expect("current compiler inputs");
    667         for (input, original) in [(0, manifest), (1, toolchain), (2, catalog)] {
    668             let old = original.replace("1.99.0", "1.97.1");
    669             let mut inputs = [
    670                 manifest.as_bytes(),
    671                 toolchain.as_bytes(),
    672                 catalog.as_bytes(),
    673             ];
    674             inputs[input] = old.as_bytes();
    675             assert!(validate_lib_compiler_inputs(inputs[0], inputs[1], inputs[2]).is_err());
    676         }
    677         for compiler in ["stable", "nightly", "1.99.1", "1.100.0"] {
    678             assert!(
    679                 validate_toolchain_bytes(toolchain.replace("1.99.0", compiler).as_bytes()).is_err()
    680             );
    681         }
    682         assert!(
    683             validate_lib_compiler_inputs(
    684                 manifest.replace("2024", "2021").as_bytes(),
    685                 toolchain.as_bytes(),
    686                 catalog.as_bytes()
    687             )
    688             .is_err()
    689         );
    690         assert!(
    691             validate_lib_compiler_inputs(
    692                 manifest.as_bytes(),
    693                 toolchain.as_bytes(),
    694                 catalog
    695                     .replace("resolver = \"3\"", "resolver = \"2\"")
    696                     .as_bytes()
    697             )
    698             .is_err()
    699         );
    700     }
    701 }