cargo-rail 0.32.0

Cargo-native Rust workspace engine for affected CI, Rust source-surface analysis, compiler reuse, dependency coherence, exact-SHA releases, and split/sync
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Exact-invocation compiler input observations, separate from compiler facts.

#![allow(
    dead_code,
    reason = "the shared wire model has disjoint producers and consumers in the main crate and isolated companion"
)]

use std::path::{Component, Path};

use rscrypto::Sha256;
use serde::{Deserialize, Serialize};

pub(crate) const NATIVE_INPUT_PROTOCOL_VERSION: u32 = 5;
pub(crate) const NATIVE_INPUT_PROTOCOL_VERSION_ARGUMENT: &str = "--cargo-rail-native-input-protocol-version";
pub(crate) const NATIVE_INPUT_INVOCATION_ENV: &str = "CARGO_RAIL_NATIVE_INPUT_INVOCATION";
pub(crate) const NATIVE_INPUT_INVOCATION_ARGUMENT: &str = "--cargo-rail-native-input-invocation";
pub(crate) const MAX_NATIVE_INPUT_INVOCATION_BYTES: u64 = 64 * 1024;
pub(crate) const MAX_NATIVE_INPUT_OBSERVATION_BYTES: u64 = 4 * 1024 * 1024;

/// Where the driver records the compiler's crate selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum NativeInputPhase {
    /// The driver performs the complete compilation and records its inputs after analysis.
    Compilation,
    /// The driver records the crate selection when rustc freezes crate loading, then stops
    /// before writing any output. Another compiler, such as Clippy, produces the outputs.
    Resolution,
}

/// One-shot capability for the actual compiler arguments and result destination.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct NativeInputInvocation {
    pub(crate) version: u32,
    pub(crate) phase: NativeInputPhase,
    pub(crate) nonce: String,
    pub(crate) action_identity: String,
    pub(crate) invocation_digest: String,
    pub(crate) result_path: String,
    pub(crate) source_working_directory: Option<String>,
}

impl NativeInputInvocation {
    pub(crate) fn decode(bytes: &[u8]) -> Result<Self, String> {
        if bytes.is_empty() || bytes.len() as u64 > MAX_NATIVE_INPUT_INVOCATION_BYTES {
            return Err("native input invocation exceeds its byte bound".into());
        }
        let invocation: Self = serde_json::from_slice(bytes).map_err(|error| error.to_string())?;
        invocation.validate()?;
        if serde_json::to_vec(&invocation).map_err(|error| error.to_string())? != bytes {
            return Err("native input invocation is not canonical JSON".into());
        }
        Ok(invocation)
    }

    pub(crate) fn identity(&self) -> Result<String, String> {
        self.validate()?;
        let bytes = serde_json::to_vec(self).map_err(|error| error.to_string())?;
        if bytes.len() as u64 > MAX_NATIVE_INPUT_INVOCATION_BYTES {
            return Err("native input invocation exceeds its byte bound".into());
        }
        Ok(hex_digest(&bytes))
    }

    fn validate(&self) -> Result<(), String> {
        if self.version != NATIVE_INPUT_PROTOCOL_VERSION
            || !is_digest(&self.nonce)
            || !is_digest(&self.invocation_digest)
            || self.action_identity.is_empty()
            || self.action_identity.len() > 512
            || self.action_identity.chars().any(char::is_control)
            || self
                .source_working_directory
                .as_deref()
                .is_some_and(|path| !absolute_input_path(path))
            || !absolute_input_path(&self.result_path)
            || Path::new(&self.result_path).file_name().is_none()
        {
            return Err("native input invocation has incompatible authority".into());
        }
        Ok(())
    }
}

/// Files rustc selected for one external crate, including transitive crates.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct NativeCrateSource {
    pub(crate) name: String,
    pub(crate) files: Vec<String>,
}

/// Compiler-owned filename query, including the effective target's conventions.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct NativeCratePattern {
    pub(crate) prefix: String,
    pub(crate) suffix: String,
}

