nextest_runner/cargo_config/
custom_platform.rs1use super::TargetTripleSource;
5use crate::errors::TargetTripleError;
6use camino::{Utf8Path, Utf8PathBuf};
7use camino_tempfile::Utf8TempDir;
8use std::{fs::File, io::Write};
9
10#[derive(Debug)]
14pub struct ExtractedCustomPlatform {
15 source: TargetTripleSource,
16 dir: Utf8TempDir,
17 path: Utf8PathBuf,
18}
19
20impl ExtractedCustomPlatform {
21 pub fn new(
23 triple_str: &str,
24 json: &str,
25 source: TargetTripleSource,
26 ) -> Result<Self, TargetTripleError> {
27 if Utf8Path::new(triple_str).file_name() != Some(triple_str) {
35 return Err(TargetTripleError::CustomPlatformInvalidTriple {
36 triple_source: source,
37 triple: triple_str.to_owned(),
38 });
39 }
40
41 let temp_dir = camino_tempfile::Builder::new()
42 .prefix("nextest-custom-target-")
43 .rand_bytes(5)
44 .tempdir()
45 .map_err(|error| TargetTripleError::CustomPlatformTempDirError {
46 source: source.clone(),
47 error,
48 })?;
49
50 let path = temp_dir.path().join(format!("{triple_str}.json"));
51
52 File::create_new(&path)
55 .and_then(|mut file| file.write_all(json.as_bytes()))
56 .map_err(|error| TargetTripleError::CustomPlatformWriteError {
57 source: source.clone(),
58 path: path.clone(),
59 error,
60 })?;
61
62 Ok(Self {
63 source,
64 dir: temp_dir,
65 path,
66 })
67 }
68
69 pub fn source(&self) -> &TargetTripleSource {
71 &self.source
72 }
73
74 pub fn dir(&self) -> &Utf8TempDir {
76 &self.dir
77 }
78
79 pub fn path(&self) -> &Utf8Path {
81 &self.path
82 }
83
84 pub fn close(self) -> Result<(), TargetTripleError> {
89 let dir_path = self.dir.path().to_owned();
90 self.dir
91 .close()
92 .map_err(|error| TargetTripleError::CustomPlatformCloseError {
93 source: self.source,
94 dir_path,
95 error,
96 })
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103 use crate::cargo_config::{
104 CargoTargetArg, TargetDefinitionLocation, TargetTriple,
105 test_helpers::{custom_platform, setup_temp_dir},
106 };
107 use camino::Utf8Component;
108 use color_eyre::eyre::{Context, Result, bail, eyre};
109
110 #[test]
111 fn test_extracted_custom_platform() -> Result<()> {
112 let target = {
118 let temp_dir = setup_temp_dir()?;
121 let platform_path = temp_dir.path().join("custom-target/my-target.json");
122
123 TargetTriple::custom_from_path(
125 &platform_path,
126 TargetTripleSource::CliOption,
127 temp_dir.path(),
128 )?
129 };
130
131 let summary = target.platform.to_summary();
133
134 let target2 = TargetTriple::deserialize(Some(summary))
136 .wrap_err("deserializing target triple")?
137 .ok_or_else(|| eyre!("deserializing target triple resulted in None"))?;
138
139 assert_eq!(target2.source, TargetTripleSource::Metadata);
140 assert!(
141 matches!(
142 target2.location,
143 TargetDefinitionLocation::MetadataCustom(_)
144 ),
145 "triple2.location should be MetadataCustom: {:?}",
146 target2.location
147 );
148
149 let arg = target2
151 .to_cargo_target_arg()
152 .wrap_err("converting to cargo target arg")?;
153 let extracted = match &arg {
154 CargoTargetArg::Extracted(extracted) => extracted,
155 _ => {
156 bail!("expected CargoTargetArg::Extracted, found {:?}", arg);
157 }
158 };
159
160 assert!(extracted.path().is_absolute(), "path should be absolute");
162 assert!(
163 extracted.path().ends_with("my-target.json"),
164 "extracted path should end with 'my-target.json'"
165 );
166 assert_eq!(
167 arg.to_string(),
168 extracted.path(),
169 "arg matches extracted path"
170 );
171
172 let target3 = TargetTriple::custom_from_path(
174 extracted.path(),
175 TargetTripleSource::CliOption,
176 extracted.dir().path(),
177 )?;
178 assert_eq!(target3.platform, target.platform, "platform roundtrips");
179
180 Ok(())
181 }
182
183 #[test]
184 fn test_extracted_custom_platform_invalid_triple() {
185 let json = r#"{"llvm-target": "x86_64-unknown-none", "arch": "x86_64"}"#;
186
187 let mut invalid = vec![
188 "",
189 ".",
190 "..",
191 "foo/bar",
192 "../escape",
193 "/absolute/path",
194 "./foo",
195 ];
196 if cfg!(windows) {
197 invalid.extend([
198 "foo\\bar",
199 "..\\escape",
200 "C:foo",
201 "C:\\absolute",
202 "\\\\server\\share",
203 ]);
204 }
205
206 for triple in invalid {
207 let error = ExtractedCustomPlatform::new(triple, json, TargetTripleSource::Metadata)
208 .expect_err(&format!("triple {triple:?} should be rejected"));
209 let TargetTripleError::CustomPlatformInvalidTriple {
210 triple: error_triple,
211 ..
212 } = &error
213 else {
214 panic!("triple {triple:?}: expected CustomPlatformInvalidTriple, found {error:?}");
215 };
216 assert_eq!(error_triple, triple, "error triple for {triple:?}");
217 }
218
219 let valid = ["my-target", "x86_64-unknown-none", "foo..bar", ".hidden"];
220 for triple in valid {
221 let extracted =
222 ExtractedCustomPlatform::new(triple, json, TargetTripleSource::Metadata)
223 .unwrap_or_else(|error| {
224 panic!("triple {triple:?} should be accepted: {error}")
225 });
226 assert_eq!(
227 extracted.path(),
228 extracted.dir().path().join(format!("{triple}.json")),
229 "extracted path for triple {triple:?}"
230 );
231 assert_eq!(
232 std::fs::read_to_string(extracted.path()).expect("read extracted JSON"),
233 json,
234 "extracted JSON for triple {triple:?}"
235 );
236 extracted.close().expect("closed temp dir");
237 }
238 }
239
240 #[test]
241 fn test_metadata_custom_triple_path_traversal() -> Result<()> {
242 let escape_dir = camino_tempfile::tempdir().wrap_err("creating escape dir")?;
243 let escape_stem = escape_dir.path().join("escaped");
244
245 let relative: Utf8PathBuf = std::iter::repeat_n(Utf8Component::ParentDir, 32)
248 .chain(
249 escape_stem
250 .components()
251 .filter(|component| match component {
252 Utf8Component::Normal(_) => true,
253 Utf8Component::Prefix(_)
254 | Utf8Component::RootDir
255 | Utf8Component::CurDir
256 | Utf8Component::ParentDir => false,
257 }),
258 )
259 .collect();
260
261 for triple in [relative.to_string(), escape_stem.to_string()] {
262 let mut summary = custom_platform().to_summary();
263 summary.triple = triple.clone();
264 let target = TargetTriple::deserialize(Some(summary))
265 .wrap_err_with(|| format!("deserializing target triple {triple:?}"))?
266 .ok_or_else(|| eyre!("deserializing {triple:?} resulted in None"))?;
267
268 match target.to_cargo_target_arg() {
269 Err(TargetTripleError::CustomPlatformInvalidTriple { .. }) => {}
270 other => {
271 bail!(
272 "triple {triple:?}: expected CustomPlatformInvalidTriple, found {other:?}"
273 );
274 }
275 }
276 assert!(
277 !escape_dir.path().join("escaped.json").exists(),
278 "triple {triple:?} must not write outside the temp dir"
279 );
280 }
281
282 Ok(())
283 }
284}