rhi

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

main.rs (71964B)


      1 #![forbid(unsafe_code)]
      2 
      3 mod rshr_202_step_301_gate;
      4 mod rshr_202_step_301_platform;
      5 
      6 use std::{
      7     collections::{BTreeMap, BTreeSet},
      8     env, fmt, fs,
      9     io::{Read as _, Write as _},
     10     path::{Path, PathBuf},
     11     process::{Command, Stdio},
     12 };
     13 
     14 use flate2::{Compression, GzBuilder};
     15 use serde::{Deserialize, Serialize};
     16 use sha2::{Digest as _, Sha256};
     17 use tar::{Builder as TarBuilder, Header as TarHeader};
     18 use tempfile::{NamedTempFile, TempDir};
     19 
     20 const SERVICE: &str = "rhi";
     21 const VERSION: &str = "0.1.0";
     22 const REPOSITORY: &str = "https://github.com/radrootslabs/rhi";
     23 const RUST_VERSION: &str = "1.99.0";
     24 const HOST_FEATURE_PROFILE: &str = "service-host";
     25 const RADROOTS_DEPENDENCIES: [&str; 13] = [
     26     "radroots_event",
     27     "radroots_event_codec",
     28     "radroots_nostr",
     29     "radroots_protocol",
     30     "radroots_runtime_paths",
     31     "radroots_secrets",
     32     "radroots_service_host",
     33     "radroots_service_sqlite",
     34     "radroots_storage",
     35     "radroots_trade",
     36     "radroots_transport",
     37     "radroots_transport_nostr",
     38     "radroots_transport_nostr_native",
     39 ];
     40 const SOURCE_LOCK: &str = "radroots.service.source_lock.v4.toml";
     41 const CONFIG_EXAMPLE: &str = "contracts/services_hardening/config.v1.example.toml";
     42 const CONFIG_SCHEMA: &str = "contracts/services_hardening/config.v1.schema.json";
     43 const SYSTEMD_UNIT: &str = "packaging/systemd/rhi@.service";
     44 const SUPPORTED_TARGETS: [&str; 2] = ["aarch64-unknown-linux-gnu", "x86_64-unknown-linux-gnu"];
     45 const OUTPUT_NAMES: [&str; 12] = [
     46     "LICENSE",
     47     "SHA256SUMS",
     48     "THIRD-PARTY-NOTICES.txt",
     49     "artifact-manifest.v1.json",
     50     "binary.tar.gz",
     51     "config.example.toml",
     52     "config.schema.json",
     53     "provenance-input.v1.json",
     54     SOURCE_LOCK,
     55     "sbom.cdx.json",
     56     "service-source.tar.gz",
     57     "systemd.service",
     58 ];
     59 const MAX_TEXT_BYTES: u64 = 1_048_576;
     60 const MAX_SOURCE_LOCK_BYTES: u64 = 16_384;
     61 const MAX_DOCUMENT_BYTES: u64 = 16_777_216;
     62 const MAX_METADATA_BYTES: u64 = 33_554_432;
     63 const MAX_BINARY_BYTES: u64 = 536_870_912;
     64 const MAX_SOURCE_ARCHIVE_BYTES: u64 = 1_073_741_824;
     65 const MAX_TRACKED_FILES: usize = 4_096;
     66 const MAX_PACKAGES: usize = 8_192;
     67 const COPY_BUFFER_BYTES: usize = 65_536;
     68 const SECRET_PATTERN_PARTS: [(&[u8], &[u8]); 7] = [
     69     (b"-----BEGIN PRIVATE ", b"KEY-----"),
     70     (b"-----BEGIN RSA PRIVATE ", b"KEY-----"),
     71     (b"-----BEGIN EC PRIVATE ", b"KEY-----"),
     72     (b"-----BEGIN OPENSSH PRIVATE ", b"KEY-----"),
     73     (b"github_", b"pat_"),
     74     (b"gh", b"p_"),
     75     (b"xo", b"xb-"),
     76 ];
     77 
     78 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     79 enum Mode {
     80     Check,
     81     Write,
     82 }
     83 
     84 #[derive(Debug)]
     85 struct NativeReleaseArgs {
     86     mode: Mode,
     87     target: String,
     88     binary: PathBuf,
     89     output: PathBuf,
     90     source_date_epoch: u32,
     91 }
     92 
     93 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     94 enum ReleaseError {
     95     InvalidArguments,
     96     InvalidSource,
     97     DirtySource,
     98     InvalidBinary,
     99     InvalidOutput,
    100     InvalidMetadata,
    101     InvalidSourceLock,
    102     ProtectedMaterial,
    103     StaleOutput,
    104     Generation,
    105 }
    106 
    107 impl ReleaseError {
    108     const fn code(self) -> &'static str {
    109         match self {
    110             Self::InvalidArguments => "invalid_arguments",
    111             Self::InvalidSource => "invalid_source",
    112             Self::DirtySource => "dirty_source",
    113             Self::InvalidBinary => "invalid_binary",
    114             Self::InvalidOutput => "invalid_output",
    115             Self::InvalidMetadata => "invalid_metadata",
    116             Self::InvalidSourceLock => "invalid_source_lock",
    117             Self::ProtectedMaterial => "protected_material_detected",
    118             Self::StaleOutput => "stale_output",
    119             Self::Generation => "generation_failure",
    120         }
    121     }
    122 }
    123 
    124 impl fmt::Display for ReleaseError {
    125     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    126         formatter.write_str(match self {
    127             Self::InvalidArguments => "native release arguments are invalid",
    128             Self::InvalidSource => "native release source is invalid",
    129             Self::DirtySource => "native release source is not an exact clean revision",
    130             Self::InvalidBinary => "native release binary is invalid",
    131             Self::InvalidOutput => "native release output is invalid",
    132             Self::InvalidMetadata => "native release metadata is invalid",
    133             Self::InvalidSourceLock => "native release source lock is invalid",
    134             Self::ProtectedMaterial => "native release input contains protected material",
    135             Self::StaleOutput => "native release artifact set is absent or stale",
    136             Self::Generation => "native release artifacts could not be generated",
    137         })
    138     }
    139 }
    140 
    141 impl std::error::Error for ReleaseError {}
    142 
    143 #[derive(Clone, Debug, Deserialize)]
    144 struct CargoMetadata {
    145     packages: Vec<CargoPackage>,
    146     workspace_members: Vec<String>,
    147     resolve: Option<CargoResolve>,
    148 }
    149 
    150 #[derive(Clone, Debug, Deserialize)]
    151 struct CargoPackage {
    152     id: String,
    153     name: String,
    154     version: String,
    155     source: Option<String>,
    156     checksum: Option<String>,
    157     license: Option<String>,
    158 }
    159 
    160 #[derive(Clone, Debug, Deserialize)]
    161 struct CargoResolve {
    162     nodes: Vec<CargoNode>,
    163 }
    164 
    165 #[derive(Clone, Debug, Deserialize)]
    166 struct CargoNode {
    167     id: String,
    168     dependencies: Vec<String>,
    169 }
    170 
    171 #[derive(Clone, Debug, Deserialize, Serialize)]
    172 #[serde(deny_unknown_fields)]
    173 struct SourceLock {
    174     schema: String,
    175     contract_version: u32,
    176     service: String,
    177     repository: String,
    178     revision: String,
    179     architecture: String,
    180     workspace_catalog_sha256: String,
    181     version: String,
    182     source_archive_sha256: String,
    183     source_archive_contract: SourceArchiveContract,
    184     cargo_lock_sha256: String,
    185     rust_version: String,
    186     host_feature_profile: String,
    187     nix: NixEvidence,
    188     artifact_contract: ArtifactContract,
    189     sqlite: SqliteContract,
    190     contract_versions: ContractVersions,
    191 }
    192 
    193 #[derive(Clone, Debug, Deserialize, Serialize)]
    194 #[serde(deny_unknown_fields)]
    195 struct NixEvidence {
    196     material: String,
    197     lib_revision: String,
    198     supported_systems: Vec<String>,
    199     public_input_lock: PublicInputLock,
    200     parent_result: ParentResult,
    201 }
    202 
    203 #[derive(Clone, Debug, Deserialize, Serialize)]
    204 #[serde(deny_unknown_fields)]
    205 struct PublicInputLock {
    206     path: String,
    207     sha256: String,
    208     binding: String,
    209     mutable_reference: String,
    210     lib_input: String,
    211 }
    212 
    213 #[derive(Clone, Debug, Deserialize, Serialize)]
    214 #[serde(deny_unknown_fields)]
    215 struct ParentResult {
    216     embedded_in_public_input_lock: bool,
    217     embedded_in_source_lock: bool,
    218     storage: String,
    219 }
    220 
    221 #[derive(Clone, Debug, Deserialize, Serialize)]
    222 #[serde(deny_unknown_fields)]
    223 struct SourceArchiveContract {
    224     binding: String,
    225     format: String,
    226     compression: String,
    227     compression_timestamp: String,
    228     entry_order: String,
    229     path_prefix: String,
    230     file_mode: String,
    231     uid: u32,
    232     gid: u32,
    233     uname: String,
    234     gname: String,
    235     mtime: String,
    236     pax_headers: String,
    237     directory_entries: String,
    238     symlinks: String,
    239     hardlinks: String,
    240     submodules: String,
    241     trailer: String,
    242 }
    243 
    244 #[derive(Clone, Debug, Deserialize, Serialize)]
    245 #[serde(deny_unknown_fields)]
    246 struct ArtifactContract {
    247     path: String,
    248     sha256: String,
    249     binding: String,
    250 }
    251 
    252 #[derive(Clone, Debug, Deserialize, Serialize)]
    253 #[serde(deny_unknown_fields)]
    254 struct SqliteContract {
    255     high_level_authority: String,
    256     second_pool_connection_query_transaction_migration_authority: String,
    257     incremental_backup_adapter: String,
    258     native_linkage_count: u32,
    259 }
    260 
    261 #[derive(Clone, Debug, Deserialize, Serialize)]
    262 #[serde(deny_unknown_fields)]
    263 struct ContractVersions {
    264     config: u32,
    265     state: u32,
    266     admin: u32,
    267     status: u32,
    268     provider: u32,
    269 }
    270 
    271 #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
    272 struct ArtifactRecord {
    273     path: String,
    274     byte_length: u64,
    275     sha256: String,
    276 }
    277 
    278 #[derive(Debug, Serialize)]
    279 struct ArtifactManifest {
    280     schema: &'static str,
    281     contract_version: u32,
    282     service: &'static str,
    283     version: &'static str,
    284     target: String,
    285     source_date_epoch: u32,
    286     service_repository: &'static str,
    287     service_revision: String,
    288     lib_repository: String,
    289     lib_revision: String,
    290     rust_version: &'static str,
    291     host_feature_profile: &'static str,
    292     contract_versions: ContractVersions,
    293     protected_material_included: bool,
    294     nix_qualified: bool,
    295     oci_included: bool,
    296     artifacts: Vec<ArtifactRecord>,
    297 }
    298 
    299 #[derive(Debug, Serialize)]
    300 struct ProvenanceInput {
    301     schema: &'static str,
    302     contract_version: u32,
    303     predicate_type: &'static str,
    304     build_type: &'static str,
    305     builder_id: &'static str,
    306     service: &'static str,
    307     version: &'static str,
    308     target: String,
    309     source_date_epoch: u32,
    310     service_repository: &'static str,
    311     service_revision: String,
    312     lib_repository: String,
    313     lib_revision: String,
    314     source_lock_sha256: String,
    315     manifest_sha256: String,
    316     subjects: Vec<ArtifactRecord>,
    317     signing_required: bool,
    318     signed: bool,
    319 }
    320 
    321 #[derive(Debug, Serialize)]
    322 struct CycloneDxBom {
    323     #[serde(rename = "bomFormat")]
    324     bom_format: &'static str,
    325     #[serde(rename = "specVersion")]
    326     spec_version: &'static str,
    327     version: u32,
    328     metadata: SbomMetadata,
    329     components: Vec<SbomComponent>,
    330     dependencies: Vec<SbomDependency>,
    331 }
    332 
    333 #[derive(Debug, Serialize)]
    334 struct SbomMetadata {
    335     component: SbomRootComponent,
    336 }
    337 
    338 #[derive(Debug, Serialize)]
    339 struct SbomRootComponent {
    340     #[serde(rename = "type")]
    341     component_type: &'static str,
    342     name: &'static str,
    343     version: &'static str,
    344 }
    345 
    346 #[derive(Debug, Serialize)]
    347 struct SbomComponent {
    348     #[serde(rename = "type")]
    349     component_type: &'static str,
    350     #[serde(rename = "bom-ref")]
    351     bom_ref: String,
    352     name: String,
    353     version: String,
    354     #[serde(skip_serializing_if = "Option::is_none")]
    355     licenses: Option<Vec<SbomLicenseChoice>>,
    356     properties: Vec<SbomProperty>,
    357 }
    358 
    359 #[derive(Debug, Serialize)]
    360 struct SbomLicenseChoice {
    361     expression: String,
    362 }
    363 
    364 #[derive(Debug, Serialize)]
    365 struct SbomProperty {
    366     name: &'static str,
    367     value: String,
    368 }
    369 
    370 #[derive(Debug, Serialize)]
    371 struct SbomDependency {
    372     #[serde(rename = "ref")]
    373     reference: String,
    374     #[serde(rename = "dependsOn")]
    375     depends_on: Vec<String>,
    376 }
    377 
    378 fn main() {
    379     if let Err(error) = run_main() {
    380         eprintln!("{}: {}", error.code(), error);
    381         std::process::exit(1);
    382     }
    383 }
    384 
    385 fn run_main() -> Result<(), ReleaseError> {
    386     let mut arguments = env::args().skip(1);
    387     match arguments.next().as_deref() {
    388         Some("native-release") => {
    389             let args = parse_native_release_args(arguments.collect())?;
    390             native_release(&workspace_root(), &args)
    391         }
    392         Some("rshr-step-301-gate") => {
    393             let args = parse_rshr_step_301_gate_args(arguments.collect())?;
    394             rshr_202_step_301_gate::run(args).map_err(|_| ReleaseError::Generation)
    395         }
    396         Some("rshr-step-301-platform-probe") if arguments.next().is_none() => {
    397             rshr_202_step_301_platform::run().map_err(|_| ReleaseError::Generation)
    398         }
    399         _ => Err(ReleaseError::InvalidArguments),
    400     }
    401 }
    402 
    403 fn parse_rshr_step_301_gate_args(
    404     values: Vec<String>,
    405 ) -> Result<rshr_202_step_301_gate::Arguments, ReleaseError> {
    406     let mut step = None;
    407     let mut check_id = None;
    408     let mut source_revision = None;
    409     let mut source_tree = None;
    410     let mut candidate_digest = None;
    411     let mut platform = None;
    412     let mut execution_request_sha256 = None;
    413     for value in values {
    414         let (name, value) = value
    415             .split_once('=')
    416             .ok_or(ReleaseError::InvalidArguments)?;
    417         let slot = match name {
    418             "--check-id" => &mut check_id,
    419             "--source-revision" => &mut source_revision,
    420             "--source-tree" => &mut source_tree,
    421             "--candidate-digest" => &mut candidate_digest,
    422             "--platform" => &mut platform,
    423             "--execution-request-sha256" => &mut execution_request_sha256,
    424             "--step" => {
    425                 let parsed = value
    426                     .parse::<u16>()
    427                     .map_err(|_| ReleaseError::InvalidArguments)?;
    428                 if step.replace(parsed).is_some() {
    429                     return Err(ReleaseError::InvalidArguments);
    430                 }
    431                 continue;
    432             }
    433             _ => return Err(ReleaseError::InvalidArguments),
    434         };
    435         if value.is_empty() || slot.replace(value.to_owned()).is_some() {
    436             return Err(ReleaseError::InvalidArguments);
    437         }
    438     }
    439     Ok(rshr_202_step_301_gate::Arguments {
    440         step: step.ok_or(ReleaseError::InvalidArguments)?,
    441         check_id: check_id.ok_or(ReleaseError::InvalidArguments)?,
    442         source_revision: source_revision.ok_or(ReleaseError::InvalidArguments)?,
    443         source_tree: source_tree.ok_or(ReleaseError::InvalidArguments)?,
    444         candidate_digest: candidate_digest.ok_or(ReleaseError::InvalidArguments)?,
    445         platform: platform.ok_or(ReleaseError::InvalidArguments)?,
    446         execution_request_sha256: execution_request_sha256.ok_or(ReleaseError::InvalidArguments)?,
    447     })
    448 }
    449 
    450 fn workspace_root() -> PathBuf {
    451     Path::new(env!("CARGO_MANIFEST_DIR"))
    452         .parent()
    453         .and_then(Path::parent)
    454         .expect("xtask is nested at tools/xtask")
    455         .to_path_buf()
    456 }
    457 
    458 fn parse_native_release_args(values: Vec<String>) -> Result<NativeReleaseArgs, ReleaseError> {
    459     let mut mode = None;
    460     let mut target = None;
    461     let mut binary = None;
    462     let mut output = None;
    463     let mut source_date_epoch = None;
    464     let mut index = 0;
    465     while index < values.len() {
    466         let value = values
    467             .get(index + 1)
    468             .ok_or(ReleaseError::InvalidArguments)?;
    469         match values[index].as_str() {
    470             "--mode" => {
    471                 let parsed = match value.as_str() {
    472                     "check" => Mode::Check,
    473                     "write" => Mode::Write,
    474                     _ => return Err(ReleaseError::InvalidArguments),
    475                 };
    476                 if mode.replace(parsed).is_some() {
    477                     return Err(ReleaseError::InvalidArguments);
    478                 }
    479             }
    480             "--target" => {
    481                 if target.replace(value.clone()).is_some() {
    482                     return Err(ReleaseError::InvalidArguments);
    483                 }
    484             }
    485             "--binary" => {
    486                 if binary.replace(PathBuf::from(value)).is_some() {
    487                     return Err(ReleaseError::InvalidArguments);
    488                 }
    489             }
    490             "--output" => {
    491                 if output.replace(PathBuf::from(value)).is_some() {
    492                     return Err(ReleaseError::InvalidArguments);
    493                 }
    494             }
    495             "--source-date-epoch" => {
    496                 let parsed = value
    497                     .parse::<u32>()
    498                     .ok()
    499                     .filter(|value| *value > 0)
    500                     .ok_or(ReleaseError::InvalidArguments)?;
    501                 if source_date_epoch.replace(parsed).is_some() {
    502                     return Err(ReleaseError::InvalidArguments);
    503                 }
    504             }
    505             _ => return Err(ReleaseError::InvalidArguments),
    506         }
    507         index += 2;
    508     }
    509     let args = NativeReleaseArgs {
    510         mode: mode.ok_or(ReleaseError::InvalidArguments)?,
    511         target: target.ok_or(ReleaseError::InvalidArguments)?,
    512         binary: binary.ok_or(ReleaseError::InvalidArguments)?,
    513         output: output.ok_or(ReleaseError::InvalidArguments)?,
    514         source_date_epoch: source_date_epoch.ok_or(ReleaseError::InvalidArguments)?,
    515     };
    516     if !SUPPORTED_TARGETS.contains(&args.target.as_str())
    517         || !args.binary.is_absolute()
    518         || !args.output.is_absolute()
    519     {
    520         return Err(ReleaseError::InvalidArguments);
    521     }
    522     Ok(args)
    523 }
    524 
    525 fn native_release(root: &Path, args: &NativeReleaseArgs) -> Result<(), ReleaseError> {
    526     validate_source_root(root)?;
    527     validate_clean_source(root)?;
    528     let initial_head = git_capture(root, &["rev-parse", "HEAD"], 128)?;
    529     let initial_head = exact_line(&initial_head).ok_or(ReleaseError::InvalidSource)?;
    530     if !lower_hex(initial_head, 40) {
    531         return Err(ReleaseError::InvalidSource);
    532     }
    533     validate_binary(&args.binary, &args.target)?;
    534     validate_output_path(root, &args.output)?;
    535     let source_lock = read_source_lock(root)?;
    536     let metadata = cargo_metadata(root)?;
    537     validate_metadata(&metadata)?;
    538 
    539     let parent = args.output.parent().ok_or(ReleaseError::InvalidOutput)?;
    540     let staging = tempfile::Builder::new()
    541         .prefix(".rhi-native-release-")
    542         .tempdir_in(parent)
    543         .map_err(|_| ReleaseError::Generation)?;
    544     let stage = staging.path();
    545     set_directory_permissions(stage)?;
    546 
    547     copy_bounded(
    548         &root.join("LICENSE"),
    549         &stage.join("LICENSE"),
    550         MAX_TEXT_BYTES,
    551     )?;
    552     copy_bounded(
    553         &root.join(CONFIG_EXAMPLE),
    554         &stage.join("config.example.toml"),
    555         MAX_TEXT_BYTES,
    556     )?;
    557     copy_bounded(
    558         &root.join(CONFIG_SCHEMA),
    559         &stage.join("config.schema.json"),
    560         MAX_TEXT_BYTES,
    561     )?;
    562     copy_bounded(
    563         &root.join(SYSTEMD_UNIT),
    564         &stage.join("systemd.service"),
    565         MAX_TEXT_BYTES,
    566     )?;
    567     copy_bounded(
    568         &root.join(SOURCE_LOCK),
    569         &stage.join(SOURCE_LOCK),
    570         MAX_SOURCE_LOCK_BYTES,
    571     )?;
    572     create_binary_archive(
    573         &args.binary,
    574         &stage.join("binary.tar.gz"),
    575         &args.target,
    576         args.source_date_epoch,
    577     )?;
    578     create_source_archive(
    579         root,
    580         &stage.join("service-source.tar.gz"),
    581         args.source_date_epoch,
    582     )?;
    583     let (sbom, notices) = supply_chain_documents(&metadata)?;
    584     write_json(&stage.join("sbom.cdx.json"), &sbom)?;
    585     write_generated(&stage.join("THIRD-PARTY-NOTICES.txt"), notices.as_bytes())?;
    586 
    587     let source_lock_sha256 = hash_regular(&stage.join(SOURCE_LOCK), MAX_SOURCE_LOCK_BYTES)?.sha256;
    588     let payload = inventory_records(stage)?;
    589     let manifest = ArtifactManifest {
    590         schema: "radroots.service.release-artifacts.v1",
    591         contract_version: 1,
    592         service: SERVICE,
    593         version: VERSION,
    594         target: args.target.clone(),
    595         source_date_epoch: args.source_date_epoch,
    596         service_repository: REPOSITORY,
    597         service_revision: initial_head.to_owned(),
    598         lib_repository: source_lock.repository.clone(),
    599         lib_revision: source_lock.revision.clone(),
    600         rust_version: RUST_VERSION,
    601         host_feature_profile: HOST_FEATURE_PROFILE,
    602         contract_versions: source_lock.contract_versions.clone(),
    603         protected_material_included: false,
    604         nix_qualified: false,
    605         oci_included: false,
    606         artifacts: payload,
    607     };
    608     write_json(&stage.join("artifact-manifest.v1.json"), &manifest)?;
    609     let manifest_sha256 =
    610         hash_regular(&stage.join("artifact-manifest.v1.json"), MAX_DOCUMENT_BYTES)?.sha256;
    611     let provenance = ProvenanceInput {
    612         schema: "radroots.service.provenance-input.v1",
    613         contract_version: 1,
    614         predicate_type: "https://slsa.dev/provenance/v1",
    615         build_type: "https://radroots.dev/contracts/rhi-native-release/v3",
    616         builder_id: "https://radroots.dev/builders/rhi-native-release/v3",
    617         service: SERVICE,
    618         version: VERSION,
    619         target: args.target.clone(),
    620         source_date_epoch: args.source_date_epoch,
    621         service_repository: REPOSITORY,
    622         service_revision: initial_head.to_owned(),
    623         lib_repository: source_lock.repository,
    624         lib_revision: source_lock.revision,
    625         source_lock_sha256,
    626         manifest_sha256,
    627         subjects: inventory_records(stage)?,
    628         signing_required: true,
    629         signed: false,
    630     };
    631     write_json(&stage.join("provenance-input.v1.json"), &provenance)?;
    632     write_checksums(stage)?;
    633     validate_exact_inventory(stage)?;
    634     let expected = inventory_records(stage)?;
    635 
    636     validate_clean_source(root)?;
    637     if exact_line(&git_capture(root, &["rev-parse", "HEAD"], 128)?) != Some(initial_head) {
    638         return Err(ReleaseError::DirtySource);
    639     }
    640 
    641     if args.output.exists() {
    642         compare_output(&args.output, &expected)?;
    643         sync_directory(&args.output)?;
    644         sync_directory(parent)?;
    645         return Ok(());
    646     }
    647     if args.mode == Mode::Check {
    648         return Err(ReleaseError::StaleOutput);
    649     }
    650     sync_directory(stage)?;
    651     publish_directory(stage, &args.output)?;
    652     sync_directory(parent)?;
    653     compare_output(&args.output, &expected)
    654 }
    655 
    656 fn validate_source_root(root: &Path) -> Result<(), ReleaseError> {
    657     if !root.is_absolute()
    658         || fs::symlink_metadata(root)
    659             .map(|metadata| metadata.file_type().is_symlink() || !metadata.is_dir())
    660             .unwrap_or(true)
    661         || root.join("docs").exists()
    662         || root.join(".github").exists()
    663         || root.join(".act").exists()
    664     {
    665         return Err(ReleaseError::InvalidSource);
    666     }
    667     for required in [
    668         "Cargo.toml",
    669         "Cargo.lock",
    670         "LICENSE",
    671         SOURCE_LOCK,
    672         CONFIG_EXAMPLE,
    673         CONFIG_SCHEMA,
    674         SYSTEMD_UNIT,
    675     ] {
    676         validate_regular(
    677             &root.join(required),
    678             MAX_DOCUMENT_BYTES,
    679             ReleaseError::InvalidSource,
    680         )?;
    681     }
    682     Ok(())
    683 }
    684 
    685 fn validate_clean_source(root: &Path) -> Result<(), ReleaseError> {
    686     for arguments in [
    687         &["diff", "--quiet", "--"] as &[&str],
    688         &["diff", "--cached", "--quiet", "--"],
    689     ] {
    690         let status = Command::new("git")
    691             .args(arguments)
    692             .current_dir(root)
    693             .stdin(Stdio::null())
    694             .stdout(Stdio::null())
    695             .stderr(Stdio::null())
    696             .status()
    697             .map_err(|_| ReleaseError::DirtySource)?;
    698         if !status.success() {
    699             return Err(ReleaseError::DirtySource);
    700         }
    701     }
    702     let untracked = command_capture_bounded(
    703         Command::new("git")
    704             .args(["ls-files", "--others", "--exclude-standard", "-z"])
    705             .current_dir(root),
    706         1,
    707         ReleaseError::DirtySource,
    708     )?;
    709     if !untracked.is_empty() {
    710         return Err(ReleaseError::DirtySource);
    711     }
    712     Ok(())
    713 }
    714 
    715 fn validate_binary(path: &Path, target: &str) -> Result<(), ReleaseError> {
    716     open_binary(path, target).map(|_| ())
    717 }
    718 
    719 fn validate_output_path(root: &Path, output: &Path) -> Result<(), ReleaseError> {
    720     let parent = output.parent().ok_or(ReleaseError::InvalidOutput)?;
    721     let canonical_root = fs::canonicalize(root).map_err(|_| ReleaseError::InvalidSource)?;
    722     let canonical_parent = fs::canonicalize(parent).map_err(|_| ReleaseError::InvalidOutput)?;
    723     if output == Path::new("/")
    724         || output.components().any(|component| {
    725             matches!(
    726                 component,
    727                 std::path::Component::CurDir
    728                     | std::path::Component::ParentDir
    729                     | std::path::Component::Prefix(_)
    730             )
    731         })
    732         || canonical_parent.starts_with(canonical_root)
    733         || fs::symlink_metadata(parent)
    734             .map(|metadata| metadata.file_type().is_symlink() || !metadata.is_dir())
    735             .unwrap_or(true)
    736         || output
    737             .file_name()
    738             .and_then(|value| value.to_str())
    739             .is_none_or(|value| value.is_empty() || value == "." || value == "..")
    740     {
    741         return Err(ReleaseError::InvalidOutput);
    742     }
    743     match fs::symlink_metadata(output) {
    744         Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
    745             return Err(ReleaseError::InvalidOutput);
    746         }
    747         Ok(_) => {}
    748         Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
    749         Err(_) => return Err(ReleaseError::InvalidOutput),
    750     }
    751     Ok(())
    752 }
    753 
    754 fn read_source_lock(root: &Path) -> Result<SourceLock, ReleaseError> {
    755     for predecessor in [
    756         "radroots.service.source-lock.v1.toml",
    757         "radroots.service.source-lock.v2.toml",
    758         "radroots.service.source-lock.v3.toml",
    759     ] {
    760         match fs::symlink_metadata(root.join(predecessor)) {
    761             Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
    762             _ => return Err(ReleaseError::InvalidSourceLock),
    763         }
    764     }
    765     let bytes = read_bounded(
    766         &root.join(SOURCE_LOCK),
    767         MAX_SOURCE_LOCK_BYTES,
    768         ReleaseError::InvalidSourceLock,
    769     )?;
    770     let text = std::str::from_utf8(&bytes).map_err(|_| ReleaseError::InvalidSourceLock)?;
    771     let lock: SourceLock = toml::from_str(text).map_err(|_| ReleaseError::InvalidSourceLock)?;
    772     if toml::to_string(&lock).map_err(|_| ReleaseError::InvalidSourceLock)? != text {
    773         return Err(ReleaseError::InvalidSourceLock);
    774     }
    775     let cargo_lock = hash_regular(&root.join("Cargo.lock"), MAX_DOCUMENT_BYTES)?;
    776     let flake_lock = hash_regular(&root.join("flake.lock"), MAX_DOCUMENT_BYTES)?;
    777     let artifact_contract = hash_regular(
    778         &root.join("contracts/release/rhi-artifact-contract.v4.json"),
    779         MAX_DOCUMENT_BYTES,
    780     )?;
    781     let revisions = cargo_dependency_revisions(root)?;
    782     if lock.schema != "radroots.service.source_lock.v4"
    783         || lock.contract_version != 4
    784         || lock.service != SERVICE
    785         || lock.repository != "https://github.com/radrootslabs/lib"
    786         || !lower_hex(&lock.revision, 40)
    787         || lock.architecture != "radroots.crates.release.v2"
    788         || !lower_hex(&lock.workspace_catalog_sha256, 64)
    789         || lock.version != "0.1.0-alpha"
    790         || !lower_hex(&lock.source_archive_sha256, 64)
    791         || lock.cargo_lock_sha256 != cargo_lock.sha256
    792         || lock.rust_version != RUST_VERSION
    793         || lock.host_feature_profile != HOST_FEATURE_PROFILE
    794         || lock.source_archive_contract.binding
    795             != "sha256_of_canonical_exact_lib_revision_tree_archive"
    796         || lock.source_archive_contract.format != "ustar"
    797         || lock.source_archive_contract.compression != "none"
    798         || lock.source_archive_contract.compression_timestamp != "not_applicable"
    799         || lock.source_archive_contract.entry_order != "bytewise_git_path"
    800         || lock.source_archive_contract.path_prefix != "none"
    801         || lock.source_archive_contract.file_mode != "git_index_100644_or_100755"
    802         || lock.source_archive_contract.uid != 0
    803         || lock.source_archive_contract.gid != 0
    804         || !lock.source_archive_contract.uname.is_empty()
    805         || !lock.source_archive_contract.gname.is_empty()
    806         || lock.source_archive_contract.mtime != "lib_revision_commit_timestamp"
    807         || lock.source_archive_contract.pax_headers != "forbidden"
    808         || lock.source_archive_contract.directory_entries != "omitted"
    809         || lock.source_archive_contract.symlinks != "forbidden"
    810         || lock.source_archive_contract.hardlinks != "forbidden"
    811         || lock.source_archive_contract.submodules != "forbidden"
    812         || lock.source_archive_contract.trailer != "two_zero_blocks"
    813         || lock.nix.material != "bound"
    814         || lock.nix.lib_revision != lock.revision
    815         || lock.nix.supported_systems != ["aarch64-darwin", "x86_64-linux"]
    816         || lock.nix.public_input_lock.path != "flake.lock"
    817         || lock.nix.public_input_lock.sha256 != flake_lock.sha256
    818         || lock.nix.public_input_lock.binding != "exact_regular_file_bytes"
    819         || lock.nix.public_input_lock.mutable_reference != "forbidden"
    820         || lock.nix.public_input_lock.lib_input != "lib"
    821         || lock.nix.parent_result.embedded_in_public_input_lock
    822         || lock.nix.parent_result.embedded_in_source_lock
    823         || lock.nix.parent_result.storage != "separate_source_scoped_execution_evidence"
    824         || lock.artifact_contract.path != "contracts/release/rhi-artifact-contract.v4.json"
    825         || lock.artifact_contract.sha256 != artifact_contract.sha256
    826         || lock.artifact_contract.binding != "exact_regular_file_bytes_in_same_source_revision"
    827         || lock.sqlite.high_level_authority != "sqlx_only"
    828         || lock
    829             .sqlite
    830             .second_pool_connection_query_transaction_migration_authority
    831             != "forbidden"
    832         || lock.sqlite.incremental_backup_adapter != "sealed_native_sqlx_owned_locked_handle_only"
    833         || lock.sqlite.native_linkage_count != 1
    834         || revisions != BTreeSet::from([lock.revision.clone()])
    835         || [
    836             lock.contract_versions.config,
    837             lock.contract_versions.state,
    838             lock.contract_versions.admin,
    839             lock.contract_versions.status,
    840             lock.contract_versions.provider,
    841         ]
    842         .contains(&0)
    843     {
    844         return Err(ReleaseError::InvalidSourceLock);
    845     }
    846     Ok(lock)
    847 }
    848 
    849 fn cargo_dependency_revisions(root: &Path) -> Result<BTreeSet<String>, ReleaseError> {
    850     let bytes = read_bounded(
    851         &root.join("Cargo.toml"),
    852         MAX_TEXT_BYTES,
    853         ReleaseError::InvalidSourceLock,
    854     )?;
    855     let value: toml::Value =
    856         toml::from_str(std::str::from_utf8(&bytes).map_err(|_| ReleaseError::InvalidSourceLock)?)
    857             .map_err(|_| ReleaseError::InvalidSourceLock)?;
    858     let dependencies = value
    859         .get("dependencies")
    860         .and_then(toml::Value::as_table)
    861         .ok_or(ReleaseError::InvalidSourceLock)?;
    862     let mut revisions = BTreeSet::new();
    863     let mut names = BTreeSet::new();
    864     for (name, dependency) in dependencies {
    865         if !name.starts_with("radroots_") {
    866             continue;
    867         }
    868         names.insert(name.as_str());
    869         let table = dependency
    870             .as_table()
    871             .ok_or(ReleaseError::InvalidSourceLock)?;
    872         if table.get("git").and_then(toml::Value::as_str)
    873             != Some("https://github.com/radrootslabs/lib")
    874             || table.contains_key("path")
    875             || table.contains_key("branch")
    876             || table.contains_key("tag")
    877         {
    878             return Err(ReleaseError::InvalidSourceLock);
    879         }
    880         revisions.insert(
    881             table
    882                 .get("rev")
    883                 .and_then(toml::Value::as_str)
    884                 .filter(|revision| lower_hex(revision, 40))
    885                 .ok_or(ReleaseError::InvalidSourceLock)?
    886                 .to_owned(),
    887         );
    888     }
    889     if names != RADROOTS_DEPENDENCIES.into_iter().collect() {
    890         return Err(ReleaseError::InvalidSourceLock);
    891     }
    892     Ok(revisions)
    893 }
    894 
    895 fn cargo_metadata(root: &Path) -> Result<CargoMetadata, ReleaseError> {
    896     let bytes = command_capture_bounded(
    897         Command::new("cargo")
    898             .args(["metadata", "--format-version", "1", "--locked", "--offline"])
    899             .current_dir(root),
    900         MAX_METADATA_BYTES,
    901         ReleaseError::InvalidMetadata,
    902     )?;
    903     serde_json::from_slice(&bytes).map_err(|_| ReleaseError::InvalidMetadata)
    904 }
    905 
    906 fn validate_metadata(metadata: &CargoMetadata) -> Result<(), ReleaseError> {
    907     if metadata.packages.is_empty()
    908         || metadata.packages.len() > MAX_PACKAGES
    909         || metadata.workspace_members.len() != 2
    910         || metadata.resolve.is_none()
    911         || !metadata
    912             .packages
    913             .iter()
    914             .any(|package| package.name == SERVICE && package.version == VERSION)
    915     {
    916         return Err(ReleaseError::InvalidMetadata);
    917     }
    918     Ok(())
    919 }
    920 
    921 fn create_binary_archive(
    922     binary: &Path,
    923     output: &Path,
    924     target: &str,
    925     epoch: u32,
    926 ) -> Result<(), ReleaseError> {
    927     let mut input = open_binary(binary, target)?;
    928     let metadata = input.metadata().map_err(|_| ReleaseError::InvalidBinary)?;
    929     let file = create_new(output)?;
    930     let encoder = GzBuilder::new().mtime(epoch).write(
    931         BoundedWriter::new(file, MAX_BINARY_BYTES + MAX_TEXT_BYTES),
    932         Compression::best(),
    933     );
    934     let mut tar = TarBuilder::new(encoder);
    935     tar.mode(tar::HeaderMode::Deterministic);
    936     let mut header = TarHeader::new_gnu();
    937     header.set_size(metadata.len());
    938     header.set_mode(0o755);
    939     header.set_uid(0);
    940     header.set_gid(0);
    941     header.set_mtime(u64::from(epoch));
    942     header.set_cksum();
    943     tar.append_data(
    944         &mut header,
    945         format!("rhi-{VERSION}-{target}/rhi"),
    946         &mut input,
    947     )
    948     .map_err(|_| ReleaseError::Generation)?;
    949     let encoder = tar.into_inner().map_err(|_| ReleaseError::Generation)?;
    950     encoder
    951         .finish()
    952         .map_err(|_| ReleaseError::Generation)?
    953         .sync_all()
    954         .map_err(|_| ReleaseError::Generation)
    955 }
    956 
    957 fn create_source_archive(root: &Path, output: &Path, epoch: u32) -> Result<(), ReleaseError> {
    958     let work = TempDir::new().map_err(|_| ReleaseError::Generation)?;
    959     let source = work.path().join(format!("rhi-{VERSION}-source"));
    960     fs::create_dir(&source).map_err(|_| ReleaseError::Generation)?;
    961     extract_exact_head(root, &source, work.path())?;
    962     scan_source_tree(&source)?;
    963     let tracked = count_tree(&source)?;
    964     if tracked == 0 || tracked > MAX_TRACKED_FILES {
    965         return Err(ReleaseError::InvalidSource);
    966     }
    967     let vendor_config = command_capture_bounded(
    968         Command::new("cargo")
    969             .args(["vendor", "--locked", "--versioned-dirs", "vendor"])
    970             .current_dir(&source),
    971         MAX_TEXT_BYTES,
    972         ReleaseError::Generation,
    973     )?;
    974     let cargo_config = source.join(".cargo/config.toml");
    975     let mut config = read_bounded(&cargo_config, MAX_TEXT_BYTES, ReleaseError::Generation)?;
    976     config.extend_from_slice(b"\n");
    977     config.extend_from_slice(&vendor_config);
    978     if config.len() as u64 > MAX_TEXT_BYTES {
    979         return Err(ReleaseError::Generation);
    980     }
    981     fs::write(&cargo_config, &config).map_err(|_| ReleaseError::Generation)?;
    982     let _ = command_capture_bounded(
    983         Command::new("cargo")
    984             .args(["metadata", "--format-version", "1", "--locked", "--offline"])
    985             .current_dir(&source),
    986         MAX_METADATA_BYTES,
    987         ReleaseError::Generation,
    988     )?;
    989     create_tree_archive(&source, output, epoch)
    990 }
    991 
    992 fn extract_exact_head(root: &Path, destination: &Path, work: &Path) -> Result<(), ReleaseError> {
    993     let archive = work.join("source-head.tar");
    994     let archive_file = fs::OpenOptions::new()
    995         .create_new(true)
    996         .write(true)
    997         .open(&archive)
    998         .map_err(|_| ReleaseError::Generation)?;
    999     let status = Command::new("git")
   1000         .args(["archive", "--format=tar", "HEAD"])
   1001         .current_dir(root)
   1002         .stdin(Stdio::null())
   1003         .stdout(Stdio::from(archive_file))
   1004         .stderr(Stdio::null())
   1005         .status()
   1006         .map_err(|_| ReleaseError::InvalidSource)?;
   1007     if !status.success() {
   1008         return Err(ReleaseError::InvalidSource);
   1009     }
   1010     validate_regular(
   1011         &archive,
   1012         MAX_SOURCE_ARCHIVE_BYTES,
   1013         ReleaseError::InvalidSource,
   1014     )?;
   1015     let file = fs::File::open(archive).map_err(|_| ReleaseError::InvalidSource)?;
   1016     tar::Archive::new(file)
   1017         .unpack(destination)
   1018         .map_err(|_| ReleaseError::InvalidSource)
   1019 }
   1020 
   1021 fn count_tree(root: &Path) -> Result<usize, ReleaseError> {
   1022     let mut count = 0_usize;
   1023     let mut pending = vec![root.to_path_buf()];
   1024     while let Some(directory) = pending.pop() {
   1025         let entries = fs::read_dir(directory).map_err(|_| ReleaseError::InvalidSource)?;
   1026         for entry in entries {
   1027             let entry = entry.map_err(|_| ReleaseError::InvalidSource)?;
   1028             let kind = entry.file_type().map_err(|_| ReleaseError::InvalidSource)?;
   1029             if kind.is_symlink() || (!kind.is_file() && !kind.is_dir()) {
   1030                 return Err(ReleaseError::InvalidSource);
   1031             }
   1032             if kind.is_dir() {
   1033                 pending.push(entry.path());
   1034             } else {
   1035                 count = count.checked_add(1).ok_or(ReleaseError::InvalidSource)?;
   1036                 if count > MAX_TRACKED_FILES {
   1037                     return Err(ReleaseError::InvalidSource);
   1038                 }
   1039             }
   1040         }
   1041     }
   1042     Ok(count)
   1043 }
   1044 
   1045 #[cfg(unix)]
   1046 fn open_binary(path: &Path, target: &str) -> Result<fs::File, ReleaseError> {
   1047     use rustix::fs::{Mode as FileMode, OFlags};
   1048     use std::io::Seek as _;
   1049     use std::os::unix::fs::PermissionsExt as _;
   1050 
   1051     let descriptor = rustix::fs::open(
   1052         path,
   1053         OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK,
   1054         FileMode::empty(),
   1055     )
   1056     .map_err(|_| ReleaseError::InvalidBinary)?;
   1057     let mut file = fs::File::from(descriptor);
   1058     let metadata = file.metadata().map_err(|_| ReleaseError::InvalidBinary)?;
   1059     if !metadata.is_file()
   1060         || metadata.len() < 20
   1061         || metadata.len() > MAX_BINARY_BYTES
   1062         || metadata.permissions().mode() & 0o111 == 0
   1063     {
   1064         return Err(ReleaseError::InvalidBinary);
   1065     }
   1066     let mut header = [0_u8; 20];
   1067     file.read_exact(&mut header)
   1068         .map_err(|_| ReleaseError::InvalidBinary)?;
   1069     file.rewind().map_err(|_| ReleaseError::InvalidBinary)?;
   1070     let expected_machine = match target {
   1071         "x86_64-unknown-linux-gnu" => 62_u16,
   1072         "aarch64-unknown-linux-gnu" => 183_u16,
   1073         _ => return Err(ReleaseError::InvalidBinary),
   1074     };
   1075     if header[..4] != [0x7f, b'E', b'L', b'F']
   1076         || header[4] != 2
   1077         || header[5] != 1
   1078         || header[6] != 1
   1079         || ![0_u8, 3_u8].contains(&header[7])
   1080         || ![2_u16, 3_u16].contains(&u16::from_le_bytes([header[16], header[17]]))
   1081         || u16::from_le_bytes([header[18], header[19]]) != expected_machine
   1082     {
   1083         return Err(ReleaseError::InvalidBinary);
   1084     }
   1085     let mut scanner = SecretScanner::default();
   1086     let mut total = 0_u64;
   1087     let mut buffer = [0_u8; COPY_BUFFER_BYTES];
   1088     loop {
   1089         let read = file
   1090             .read(&mut buffer)
   1091             .map_err(|_| ReleaseError::InvalidBinary)?;
   1092         if read == 0 {
   1093             break;
   1094         }
   1095         total = total
   1096             .checked_add(u64::try_from(read).map_err(|_| ReleaseError::InvalidBinary)?)
   1097             .ok_or(ReleaseError::InvalidBinary)?;
   1098         if total > MAX_BINARY_BYTES {
   1099             return Err(ReleaseError::InvalidBinary);
   1100         }
   1101         scanner.scan(&buffer[..read])?;
   1102     }
   1103     if total != metadata.len() {
   1104         return Err(ReleaseError::InvalidBinary);
   1105     }
   1106     file.rewind().map_err(|_| ReleaseError::InvalidBinary)?;
   1107     Ok(file)
   1108 }
   1109 
   1110 #[cfg(not(unix))]
   1111 fn open_binary(_path: &Path, _target: &str) -> Result<fs::File, ReleaseError> {
   1112     Err(ReleaseError::InvalidBinary)
   1113 }
   1114 
   1115 fn create_tree_archive(source: &Path, output: &Path, epoch: u32) -> Result<(), ReleaseError> {
   1116     let file = create_new(output)?;
   1117     let encoder = GzBuilder::new().mtime(epoch).write(
   1118         BoundedWriter::new(file, MAX_SOURCE_ARCHIVE_BYTES),
   1119         Compression::best(),
   1120     );
   1121     let mut tar = TarBuilder::new(encoder);
   1122     tar.mode(tar::HeaderMode::Deterministic);
   1123     let root_name = source.file_name().ok_or(ReleaseError::Generation)?;
   1124     append_tree(&mut tar, source, Path::new(root_name), epoch)?;
   1125     let encoder = tar.into_inner().map_err(|_| ReleaseError::Generation)?;
   1126     encoder
   1127         .finish()
   1128         .map_err(|_| ReleaseError::Generation)?
   1129         .sync_all()
   1130         .map_err(|_| ReleaseError::Generation)
   1131 }
   1132 
   1133 fn append_tree<W: std::io::Write>(
   1134     tar: &mut TarBuilder<W>,
   1135     source: &Path,
   1136     archive_path: &Path,
   1137     epoch: u32,
   1138 ) -> Result<(), ReleaseError> {
   1139     let mut entries = fs::read_dir(source)
   1140         .map_err(|_| ReleaseError::Generation)?
   1141         .collect::<Result<Vec<_>, _>>()
   1142         .map_err(|_| ReleaseError::Generation)?;
   1143     entries.sort_by_key(fs::DirEntry::file_name);
   1144     for entry in entries {
   1145         let file_type = entry.file_type().map_err(|_| ReleaseError::Generation)?;
   1146         let path = entry.path();
   1147         let member = archive_path.join(entry.file_name());
   1148         if file_type.is_symlink() {
   1149             return Err(ReleaseError::Generation);
   1150         }
   1151         if file_type.is_dir() {
   1152             append_tree(tar, &path, &member, epoch)?;
   1153             continue;
   1154         }
   1155         if !file_type.is_file() {
   1156             return Err(ReleaseError::Generation);
   1157         }
   1158         let metadata = entry.metadata().map_err(|_| ReleaseError::Generation)?;
   1159         let mut file = fs::File::open(path).map_err(|_| ReleaseError::Generation)?;
   1160         let mut header = TarHeader::new_gnu();
   1161         header.set_size(metadata.len());
   1162         header.set_mode(0o644);
   1163         header.set_uid(0);
   1164         header.set_gid(0);
   1165         header.set_mtime(u64::from(epoch));
   1166         header.set_cksum();
   1167         tar.append_data(&mut header, member, &mut file)
   1168             .map_err(|_| ReleaseError::Generation)?;
   1169     }
   1170     Ok(())
   1171 }
   1172 
   1173 fn supply_chain_documents(
   1174     metadata: &CargoMetadata,
   1175 ) -> Result<(CycloneDxBom, String), ReleaseError> {
   1176     validate_metadata(metadata)?;
   1177     let workspace = metadata
   1178         .workspace_members
   1179         .iter()
   1180         .cloned()
   1181         .collect::<BTreeSet<_>>();
   1182     let mut packages = metadata.packages.clone();
   1183     packages.sort_by(|left, right| left.id.cmp(&right.id));
   1184     let package_references = packages
   1185         .iter()
   1186         .map(|package| {
   1187             let is_workspace = workspace.contains(&package.id);
   1188             if !is_workspace && package.source.is_none() {
   1189                 return Err(ReleaseError::InvalidMetadata);
   1190             }
   1191             Ok((
   1192                 package.id.clone(),
   1193                 stable_package_reference(package, is_workspace)?,
   1194             ))
   1195         })
   1196         .collect::<Result<BTreeMap<_, _>, _>>()?;
   1197     if package_references.len() != packages.len()
   1198         || package_references.values().collect::<BTreeSet<_>>().len() != packages.len()
   1199     {
   1200         return Err(ReleaseError::InvalidMetadata);
   1201     }
   1202     let mut components = Vec::with_capacity(packages.len());
   1203     let mut notices = String::from(
   1204         "THIRD-PARTY NOTICES\n\nGenerated from the exact locked Cargo graph. License expressions are package metadata; packaged vendored source is authoritative for license texts.\n\n",
   1205     );
   1206     for package in packages {
   1207         let package_reference = package_references
   1208             .get(&package.id)
   1209             .ok_or(ReleaseError::InvalidMetadata)?
   1210             .clone();
   1211         let mut properties = vec![SbomProperty {
   1212             name: "radroots:cargo_component_ref",
   1213             value: package_reference.clone(),
   1214         }];
   1215         if let Some(source) = package.source {
   1216             properties.push(SbomProperty {
   1217                 name: "radroots:cargo_source",
   1218                 value: source,
   1219             });
   1220         }
   1221         if let Some(checksum) = package.checksum {
   1222             properties.push(SbomProperty {
   1223                 name: "radroots:cargo_checksum",
   1224                 value: checksum,
   1225             });
   1226         }
   1227         properties.push(SbomProperty {
   1228             name: "radroots:workspace_member",
   1229             value: workspace.contains(&package.id).to_string(),
   1230         });
   1231         let licenses = package.license.as_ref().map(|license| {
   1232             vec![SbomLicenseChoice {
   1233                 expression: license.clone(),
   1234             }]
   1235         });
   1236         use fmt::Write as _;
   1237         writeln!(
   1238             notices,
   1239             "{} {} — {}",
   1240             package.name,
   1241             package.version,
   1242             package.license.as_deref().unwrap_or("NOASSERTION")
   1243         )
   1244         .map_err(|_| ReleaseError::Generation)?;
   1245         components.push(SbomComponent {
   1246             component_type: "library",
   1247             bom_ref: package_reference,
   1248             name: package.name,
   1249             version: package.version,
   1250             licenses,
   1251             properties,
   1252         });
   1253     }
   1254     let mut dependencies = metadata
   1255         .resolve
   1256         .as_ref()
   1257         .ok_or(ReleaseError::InvalidMetadata)?
   1258         .nodes
   1259         .iter()
   1260         .map(|node| -> Result<SbomDependency, ReleaseError> {
   1261             let reference = package_references
   1262                 .get(&node.id)
   1263                 .ok_or(ReleaseError::InvalidMetadata)?
   1264                 .clone();
   1265             let mut depends_on = node
   1266                 .dependencies
   1267                 .iter()
   1268                 .map(|dependency| {
   1269                     package_references
   1270                         .get(dependency)
   1271                         .cloned()
   1272                         .ok_or(ReleaseError::InvalidMetadata)
   1273                 })
   1274                 .collect::<Result<Vec<_>, _>>()?;
   1275             depends_on.sort();
   1276             depends_on.dedup();
   1277             Ok(SbomDependency {
   1278                 reference,
   1279                 depends_on,
   1280             })
   1281         })
   1282         .collect::<Result<Vec<_>, _>>()?;
   1283     dependencies.sort_by(|left, right| left.reference.cmp(&right.reference));
   1284     Ok((
   1285         CycloneDxBom {
   1286             bom_format: "CycloneDX",
   1287             spec_version: "1.5",
   1288             version: 1,
   1289             metadata: SbomMetadata {
   1290                 component: SbomRootComponent {
   1291                     component_type: "application",
   1292                     name: SERVICE,
   1293                     version: VERSION,
   1294                 },
   1295             },
   1296             components,
   1297             dependencies,
   1298         },
   1299         notices,
   1300     ))
   1301 }
   1302 
   1303 fn stable_package_reference(
   1304     package: &CargoPackage,
   1305     is_workspace: bool,
   1306 ) -> Result<String, ReleaseError> {
   1307     let mut hasher = Sha256::new();
   1308     hasher.update(b"radroots.service.native_release.cargo_component.v1\0");
   1309     hash_framed(&mut hasher, package.name.as_bytes())?;
   1310     hash_framed(&mut hasher, package.version.as_bytes())?;
   1311     hash_framed(
   1312         &mut hasher,
   1313         if is_workspace {
   1314             b"workspace"
   1315         } else {
   1316             package
   1317                 .source
   1318                 .as_deref()
   1319                 .ok_or(ReleaseError::InvalidMetadata)?
   1320                 .as_bytes()
   1321         },
   1322     )?;
   1323     hash_framed(
   1324         &mut hasher,
   1325         package.checksum.as_deref().unwrap_or("").as_bytes(),
   1326     )?;
   1327     Ok(format!(
   1328         "urn:radroots:cargo-component:sha256:{}",
   1329         hex::encode(hasher.finalize())
   1330     ))
   1331 }
   1332 
   1333 fn hash_framed(hasher: &mut Sha256, bytes: &[u8]) -> Result<(), ReleaseError> {
   1334     let length = u64::try_from(bytes.len()).map_err(|_| ReleaseError::InvalidMetadata)?;
   1335     hasher.update(length.to_be_bytes());
   1336     hasher.update(bytes);
   1337     Ok(())
   1338 }
   1339 
   1340 #[cfg(test)]
   1341 fn validate_relative(value: &str) -> Result<(), ReleaseError> {
   1342     let path = Path::new(value);
   1343     if value.is_empty()
   1344         || path.is_absolute()
   1345         || path.components().any(|component| {
   1346             matches!(
   1347                 component,
   1348                 std::path::Component::ParentDir
   1349                     | std::path::Component::RootDir
   1350                     | std::path::Component::Prefix(_)
   1351             )
   1352         })
   1353     {
   1354         return Err(ReleaseError::InvalidSource);
   1355     }
   1356     Ok(())
   1357 }
   1358 
   1359 fn copy_bounded(source: &Path, output: &Path, maximum: u64) -> Result<(), ReleaseError> {
   1360     validate_regular(source, maximum, ReleaseError::InvalidSource)?;
   1361     let metadata = fs::metadata(source).map_err(|_| ReleaseError::InvalidSource)?;
   1362     let mut input = fs::File::open(source).map_err(|_| ReleaseError::InvalidSource)?;
   1363     let mut target = create_new(output)?;
   1364     let mut scanner = SecretScanner::default();
   1365     let mut total = 0_u64;
   1366     let mut buffer = [0_u8; COPY_BUFFER_BYTES];
   1367     loop {
   1368         let read = input
   1369             .read(&mut buffer)
   1370             .map_err(|_| ReleaseError::InvalidSource)?;
   1371         if read == 0 {
   1372             break;
   1373         }
   1374         total = total
   1375             .checked_add(u64::try_from(read).map_err(|_| ReleaseError::InvalidSource)?)
   1376             .ok_or(ReleaseError::InvalidSource)?;
   1377         if total > maximum {
   1378             return Err(ReleaseError::InvalidSource);
   1379         }
   1380         scanner.scan(&buffer[..read])?;
   1381         target
   1382             .write_all(&buffer[..read])
   1383             .map_err(|_| ReleaseError::Generation)?;
   1384     }
   1385     if total != metadata.len() {
   1386         return Err(ReleaseError::InvalidSource);
   1387     }
   1388     target.sync_all().map_err(|_| ReleaseError::Generation)
   1389 }
   1390 
   1391 fn scan_source_tree(root: &Path) -> Result<(), ReleaseError> {
   1392     let mut pending = vec![root.to_path_buf()];
   1393     let mut file_count = 0_usize;
   1394     while let Some(directory) = pending.pop() {
   1395         let entries = fs::read_dir(directory).map_err(|_| ReleaseError::InvalidSource)?;
   1396         for entry in entries {
   1397             let entry = entry.map_err(|_| ReleaseError::InvalidSource)?;
   1398             let kind = entry.file_type().map_err(|_| ReleaseError::InvalidSource)?;
   1399             if kind.is_symlink() || (!kind.is_file() && !kind.is_dir()) {
   1400                 return Err(ReleaseError::InvalidSource);
   1401             }
   1402             if kind.is_dir() {
   1403                 pending.push(entry.path());
   1404                 continue;
   1405             }
   1406             file_count = file_count
   1407                 .checked_add(1)
   1408                 .ok_or(ReleaseError::InvalidSource)?;
   1409             if file_count > MAX_TRACKED_FILES {
   1410                 return Err(ReleaseError::InvalidSource);
   1411             }
   1412             let path = entry.path();
   1413             validate_regular(&path, MAX_DOCUMENT_BYTES, ReleaseError::InvalidSource)?;
   1414             let mut file = fs::File::open(path).map_err(|_| ReleaseError::InvalidSource)?;
   1415             let mut scanner = SecretScanner::default();
   1416             let mut buffer = [0_u8; COPY_BUFFER_BYTES];
   1417             loop {
   1418                 let read = file
   1419                     .read(&mut buffer)
   1420                     .map_err(|_| ReleaseError::InvalidSource)?;
   1421                 if read == 0 {
   1422                     break;
   1423                 }
   1424                 scanner.scan(&buffer[..read])?;
   1425             }
   1426         }
   1427     }
   1428     Ok(())
   1429 }
   1430 
   1431 fn create_new(path: &Path) -> Result<fs::File, ReleaseError> {
   1432     let mut options = fs::OpenOptions::new();
   1433     options.create_new(true).write(true);
   1434     #[cfg(unix)]
   1435     {
   1436         use std::os::unix::fs::OpenOptionsExt as _;
   1437         options.mode(0o644);
   1438     }
   1439     let file = options.open(path).map_err(|_| ReleaseError::Generation)?;
   1440     set_file_permissions(&file)?;
   1441     Ok(file)
   1442 }
   1443 
   1444 #[cfg(unix)]
   1445 fn set_file_permissions(file: &fs::File) -> Result<(), ReleaseError> {
   1446     use std::os::unix::fs::PermissionsExt as _;
   1447 
   1448     file.set_permissions(fs::Permissions::from_mode(0o644))
   1449         .map_err(|_| ReleaseError::Generation)
   1450 }
   1451 
   1452 #[cfg(not(unix))]
   1453 fn set_file_permissions(_file: &fs::File) -> Result<(), ReleaseError> {
   1454     Ok(())
   1455 }
   1456 
   1457 #[cfg(unix)]
   1458 fn set_directory_permissions(path: &Path) -> Result<(), ReleaseError> {
   1459     use std::os::unix::fs::PermissionsExt as _;
   1460 
   1461     fs::set_permissions(path, fs::Permissions::from_mode(0o755))
   1462         .map_err(|_| ReleaseError::Generation)
   1463 }
   1464 
   1465 #[cfg(not(unix))]
   1466 fn set_directory_permissions(_path: &Path) -> Result<(), ReleaseError> {
   1467     Ok(())
   1468 }
   1469 
   1470 #[cfg(unix)]
   1471 fn sync_directory(path: &Path) -> Result<(), ReleaseError> {
   1472     fs::File::open(path)
   1473         .and_then(|directory| directory.sync_all())
   1474         .map_err(|_| ReleaseError::Generation)
   1475 }
   1476 
   1477 #[cfg(not(unix))]
   1478 fn sync_directory(_path: &Path) -> Result<(), ReleaseError> {
   1479     Ok(())
   1480 }
   1481 
   1482 #[cfg(unix)]
   1483 fn publish_directory(source: &Path, destination: &Path) -> Result<(), ReleaseError> {
   1484     use rustix::fs::{CWD, RenameFlags, renameat_with};
   1485 
   1486     renameat_with(CWD, source, CWD, destination, RenameFlags::NOREPLACE)
   1487         .map_err(|_| ReleaseError::Generation)
   1488 }
   1489 
   1490 #[cfg(not(unix))]
   1491 fn publish_directory(_source: &Path, _destination: &Path) -> Result<(), ReleaseError> {
   1492     Err(ReleaseError::Generation)
   1493 }
   1494 
   1495 struct BoundedWriter<W> {
   1496     inner: W,
   1497     written: u64,
   1498     maximum: u64,
   1499 }
   1500 
   1501 impl<W> BoundedWriter<W> {
   1502     const fn new(inner: W, maximum: u64) -> Self {
   1503         Self {
   1504             inner,
   1505             written: 0,
   1506             maximum,
   1507         }
   1508     }
   1509 }
   1510 
   1511 impl BoundedWriter<fs::File> {
   1512     fn sync_all(&self) -> std::io::Result<()> {
   1513         self.inner.sync_all()
   1514     }
   1515 }
   1516 
   1517 impl<W: std::io::Write> std::io::Write for BoundedWriter<W> {
   1518     fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
   1519         let remaining = self.maximum.saturating_sub(self.written);
   1520         if remaining == 0 && !bytes.is_empty() {
   1521             return Err(std::io::Error::other("bounded output exceeded"));
   1522         }
   1523         let admitted = bytes
   1524             .len()
   1525             .min(usize::try_from(remaining).unwrap_or(usize::MAX));
   1526         let written = self.inner.write(&bytes[..admitted])?;
   1527         self.written = self
   1528             .written
   1529             .checked_add(u64::try_from(written).map_err(std::io::Error::other)?)
   1530             .ok_or_else(|| std::io::Error::other("bounded output exceeded"))?;
   1531         Ok(written)
   1532     }
   1533 
   1534     fn flush(&mut self) -> std::io::Result<()> {
   1535         self.inner.flush()
   1536     }
   1537 }
   1538 
   1539 fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), ReleaseError> {
   1540     let mut bytes = serde_json::to_vec(value).map_err(|_| ReleaseError::Generation)?;
   1541     bytes.push(b'\n');
   1542     write_generated(path, &bytes)
   1543 }
   1544 
   1545 fn write_generated(path: &Path, bytes: &[u8]) -> Result<(), ReleaseError> {
   1546     if bytes.is_empty() || bytes.len() as u64 > MAX_DOCUMENT_BYTES {
   1547         return Err(ReleaseError::Generation);
   1548     }
   1549     scan_bytes(bytes)?;
   1550     let mut file = create_new(path)?;
   1551     file.write_all(bytes)
   1552         .and_then(|()| file.sync_all())
   1553         .map_err(|_| ReleaseError::Generation)
   1554 }
   1555 
   1556 fn write_checksums(root: &Path) -> Result<(), ReleaseError> {
   1557     let records = inventory_records(root)?;
   1558     let mut output = String::new();
   1559     use fmt::Write as _;
   1560     for record in records {
   1561         writeln!(output, "{}  {}", record.sha256, record.path)
   1562             .map_err(|_| ReleaseError::Generation)?;
   1563     }
   1564     write_generated(&root.join("SHA256SUMS"), output.as_bytes())
   1565 }
   1566 
   1567 fn inventory_records(root: &Path) -> Result<Vec<ArtifactRecord>, ReleaseError> {
   1568     let mut names = fs::read_dir(root)
   1569         .map_err(|_| ReleaseError::InvalidOutput)?
   1570         .collect::<Result<Vec<_>, _>>()
   1571         .map_err(|_| ReleaseError::InvalidOutput)?;
   1572     names.sort_by_key(fs::DirEntry::file_name);
   1573     names
   1574         .into_iter()
   1575         .map(|entry| {
   1576             let name = entry
   1577                 .file_name()
   1578                 .into_string()
   1579                 .map_err(|_| ReleaseError::InvalidOutput)?;
   1580             let evidence = hash_regular(&entry.path(), output_maximum(&name)?)?;
   1581             Ok(ArtifactRecord {
   1582                 path: name,
   1583                 byte_length: evidence.byte_length,
   1584                 sha256: evidence.sha256,
   1585             })
   1586         })
   1587         .collect()
   1588 }
   1589 
   1590 fn output_maximum(name: &str) -> Result<u64, ReleaseError> {
   1591     match name {
   1592         "binary.tar.gz" => Ok(MAX_BINARY_BYTES + MAX_TEXT_BYTES),
   1593         "service-source.tar.gz" => Ok(MAX_SOURCE_ARCHIVE_BYTES),
   1594         "LICENSE" | "config.example.toml" | "config.schema.json" | "systemd.service" => {
   1595             Ok(MAX_TEXT_BYTES)
   1596         }
   1597         SOURCE_LOCK => Ok(MAX_SOURCE_LOCK_BYTES),
   1598         "SHA256SUMS"
   1599         | "THIRD-PARTY-NOTICES.txt"
   1600         | "artifact-manifest.v1.json"
   1601         | "provenance-input.v1.json"
   1602         | "sbom.cdx.json" => Ok(MAX_DOCUMENT_BYTES),
   1603         _ => Err(ReleaseError::InvalidOutput),
   1604     }
   1605 }
   1606 
   1607 fn validate_exact_inventory(root: &Path) -> Result<(), ReleaseError> {
   1608     let actual = inventory_records(root)?;
   1609     if actual
   1610         .iter()
   1611         .map(|record| record.path.as_str())
   1612         .collect::<Vec<_>>()
   1613         != OUTPUT_NAMES
   1614     {
   1615         return Err(ReleaseError::InvalidOutput);
   1616     }
   1617     validate_output_permissions(root)?;
   1618     Ok(())
   1619 }
   1620 
   1621 #[cfg(unix)]
   1622 fn validate_output_permissions(root: &Path) -> Result<(), ReleaseError> {
   1623     use std::os::unix::fs::PermissionsExt as _;
   1624 
   1625     let root_metadata = fs::symlink_metadata(root).map_err(|_| ReleaseError::InvalidOutput)?;
   1626     if root_metadata.file_type().is_symlink()
   1627         || !root_metadata.is_dir()
   1628         || root_metadata.permissions().mode() & 0o777 != 0o755
   1629     {
   1630         return Err(ReleaseError::InvalidOutput);
   1631     }
   1632     for name in OUTPUT_NAMES {
   1633         let metadata =
   1634             fs::symlink_metadata(root.join(name)).map_err(|_| ReleaseError::InvalidOutput)?;
   1635         if metadata.file_type().is_symlink()
   1636             || !metadata.is_file()
   1637             || metadata.permissions().mode() & 0o777 != 0o644
   1638         {
   1639             return Err(ReleaseError::InvalidOutput);
   1640         }
   1641     }
   1642     Ok(())
   1643 }
   1644 
   1645 #[cfg(not(unix))]
   1646 fn validate_output_permissions(_root: &Path) -> Result<(), ReleaseError> {
   1647     Ok(())
   1648 }
   1649 
   1650 fn compare_output(output: &Path, expected: &[ArtifactRecord]) -> Result<(), ReleaseError> {
   1651     validate_exact_inventory(output)?;
   1652     let actual = inventory_records(output)?;
   1653     if actual != expected {
   1654         return Err(ReleaseError::StaleOutput);
   1655     }
   1656     Ok(())
   1657 }
   1658 
   1659 struct FileEvidence {
   1660     byte_length: u64,
   1661     sha256: String,
   1662 }
   1663 
   1664 fn hash_regular(path: &Path, maximum: u64) -> Result<FileEvidence, ReleaseError> {
   1665     validate_regular(path, maximum, ReleaseError::InvalidOutput)?;
   1666     let metadata = fs::metadata(path).map_err(|_| ReleaseError::InvalidOutput)?;
   1667     let mut file = fs::File::open(path).map_err(|_| ReleaseError::InvalidOutput)?;
   1668     let mut hasher = Sha256::new();
   1669     let mut total = 0_u64;
   1670     let mut buffer = [0_u8; COPY_BUFFER_BYTES];
   1671     loop {
   1672         let read = file
   1673             .read(&mut buffer)
   1674             .map_err(|_| ReleaseError::InvalidOutput)?;
   1675         if read == 0 {
   1676             break;
   1677         }
   1678         total = total
   1679             .checked_add(u64::try_from(read).map_err(|_| ReleaseError::InvalidOutput)?)
   1680             .ok_or(ReleaseError::InvalidOutput)?;
   1681         if total > maximum {
   1682             return Err(ReleaseError::InvalidOutput);
   1683         }
   1684         hasher.update(&buffer[..read]);
   1685     }
   1686     if total != metadata.len() {
   1687         return Err(ReleaseError::InvalidOutput);
   1688     }
   1689     Ok(FileEvidence {
   1690         byte_length: total,
   1691         sha256: hex::encode(hasher.finalize()),
   1692     })
   1693 }
   1694 
   1695 fn validate_regular(path: &Path, maximum: u64, error: ReleaseError) -> Result<(), ReleaseError> {
   1696     let metadata = fs::symlink_metadata(path).map_err(|_| error)?;
   1697     if metadata.file_type().is_symlink() || !metadata.is_file() || metadata.len() > maximum {
   1698         return Err(error);
   1699     }
   1700     Ok(())
   1701 }
   1702 
   1703 fn read_bounded(path: &Path, maximum: u64, error: ReleaseError) -> Result<Vec<u8>, ReleaseError> {
   1704     validate_regular(path, maximum, error)?;
   1705     let mut bytes = Vec::new();
   1706     fs::File::open(path)
   1707         .map_err(|_| error)?
   1708         .take(maximum.saturating_add(1))
   1709         .read_to_end(&mut bytes)
   1710         .map_err(|_| error)?;
   1711     if bytes.len() as u64 > maximum {
   1712         return Err(error);
   1713     }
   1714     Ok(bytes)
   1715 }
   1716 
   1717 fn command_capture_bounded(
   1718     command: &mut Command,
   1719     maximum: u64,
   1720     error: ReleaseError,
   1721 ) -> Result<Vec<u8>, ReleaseError> {
   1722     let file = NamedTempFile::new().map_err(|_| error)?;
   1723     let stdout = file.reopen().map_err(|_| error)?;
   1724     let status = command
   1725         .stdin(Stdio::null())
   1726         .stdout(Stdio::from(stdout))
   1727         .stderr(Stdio::null())
   1728         .status()
   1729         .map_err(|_| error)?;
   1730     if !status.success() {
   1731         return Err(error);
   1732     }
   1733     read_bounded(file.path(), maximum, error)
   1734 }
   1735 
   1736 fn git_capture(root: &Path, arguments: &[&str], maximum: usize) -> Result<Vec<u8>, ReleaseError> {
   1737     command_capture_bounded(
   1738         Command::new("git").args(arguments).current_dir(root),
   1739         maximum as u64,
   1740         ReleaseError::InvalidSource,
   1741     )
   1742 }
   1743 
   1744 fn exact_line(bytes: &[u8]) -> Option<&str> {
   1745     let value = std::str::from_utf8(bytes).ok()?.strip_suffix('\n')?;
   1746     (!value.is_empty() && !value.contains(['\n', '\r'])).then_some(value)
   1747 }
   1748 
   1749 fn lower_hex(value: &str, length: usize) -> bool {
   1750     value.len() == length
   1751         && value
   1752             .bytes()
   1753             .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
   1754 }
   1755 
   1756 #[derive(Default)]
   1757 struct SecretScanner {
   1758     tail: Vec<u8>,
   1759 }
   1760 
   1761 impl SecretScanner {
   1762     fn scan(&mut self, bytes: &[u8]) -> Result<(), ReleaseError> {
   1763         let mut combined = Vec::with_capacity(self.tail.len() + bytes.len());
   1764         combined.extend_from_slice(&self.tail);
   1765         combined.extend_from_slice(bytes);
   1766         if SECRET_PATTERN_PARTS
   1767             .iter()
   1768             .any(|(first, second)| contains_joined_bytes(&combined, first, second))
   1769         {
   1770             return Err(ReleaseError::ProtectedMaterial);
   1771         }
   1772         let retained = SECRET_PATTERN_PARTS
   1773             .iter()
   1774             .map(|(first, second)| first.len().saturating_add(second.len()).saturating_sub(1))
   1775             .max()
   1776             .unwrap_or(0)
   1777             .min(combined.len());
   1778         self.tail.clear();
   1779         self.tail
   1780             .extend_from_slice(&combined[combined.len() - retained..]);
   1781         Ok(())
   1782     }
   1783 }
   1784 
   1785 fn scan_bytes(bytes: &[u8]) -> Result<(), ReleaseError> {
   1786     let mut scanner = SecretScanner::default();
   1787     scanner.scan(bytes)
   1788 }
   1789 
   1790 fn contains_joined_bytes(haystack: &[u8], first: &[u8], second: &[u8]) -> bool {
   1791     let length = first.len().saturating_add(second.len());
   1792     length > 0
   1793         && haystack.windows(length).any(|window| {
   1794             window.get(..first.len()) == Some(first) && window.get(first.len()..) == Some(second)
   1795         })
   1796 }
   1797 
   1798 #[cfg(test)]
   1799 mod tests {
   1800     use super::*;
   1801 
   1802     #[test]
   1803     fn current_source_lock_is_canonical_bounded_and_exactly_bound() {
   1804         let root = workspace_root();
   1805         let lock = read_source_lock(&root).expect("current V4 lock");
   1806         assert_eq!(lock.rust_version, RUST_VERSION);
   1807         assert_eq!(lock.nix.material, "bound");
   1808         assert_eq!(output_maximum(SOURCE_LOCK), Ok(MAX_SOURCE_LOCK_BYTES));
   1809         let fixture = TempDir::new().expect("source fixture");
   1810         for name in [
   1811             SOURCE_LOCK,
   1812             "Cargo.toml",
   1813             "Cargo.lock",
   1814             "flake.lock",
   1815             "contracts/release/rhi-artifact-contract.v4.json",
   1816         ] {
   1817             let target = fixture.path().join(name);
   1818             fs::create_dir_all(target.parent().expect("fixture parent")).expect("parent");
   1819             fs::copy(root.join(name), target).expect("fixture input");
   1820         }
   1821         read_source_lock(fixture.path()).expect("exact fixture");
   1822         let path = fixture.path().join(SOURCE_LOCK);
   1823         let original = fs::read_to_string(&path).expect("lock bytes");
   1824         for changed in [
   1825             format!("{original}\n"),
   1826             original.replacen("1.99.0", "1.97.1", 1),
   1827             original.replacen("material = \"bound\"", "material = \"qualified\"", 1),
   1828             original.replacen("native_linkage_count = 1", "native_linkage_count = 2", 1),
   1829             original.replacen("contract_version = 4", "contract_version = 3", 1),
   1830             "x".repeat(MAX_SOURCE_LOCK_BYTES as usize + 1),
   1831         ] {
   1832             assert_ne!(changed, original);
   1833             fs::write(&path, changed).expect("mutated lock");
   1834             assert!(read_source_lock(fixture.path()).is_err());
   1835         }
   1836         fs::write(&path, original).expect("restore lock");
   1837         fs::write(
   1838             fixture.path().join("radroots.service.source-lock.v3.toml"),
   1839             b"historical",
   1840         )
   1841         .expect("coexisting predecessor");
   1842         assert!(read_source_lock(fixture.path()).is_err());
   1843         fs::remove_file(fixture.path().join("radroots.service.source-lock.v3.toml"))
   1844             .expect("remove predecessor fixture");
   1845         for name in [
   1846             "Cargo.lock",
   1847             "flake.lock",
   1848             "contracts/release/rhi-artifact-contract.v4.json",
   1849         ] {
   1850             let target = fixture.path().join(name);
   1851             let original = fs::read(&target).expect("bound input");
   1852             let mut changed = original.clone();
   1853             changed.push(b'\n');
   1854             fs::write(&target, changed).expect("changed input");
   1855             assert!(read_source_lock(fixture.path()).is_err(), "{name}");
   1856             fs::write(target, original).expect("restore input");
   1857         }
   1858         let manifest = fixture.path().join("Cargo.toml");
   1859         let original = fs::read_to_string(&manifest).expect("manifest");
   1860         let native = original
   1861             .lines()
   1862             .find(|line| line.starts_with("radroots_transport_nostr_native ="))
   1863             .expect("native connector dependency");
   1864         for changed in [
   1865             original.replace(native, ""),
   1866             original.replace(
   1867                 "radroots_transport_nostr_native =",
   1868                 "radroots_transport_unexpected =",
   1869             ),
   1870         ] {
   1871             fs::write(&manifest, changed).expect("changed dependency inventory");
   1872             assert!(read_source_lock(fixture.path()).is_err());
   1873         }
   1874         fs::write(manifest, original).expect("restore manifest");
   1875     }
   1876 
   1877     #[test]
   1878     fn argument_parser_is_closed_and_bounded() {
   1879         let args = parse_native_release_args(vec![
   1880             "--mode".into(),
   1881             "check".into(),
   1882             "--target".into(),
   1883             "x86_64-unknown-linux-gnu".into(),
   1884             "--binary".into(),
   1885             "/tmp/rhi".into(),
   1886             "--output".into(),
   1887             "/tmp/release".into(),
   1888             "--source-date-epoch".into(),
   1889             "1".into(),
   1890         ])
   1891         .expect("valid arguments");
   1892         assert_eq!(args.mode, Mode::Check);
   1893         assert_eq!(args.source_date_epoch, 1);
   1894         for mutation in [
   1895             vec!["--mode".into(), "write".into()],
   1896             vec![
   1897                 "--mode".into(),
   1898                 "write".into(),
   1899                 "--mode".into(),
   1900                 "check".into(),
   1901                 "--target".into(),
   1902                 "x86_64-unknown-linux-gnu".into(),
   1903                 "--binary".into(),
   1904                 "/tmp/rhi".into(),
   1905                 "--output".into(),
   1906                 "/tmp/release".into(),
   1907                 "--source-date-epoch".into(),
   1908                 "1".into(),
   1909             ],
   1910             vec![
   1911                 "--mode".into(),
   1912                 "write".into(),
   1913                 "--target".into(),
   1914                 "x86_64-apple-darwin".into(),
   1915                 "--binary".into(),
   1916                 "/tmp/rhi".into(),
   1917                 "--output".into(),
   1918                 "/tmp/release".into(),
   1919                 "--source-date-epoch".into(),
   1920                 "1".into(),
   1921             ],
   1922         ] {
   1923             assert_eq!(
   1924                 parse_native_release_args(mutation).expect_err("invalid arguments"),
   1925                 ReleaseError::InvalidArguments
   1926             );
   1927         }
   1928     }
   1929 
   1930     #[test]
   1931     fn secret_scanner_detects_split_patterns() {
   1932         let mut scanner = SecretScanner::default();
   1933         scanner.scan(b"prefix github_").expect("prefix");
   1934         assert_eq!(
   1935             scanner.scan(b"pat_value").expect_err("secret rejected"),
   1936             ReleaseError::ProtectedMaterial
   1937         );
   1938     }
   1939 
   1940     #[test]
   1941     fn source_scanner_bounds_files_and_detects_protected_material() {
   1942         let directory = TempDir::new().expect("tempdir");
   1943         fs::write(directory.path().join("safe.rs"), b"fn safe() {}").expect("safe source");
   1944         scan_source_tree(directory.path()).expect("safe source tree");
   1945         fs::write(
   1946             directory.path().join("protected.txt"),
   1947             [b"github_".as_slice(), b"pat_value".as_slice()].concat(),
   1948         )
   1949         .expect("protected fixture");
   1950         assert_eq!(
   1951             scan_source_tree(directory.path()).expect_err("protected source rejected"),
   1952             ReleaseError::ProtectedMaterial
   1953         );
   1954     }
   1955 
   1956     #[cfg(unix)]
   1957     #[test]
   1958     fn binary_archive_is_deterministic_and_contains_one_member() {
   1959         use std::os::unix::fs::PermissionsExt as _;
   1960 
   1961         let directory = TempDir::new().expect("tempdir");
   1962         let binary = directory.path().join("rhi");
   1963         let mut elf = [0_u8; 20];
   1964         elf[..8].copy_from_slice(&[0x7f, b'E', b'L', b'F', 2, 1, 1, 0]);
   1965         elf[16..18].copy_from_slice(&3_u16.to_le_bytes());
   1966         elf[18..20].copy_from_slice(&62_u16.to_le_bytes());
   1967         fs::write(&binary, elf).expect("binary");
   1968         fs::set_permissions(&binary, fs::Permissions::from_mode(0o755)).expect("binary mode");
   1969         let first = directory.path().join("first.tar.gz");
   1970         let second = directory.path().join("second.tar.gz");
   1971         create_binary_archive(&binary, &first, "x86_64-unknown-linux-gnu", 1)
   1972             .expect("first archive");
   1973         create_binary_archive(&binary, &second, "x86_64-unknown-linux-gnu", 1)
   1974             .expect("second archive");
   1975         assert_eq!(
   1976             fs::read(first).expect("first"),
   1977             fs::read(second).expect("second")
   1978         );
   1979         assert_eq!(
   1980             create_binary_archive(
   1981                 &binary,
   1982                 &directory.path().join("wrong-target.tar.gz"),
   1983                 "aarch64-unknown-linux-gnu",
   1984                 1,
   1985             )
   1986             .expect_err("target mismatch"),
   1987             ReleaseError::InvalidBinary
   1988         );
   1989     }
   1990 
   1991     #[cfg(unix)]
   1992     #[test]
   1993     fn generated_permissions_are_exact() {
   1994         use std::os::unix::fs::PermissionsExt as _;
   1995 
   1996         let parent = TempDir::new().expect("tempdir");
   1997         let directory = parent.path().join("release");
   1998         fs::create_dir(&directory).expect("directory");
   1999         set_directory_permissions(&directory).expect("directory mode");
   2000         let file = directory.join("artifact");
   2001         create_new(&file).expect("artifact");
   2002         assert_eq!(
   2003             fs::metadata(directory)
   2004                 .expect("directory metadata")
   2005                 .permissions()
   2006                 .mode()
   2007                 & 0o777,
   2008             0o755
   2009         );
   2010         assert_eq!(
   2011             fs::metadata(file)
   2012                 .expect("file metadata")
   2013                 .permissions()
   2014                 .mode()
   2015                 & 0o777,
   2016             0o644
   2017         );
   2018     }
   2019 
   2020     #[test]
   2021     fn compressed_outputs_are_bounded_before_allocation() {
   2022         let mut writer = BoundedWriter::new(Vec::new(), 3);
   2023         assert!(writer.write_all(b"abc").is_ok());
   2024         assert_eq!(writer.written, 3);
   2025         assert!(writer.write_all(b"d").is_err());
   2026     }
   2027 
   2028     #[test]
   2029     fn sbom_uses_spdx_expressions_in_the_governed_field() {
   2030         assert_eq!(
   2031             serde_json::to_value(SbomLicenseChoice {
   2032                 expression: "MIT OR Apache-2.0".to_owned(),
   2033             })
   2034             .expect("license choice"),
   2035             serde_json::json!({"expression": "MIT OR Apache-2.0"})
   2036         );
   2037     }
   2038 
   2039     #[test]
   2040     fn sbom_component_references_are_path_free_and_checkout_independent() {
   2041         let package_at_first_path = CargoPackage {
   2042             id: "path+file:///private/first/rhi#0.1.0".to_owned(),
   2043             name: "rhi".to_owned(),
   2044             version: "0.1.0".to_owned(),
   2045             source: None,
   2046             checksum: None,
   2047             license: Some("AGPL-3.0-or-later".to_owned()),
   2048         };
   2049         let package_at_second_path = CargoPackage {
   2050             id: "path+file:///different/checkout/rhi#0.1.0".to_owned(),
   2051             ..package_at_first_path.clone()
   2052         };
   2053         let first =
   2054             stable_package_reference(&package_at_first_path, true).expect("first reference");
   2055         let second =
   2056             stable_package_reference(&package_at_second_path, true).expect("second reference");
   2057         assert_eq!(first, second);
   2058         assert!(first.starts_with("urn:radroots:cargo-component:sha256:"));
   2059         assert!(!first.contains("private"));
   2060         assert!(!first.contains("checkout"));
   2061     }
   2062 
   2063     #[test]
   2064     fn relative_paths_reject_escape_and_absolute_values() {
   2065         for rejected in ["", "../escape", "a/../../escape", "/absolute"] {
   2066             assert_eq!(
   2067                 validate_relative(rejected).expect_err("path rejected"),
   2068                 ReleaseError::InvalidSource
   2069             );
   2070         }
   2071         validate_relative("contracts/config.json").expect("safe path");
   2072     }
   2073 
   2074     #[test]
   2075     fn error_surface_is_fixed_and_source_free() {
   2076         for error in [
   2077             ReleaseError::InvalidArguments,
   2078             ReleaseError::InvalidSource,
   2079             ReleaseError::DirtySource,
   2080             ReleaseError::InvalidBinary,
   2081             ReleaseError::InvalidOutput,
   2082             ReleaseError::InvalidMetadata,
   2083             ReleaseError::InvalidSourceLock,
   2084             ReleaseError::ProtectedMaterial,
   2085             ReleaseError::StaleOutput,
   2086             ReleaseError::Generation,
   2087         ] {
   2088             assert!(!error.code().is_empty());
   2089             let display = error.to_string();
   2090             assert!(!display.contains('/'));
   2091             assert!(!display.contains("github_pat"));
   2092             assert!(std::error::Error::source(&error).is_none());
   2093         }
   2094     }
   2095 }