impl NativeCratePattern {
    pub(crate) fn matches(&self, name: &str) -> bool {
        name.len() >= self.prefix.len() + self.suffix.len()
            && name.starts_with(&self.prefix)
            && name.ends_with(&self.suffix)
    }

    pub(crate) fn validate(&self) -> Result<(), String> {
        if self.prefix.is_empty()
            || self.prefix.len() > 1024
            || self.suffix.len() > 128
            || self
                .prefix
                .chars()
                .chain(self.suffix.chars())
                .any(|character| matches!(character, '\0' | '/' | '\\'))
        {
            return Err("native crate filename query is invalid".into());
        }
        Ok(())
    }
}

/// The retained filename index actually searched by rustc, not a later scan.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct NativeCrateSearch {
    pub(crate) directory: String,
    pub(crate) patterns: Vec<NativeCratePattern>,
    pub(crate) files: Vec<String>,
}

/// Whether this compilation can consume assembler inputs outside dep-info.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum NativeAssemblyObservation {
    NoCodegen,
    Absent,
    Present,
    ImportedLtoUnobserved,
}

/// Backend work observed after code generation has completed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum NativeCodegenObservation {
    NotRun,
    Llvm,
    Cranelift { separate_assembly: bool },
    Unsupported,
}

impl NativeCodegenObservation {
    pub(crate) fn certifies_no_external_tools(self) -> bool {
        matches!(
            self,
            Self::Llvm
                | Self::Cranelift {
                    separate_assembly: false
                }
        )
    }
}

pub(crate) const MAX_MACRO_PATH_READS: usize = 4096;
pub(crate) const MAX_MACRO_PATH_BYTES: usize = 4096;
pub(crate) const MAX_MACRO_ENVIRONMENT_READS: usize = 1024;
pub(crate) const MAX_MACRO_ENVIRONMENT_NAME_BYTES: usize = 1024;
pub(crate) const MAX_MACRO_SPAWNS: usize = 64;
pub(crate) const MAX_MACRO_SPAWN_ARGUMENTS: usize = 256;
pub(crate) const MAX_MACRO_UNOBSERVABLE_IMPORTS: usize = 64;
pub(crate) const MAX_MACRO_IMPORT_NAME_BYTES: usize = 256;

/// How a procedural macro reached one path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum NativeMacroPathAccess {
    /// Existence, type, or link target, such as `stat`, `access`, or `readlink`.
    Entry,
    /// Contents opened for reading.
    Contents,
    /// Directory entries listed.
    Listing,
    /// Canonical resolution, which follows the link state of every ancestor.
    Resolution,
}

/// One path a procedural macro read, spelled as the absolute path the operating system resolved.
/// The spelling can contain `..` components, because resolving them lexically ignores symbolic links.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct NativeMacroPathRead {
    pub(crate) path: String,
    pub(crate) access: NativeMacroPathAccess,
}

/// A process a procedural macro started with the inherited environment and working directory.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct NativeMacroSpawn {
    pub(crate) program: String,
    pub(crate) arguments: Vec<String>,
}

/// An effect of procedural-macro execution that no observation can bind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum NativeMacroUnobservable {
    /// The host cannot observe a loaded macro, for example a kernel without seccomp user notification.
    ObservationUnavailable,
    /// The macro imports a function outside the classified set.
    ImportUnclassified,
    /// The macro loads a shared library other than the system C library.
    DynamicDependency,
    /// The macro runs load-time initializers that execute before observation.
    Initializer,
    /// The macro issues system calls without the C library, and the host cannot observe them.
    RawSystemCall,
    /// The macro forks, executes, or starts a process with a changed environment or directory.
    ProcessControl,
    Network,
    FileWrite,
    EnvironmentWrite,
    /// The macro read the whole environment instead of named variables.
    EnvironmentEnumeration,
    DynamicLoad,
    ExecutableMemory,
    WorkingDirectory,
    /// The macro read host identity, such as the host name or user database.
    HostState,
    /// A path is not UTF-8 or names an open descriptor that cannot be resolved.
    PathUnavailable,
    ObservationLimit,
}

