myc

Self-custodial remote signer for Radroots apps
git clone https://radroots.dev/git/myc.git
Log | Files | Refs | README | LICENSE

main.rs (65155B)


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