rhi

Coordinated trade for connected markets
git clone https://radroots.dev/git/rhi.git
Log | Files | Refs | README | LICENSE

canonical_source.rs (8347B)


      1 use std::{
      2     fs,
      3     path::{Path, PathBuf},
      4 };
      5 
      6 pub(super) fn source_root(
      7     manifest_root: &Path,
      8     build_top: Option<&Path>,
      9     input_source: Option<&Path>,
     10     store_root: &Path,
     11     service: &str,
     12     compiled_inputs: &[(&str, &[u8])],
     13 ) -> Result<PathBuf, &'static str> {
     14     let root = manifest_root
     15         .canonicalize()
     16         .map_err(|_| "manifest_root_unavailable")?;
     17     let Some(top) = build_top else {
     18         return Ok(root);
     19     };
     20     let top = top.canonicalize().map_err(|_| "build_top_unavailable")?;
     21     if root == top || !root.starts_with(&top) || root.join(".git").exists() {
     22         return Err("not_an_isolated_build_copy");
     23     }
     24     let source = input_source.ok_or("nix_input_source_missing")?;
     25     let metadata = fs::symlink_metadata(source).map_err(|_| "input_source_unavailable")?;
     26     if !metadata.is_dir() || metadata.file_type().is_symlink() || !metadata.permissions().readonly()
     27     {
     28         return Err("input_source_not_immutable_directory");
     29     }
     30     let source = source
     31         .canonicalize()
     32         .map_err(|_| "input_source_unavailable")?;
     33     let store = store_root
     34         .canonicalize()
     35         .map_err(|_| "store_root_unavailable")?;
     36     if source.parent() != Some(store.as_path())
     37         || source == root
     38         || source.starts_with(&top)
     39         || source.join(".git").exists()
     40     {
     41         return Err("input_source_scope_mismatch");
     42     }
     43     if fs::read(source.join(".radroots-consumer-root")).map_err(|_| "consumer_marker_missing")?
     44         != format!("{service}\n").as_bytes()
     45     {
     46         return Err("consumer_marker_mismatch");
     47     }
     48     for (relative, expected) in compiled_inputs {
     49         let relative = Path::new(relative);
     50         if relative.is_absolute()
     51             || relative
     52                 .components()
     53                 .any(|part| !matches!(part, std::path::Component::Normal(_)))
     54         {
     55             return Err("compiled_input_path_invalid");
     56         }
     57         let path = source.join(relative);
     58         let metadata = fs::symlink_metadata(&path).map_err(|_| "compiled_input_missing")?;
     59         if !metadata.is_file()
     60             || metadata.file_type().is_symlink()
     61             || !metadata.permissions().readonly()
     62             || metadata.len() != expected.len() as u64
     63             || fs::read(path).map_err(|_| "compiled_input_unavailable")? != *expected
     64         {
     65             return Err("compiled_input_mismatch");
     66         }
     67     }
     68     Ok(source)
     69 }
     70 
     71 #[cfg(unix)]
     72 mod tests {
     73     use super::*;
     74     use std::os::unix::fs::{PermissionsExt, symlink};
     75 
     76     struct Fixture {
     77         _directory: tempfile::TempDir,
     78         top: PathBuf,
     79         build: PathBuf,
     80         store: PathBuf,
     81         source: PathBuf,
     82     }
     83 
     84     const INPUTS: &[(&str, &[u8])] = &[
     85         ("Cargo.toml", b"manifest"),
     86         ("flake.lock", b"lock"),
     87         ("tests/guard.rs", b"guard"),
     88     ];
     89 
     90     impl Fixture {
     91         fn new() -> Self {
     92             let directory = tempfile::tempdir().unwrap();
     93             let top = directory.path().join("build_top");
     94             let build = top.join("source");
     95             let store = directory.path().join("store");
     96             let source = store.join("immutable_source");
     97             fs::create_dir_all(build.join("target")).unwrap();
     98             fs::create_dir_all(source.join("tests")).unwrap();
     99             fs::write(source.join(".radroots-consumer-root"), b"rhi\n").unwrap();
    100             for (name, bytes) in INPUTS {
    101                 let path = source.join(name);
    102                 fs::write(&path, bytes).unwrap();
    103                 fs::set_permissions(path, fs::Permissions::from_mode(0o444)).unwrap();
    104             }
    105             fs::set_permissions(&source, fs::Permissions::from_mode(0o555)).unwrap();
    106             Self {
    107                 _directory: directory,
    108                 top,
    109                 build,
    110                 store,
    111                 source,
    112             }
    113         }
    114 
    115         fn select(&self) -> Result<PathBuf, &'static str> {
    116             source_root(
    117                 &self.build,
    118                 Some(&self.top),
    119                 Some(&self.source),
    120                 &self.store,
    121                 "rhi",
    122                 INPUTS,
    123             )
    124         }
    125     }
    126 
    127     impl Drop for Fixture {
    128         fn drop(&mut self) {
    129             // Only this test's owned temporary input directory is made writable for cleanup.
    130             let _ = fs::set_permissions(&self.source, fs::Permissions::from_mode(0o755));
    131         }
    132     }
    133 
    134     #[test]
    135     fn native_context_keeps_the_working_tree_and_its_forbidden_artifacts_visible() {
    136         let fixture = Fixture::new();
    137         let selected = source_root(
    138             &fixture.build,
    139             None,
    140             Some(&fixture.source),
    141             &fixture.store,
    142             "rhi",
    143             INPUTS,
    144         )
    145         .unwrap();
    146         assert_eq!(selected, fixture.build.canonicalize().unwrap());
    147         assert!(selected.join("target").exists());
    148     }
    149 
    150     #[test]
    151     fn complete_isolated_context_selects_the_bound_immutable_input() {
    152         let fixture = Fixture::new();
    153         assert_eq!(
    154             fixture.select().unwrap(),
    155             fixture.source.canonicalize().unwrap()
    156         );
    157         assert!(fixture.build.join("target").exists());
    158         assert!(!fixture.select().unwrap().join("target").exists());
    159     }
    160 
    161     #[test]
    162     fn incomplete_or_git_context_cannot_select_another_source() {
    163         let fixture = Fixture::new();
    164         assert!(
    165             source_root(
    166                 &fixture.build,
    167                 Some(&fixture.top),
    168                 None,
    169                 &fixture.store,
    170                 "rhi",
    171                 INPUTS
    172             )
    173             .is_err()
    174         );
    175         assert!(
    176             source_root(
    177                 &fixture.top,
    178                 Some(&fixture.top),
    179                 Some(&fixture.source),
    180                 &fixture.store,
    181                 "rhi",
    182                 INPUTS
    183             )
    184             .is_err()
    185         );
    186         assert!(
    187             source_root(
    188                 &fixture.store,
    189                 Some(&fixture.top),
    190                 Some(&fixture.source),
    191                 &fixture.store,
    192                 "rhi",
    193                 INPUTS
    194             )
    195             .is_err()
    196         );
    197         fs::write(fixture.build.join(".git"), b"gitdir: fixture").unwrap();
    198         assert_eq!(fixture.select(), Err("not_an_isolated_build_copy"));
    199     }
    200 
    201     #[test]
    202     fn wrong_store_mutability_owner_and_compiled_bytes_are_refused() {
    203         let fixture = Fixture::new();
    204         assert!(
    205             source_root(
    206                 &fixture.build,
    207                 Some(&fixture.top),
    208                 Some(&fixture.source),
    209                 &fixture.top,
    210                 "rhi",
    211                 INPUTS
    212             )
    213             .is_err()
    214         );
    215         assert!(
    216             source_root(
    217                 &fixture.build,
    218                 Some(&fixture.top),
    219                 Some(&fixture.source),
    220                 &fixture.store,
    221                 "myc",
    222                 INPUTS
    223             )
    224             .is_err()
    225         );
    226         assert!(
    227             source_root(
    228                 &fixture.build,
    229                 Some(&fixture.top),
    230                 Some(&fixture.source),
    231                 &fixture.store,
    232                 "rhi",
    233                 &[("Cargo.toml", b"changed")]
    234             )
    235             .is_err()
    236         );
    237         fs::set_permissions(&fixture.source, fs::Permissions::from_mode(0o755)).unwrap();
    238         assert_eq!(
    239             fixture.select(),
    240             Err("input_source_not_immutable_directory")
    241         );
    242     }
    243 
    244     #[test]
    245     fn linked_input_and_extra_canonical_artifacts_are_not_hidden() {
    246         let fixture = Fixture::new();
    247         let linked = fixture.store.join("linked_source");
    248         symlink(&fixture.source, &linked).unwrap();
    249         assert!(
    250             source_root(
    251                 &fixture.build,
    252                 Some(&fixture.top),
    253                 Some(&linked),
    254                 &fixture.store,
    255                 "rhi",
    256                 INPUTS
    257             )
    258             .is_err()
    259         );
    260         fs::set_permissions(&fixture.source, fs::Permissions::from_mode(0o755)).unwrap();
    261         fs::create_dir(fixture.source.join("target")).unwrap();
    262         fs::set_permissions(&fixture.source, fs::Permissions::from_mode(0o555)).unwrap();
    263         assert!(fixture.select().unwrap().join("target").exists());
    264     }
    265 }