/// Everything loaded procedural macros read during one compiler run.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct NativeMacroObservation {
    pub(crate) paths: Vec<NativeMacroPathRead>,
    pub(crate) environment: Vec<String>,
    pub(crate) spawns: Vec<NativeMacroSpawn>,
    pub(crate) unobservable: Vec<NativeMacroUnobservable>,
    /// Imported symbols that made the observation incomplete, so a `procedural_macro_import_unclassified` bypass
    /// names them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) unobservable_imports: Vec<String>,
}

impl NativeMacroObservation {
    pub(crate) fn validate(&self) -> Result<(), String> {
        let valid = self.paths.len() <= MAX_MACRO_PATH_READS
            && self.paths.windows(2).all(|pair| pair[0] < pair[1])
            && self.paths.iter().all(|read| {
                read.path.len() <= MAX_MACRO_PATH_BYTES
                    && !read.path.contains('\0')
                    && Path::new(&read.path).is_absolute()
            })
            && self.environment.len() <= MAX_MACRO_ENVIRONMENT_READS
            && self.environment.windows(2).all(|pair| pair[0] < pair[1])
            && self.environment.iter().all(|name| {
                !name.is_empty() && name.len() <= MAX_MACRO_ENVIRONMENT_NAME_BYTES && !name.contains(['\0', '='])
            })
            && self.spawns.len() <= MAX_MACRO_SPAWNS
            && self.spawns.windows(2).all(|pair| pair[0] < pair[1])
            && self.spawns.iter().all(|spawn| {
                !spawn.program.is_empty()
                    && spawn.program.len() <= MAX_MACRO_PATH_BYTES
                    && !spawn.program.contains('\0')
                    && spawn.arguments.len() <= MAX_MACRO_SPAWN_ARGUMENTS
                    && spawn
                        .arguments
                        .iter()
                        .all(|argument| argument.len() <= MAX_MACRO_PATH_BYTES && !argument.contains('\0'))
            })
            && self.unobservable.windows(2).all(|pair| pair[0] < pair[1])
            && self.unobservable_imports.len() <= MAX_MACRO_UNOBSERVABLE_IMPORTS
            && self.unobservable_imports.windows(2).all(|pair| pair[0] < pair[1])
            && self
                .unobservable_imports
                .iter()
                .all(|name| !name.is_empty() && name.len() <= MAX_MACRO_IMPORT_NAME_BYTES && !name.contains('\0'))
            && (self.unobservable_imports.is_empty()
                || self.unobservable.contains(&NativeMacroUnobservable::ImportUnclassified));
        if valid {
            Ok(())
        } else {
            Err("procedural-macro observation has incompatible authority".into())
        }
    }
}

pub(crate) const MAX_NATIVE_LIBRARY_SEARCHES: usize = 4096;
pub(crate) const MAX_NATIVE_LIBRARY_PROBES: usize = 4096;
const MAX_NATIVE_LIBRARY_NAME_BYTES: usize = 1024;

/// The file forms rustc tests when it searches for a native library by name itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum NativeLibraryForm {
    /// A static archive, which rustc bundles into an rlib or staticlib, or passes to the linker by path.
    Static,
    /// An MSVC import library, which rustc passes to the linker by path.
    Import,
}

/// One candidate file of a native-library search, and whether it existed when the driver tested it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct NativeLibraryProbe {
    /// The `-L` directory, spelled as rustc received it and made absolute.
    pub(crate) directory: String,
    pub(crate) file: String,
    pub(crate) present: bool,
}

/// One native-library search that rustc performs itself: every candidate it can test, in its order. Rustc
/// selects the first candidate that exists. The candidates depend only on the library, the `-L` arguments,
/// and the target, so they are the same in every execution of one action; which one exists can change.
/// The linker's own library searches are not reported; the linker witness binds them.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct NativeLibrarySearch {
    pub(crate) name: String,
    pub(crate) form: NativeLibraryForm,
    pub(crate) verbatim: bool,
    pub(crate) probes: Vec<NativeLibraryProbe>,
}

/// Whether `name` can name a native library or one of its candidate files.
///
/// A name can hold path separators: rustc tests `directory.join(file)`, so a verbatim name such as the
/// MSVC linker directive `/defaultlib:msvcrt` names one absolute candidate in every directory.
pub(crate) fn native_library_name_valid(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= MAX_NATIVE_LIBRARY_NAME_BYTES
        && !name.contains('\0')
        && name != "."
        && name != ".."
}

/// Whether rustc can test `file` when it searches for library `name`: the name itself when verbatim,
/// otherwise the name with a target prefix and suffix, neither of which holds a path separator.
pub(crate) fn native_library_candidate_valid(name: &str, verbatim: bool, file: &str) -> bool {
    native_library_name_valid(file)
        && if verbatim {
            file == name
        } else {
            file.match_indices(name).any(|(start, _)| {
                file.get(..start)
                    .zip(file.get(start + name.len()..))
                    .is_some_and(|(prefix, suffix)| !prefix.contains(['/', '\\']) && !suffix.contains(['/', '\\']))
            })
        }
}

impl NativeLibrarySearch {
    pub(crate) fn validate(&self) -> Result<(), String> {
        let mut paths = std::collections::BTreeSet::new();
        let valid = native_library_name_valid(&self.name)
            && self.probes.len() <= MAX_NATIVE_LIBRARY_PROBES
            && self.probes.iter().all(|probe| {
                absolute_input_path(&probe.directory)
                    && native_library_candidate_valid(&self.name, self.verbatim, &probe.file)
                    && paths.insert((probe.directory.as_str(), probe.file.as_str()))
            });
        if valid {
            Ok(())
        } else {
            Err("native library search has incompatible authority".into())
        }
    }
}

/// Complete selected crate sources and assembly coverage from one compiler run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct NativeInputObservation {
    pub(crate) version: u32,
    pub(crate) request_identity: String,
    pub(crate) crates: Vec<NativeCrateSource>,
    pub(crate) searches: Vec<NativeCrateSearch>,
    /// Whether rustc needs only the metadata of the crates it loads: every crate type is an rlib, or the
    /// compilation produces no object code. Rustc then skips a crate's `.rlib` once the `.rmeta` with the
    /// same filename hash supplies its metadata.
    pub(crate) metadata_only: bool,
    /// Native-library searches that rustc performs itself, sorted by library.
    pub(crate) native_libraries: Vec<NativeLibrarySearch>,
    pub(crate) assembly: NativeAssemblyObservation,
    pub(crate) codegen: NativeCodegenObservation,
    /// `None` when the compiler loaded no procedural macro.
    pub(crate) macros: Option<NativeMacroObservation>,
}

impl NativeInputObservation {
    pub(crate) fn decode(bytes: &[u8], invocation: &NativeInputInvocation) -> Result<Self, String> {
        if bytes.is_empty() || bytes.len() as u64 > MAX_NATIVE_INPUT_OBSERVATION_BYTES {
            return Err("native input observation exceeds its byte bound".into());
        }
        let observation: Self = serde_json::from_slice(bytes).map_err(|error| error.to_string())?;
        if observation.encode(invocation)? != bytes {
            return Err("native input observation is not canonical JSON".into());
        }
        Ok(observation)
    }

    pub(crate) fn encode(&self, invocation: &NativeInputInvocation) -> Result<Vec<u8>, String> {
        if self.version != NATIVE_INPUT_PROTOCOL_VERSION
            || self.request_identity != invocation.identity()?
            || self.crates.len() > 4096
            || self.crates.windows(2).any(|pair| pair[0] >= pair[1])
            || self.crates.iter().any(|source| {
                source.name.is_empty()
                    || source.name.len() > 256
                    || !source
                        .name
                        .chars()
                        .all(|character| character == '_' || character.is_alphanumeric())
                    || source.files.is_empty()
                    || source.files.len() > 4
                    || source.files.windows(2).any(|pair| pair[0] >= pair[1])
                    || source.files.iter().any(|path| !absolute_input_path(path))
            })
            || self.searches.len() > 512
            || self
                .searches
                .windows(2)
                .any(|pair| pair[0].directory >= pair[1].directory)
            || self.searches.iter().any(|search| {
                !absolute_input_path(&search.directory)
                    || search.patterns.is_empty()
                    || search.patterns.len() > 4096 * 10
                    || search.patterns.windows(2).any(|pair| pair[0] >= pair[1])
                    || search.patterns.iter().any(|pattern| pattern.validate().is_err())
                    || search.files.len() > 100_000
                    || search.files.windows(2).any(|pair| pair[0] >= pair[1])
                    || search.files.iter().any(|name| {
                        name.is_empty()
                            || name.chars().any(|character| matches!(character, '\0' | '/' | '\\'))
                            || !search.patterns.iter().any(|pattern| pattern.matches(name))
                    })
            })
        {
            return Err("native input observation has incompatible authority".into());
        }
        if self.native_libraries.len() > MAX_NATIVE_LIBRARY_SEARCHES
            || self.native_libraries.windows(2).any(|pair| {
                (&pair[0].name, pair[0].form, pair[0].verbatim) >= (&pair[1].name, pair[1].form, pair[1].verbatim)
            })
        {
            return Err("native input observation has incompatible authority".into());
        }
        self.native_libraries
            .iter()
            .try_for_each(NativeLibrarySearch::validate)?;
        if let Some(macros) = &self.macros {
            macros.validate()?;
        }
        let bytes = serde_json::to_vec(self).map_err(|error| error.to_string())?;
        if bytes.len() as u64 > MAX_NATIVE_INPUT_OBSERVATION_BYTES {
            return Err("native input observation exceeds its byte bound".into());
        }
        Ok(bytes)
    }
}

/// Bind the unmodified rustc arguments (excluding `argv[0]`) and working directory.
pub(crate) fn native_invocation_digest(arguments: &[String], current_directory: &Path) -> Result<String, String> {
    let current_directory = current_directory
        .to_str()
        .filter(|path| absolute_input_path(path))
        .ok_or_else(|| "native input working directory is not an absolute UTF-8 path".to_string())?;
    let bytes = serde_json::to_vec(&(NATIVE_INPUT_PROTOCOL_VERSION, arguments, current_directory))
        .map_err(|error| error.to_string())?;
    Ok(hex_digest(&bytes))
}

fn absolute_input_path(path: &str) -> bool {
    !path.contains('\0')
        && Path::new(path).is_absolute()
        && !Path::new(path)
            .components()
            .any(|component| matches!(component, Component::CurDir | Component::ParentDir))
}

fn is_digest(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn hex_digest(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut encoded = String::with_capacity(64);
    for byte in Sha256::digest(bytes) {
        encoded.push(char::from(HEX[usize::from(byte >> 4)]));
        encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    encoded
}

#[cfg(test)]
mod tests {
    use super::*;

    fn invocation() -> NativeInputInvocation {
        NativeInputInvocation {
            version: NATIVE_INPUT_PROTOCOL_VERSION,
            phase: NativeInputPhase::Compilation,
            source_working_directory: None,
            nonce: "1".repeat(64),
            action_identity: "native-action".into(),
            invocation_digest: "2".repeat(64),
            result_path: std::env::temp_dir().join("native-result.json").to_str().unwrap().into(),
        }
    }

    #[test]
    fn invocation_rejects_noncanonical_and_unknown_authority() {
        let invocation = invocation();
        let mut bytes = serde_json::to_vec(&invocation).unwrap();
        bytes.push(b'\n');
        assert_eq!(
            NativeInputInvocation::decode(&bytes).unwrap_err(),
            "native input invocation is not canonical JSON"
        );
        let mut value = serde_json::to_value(&invocation).unwrap();
        value["extra"] = true.into();
        assert!(
            NativeInputInvocation::decode(&serde_json::to_vec(&value).unwrap())
                .unwrap_err()
                .contains("unknown field")
        );
    }

    #[test]
    fn observation_rejects_another_request_and_duplicate_sources() {
        let mut invocation = invocation();
        let observation = NativeInputObservation {
            version: NATIVE_INPUT_PROTOCOL_VERSION,
            request_identity: invocation.identity().unwrap(),
            crates: vec![],
            searches: vec![],
            metadata_only: false,
            native_libraries: vec![],
            assembly: NativeAssemblyObservation::NoCodegen,
            codegen: NativeCodegenObservation::NotRun,
            macros: None,
        };
        let bytes = observation.encode(&invocation).unwrap();
        invocation.nonce = "3".repeat(64);
        assert_eq!(
            NativeInputObservation::decode(&bytes, &invocation).unwrap_err(),
            "native input observation has incompatible authority"
        );
        let source = NativeCrateSource {
            name: "dependency".into(),
            files: vec![invocation.result_path.clone()],
        };
        let duplicated = NativeInputObservation {
            request_identity: invocation.identity().unwrap(),
            crates: vec![source.clone(), source],
            ..observation
        };
        assert_eq!(
            duplicated.encode(&invocation).unwrap_err(),
            "native input observation has incompatible authority"
        );
    }

    #[test]
    fn native_library_search_admits_only_rustc_ordered_candidates() {
        let invocation = invocation();
        let directory = std::env::temp_dir().to_str().unwrap().to_string();
        let probe = |file: &str, present| NativeLibraryProbe {
            directory: directory.clone(),
            file: file.into(),
            present,
        };
        let search = |name: &str, verbatim, probes| NativeLibrarySearch {
            name: name.into(),
            form: NativeLibraryForm::Static,
            verbatim,
            probes,
        };
        let observation = |native_libraries| NativeInputObservation {
            version: NATIVE_INPUT_PROTOCOL_VERSION,
            request_identity: invocation.identity().unwrap(),
            crates: vec![],
            searches: vec![],
            metadata_only: false,
            native_libraries,
            assembly: NativeAssemblyObservation::NoCodegen,
            codegen: NativeCodegenObservation::NotRun,
            macros: None,
        };
        // Every candidate is reported, including those after the one rustc selects. A verbatim name is the
        // path that rustc joins to each directory, such as an MSVC linker directive.
        let valid = observation(vec![
            search("/defaultlib:msvcrt", true, vec![probe("/defaultlib:msvcrt", false)]),
            search("bar", false, vec![probe("libbar.a", true), probe("bar.lib", true)]),
            search("foo", true, vec![probe("foo", false)]),
            search("nested/libqux.a", true, vec![probe("nested/libqux.a", false)]),
        ]);
        let bytes = valid.encode(&invocation).unwrap();
        assert_eq!(NativeInputObservation::decode(&bytes, &invocation).unwrap(), valid);
        for (case, invalid) in [
            (
                "a candidate for another library",
                vec![search("bar", false, vec![probe("libbaz.a", false)])],
            ),
            (
                "a verbatim candidate with another name",
                vec![search("bar", true, vec![probe("libbar.a", false)])],
            ),
            (
                "a repeated candidate",
                vec![search(
                    "bar",
                    false,
                    vec![probe("libbar.a", false), probe("libbar.a", false)],
                )],
            ),
            (
                "a candidate path",
                vec![search("bar", false, vec![probe("lib/libbar.a", false)])],
            ),
            (
                "unsorted libraries",
                vec![search("foo", false, vec![]), search("bar", false, vec![])],
            ),
        ] {
            assert!(observation(invalid).encode(&invocation).is_err(), "{case}");
        }
    }

    #[test]
    fn invocation_identity_binds_the_observation_phase() {
        let compilation = invocation();
        let resolution = NativeInputInvocation {
            phase: NativeInputPhase::Resolution,
            ..compilation.clone()
        };
        assert_ne!(compilation.identity().unwrap(), resolution.identity().unwrap());
        let encoded = serde_json::to_vec(&resolution).unwrap();
        assert_eq!(NativeInputInvocation::decode(&encoded).unwrap(), resolution);
    }

    #[test]
    fn invocation_digest_binds_argument_boundaries_and_directory() {
        let current = std::env::temp_dir();
        let digest = native_invocation_digest(&["--cfg".into(), "a b".into()], &current).unwrap();
        assert_ne!(
            digest,
            native_invocation_digest(&["--cfg a".into(), "b".into()], &current).unwrap()
        );
        assert_ne!(
            digest,
            native_invocation_digest(&["--cfg".into(), "a b".into()], &current.join("other")).unwrap()
        );
    }
}