refactor(snix/glue/fetchers): cleanup

We can reject early if invalid keys are provided in the attrset, no need
to look at values already.

Also, restructure the code parsing and extracting a sha256 by
destructuring the enum, rather than grabbing a slice and trying to
convert to a fixed-size array.

Change-Id: I1bb067133e398626df25b9c1cf99926c6d836a19
Reviewed-on: https://cl.snix.dev/c/snix/+/30559
Autosubmit: Florian Klink <flokli@flokli.de>
Reviewed-by: edef <edef@edef.eu>
Tested-by: besadii
This commit is contained in:
Florian Klink 2025-06-04 02:23:18 +03:00 committed by clbot
parent f6c66af33d
commit ea861bba67

View file

@ -47,6 +47,15 @@ async fn extract_fetch_args(
actual: args.type_of(), actual: args.type_of(),
})?; })?;
// Reject disallowed attrset keys, to match Nix' behaviour.
// We complain about the first unexpected key we find in the list.
const VALID_KEYS: [&[u8]; 3] = [b"url", b"name", b"sha256"];
if let Some(first_invalid_key) = attrs.keys().find(|k| !&VALID_KEYS.contains(&k.as_bytes())) {
return Err(ErrorKind::UnexpectedArgumentBuiltin(
first_invalid_key.clone(),
));
}
let url_str = match select_string(co, &attrs, "url").await? { let url_str = match select_string(co, &attrs, "url").await? {
Ok(s) => s.ok_or_else(|| ErrorKind::AttributeNotFound { name: "url".into() })?, Ok(s) => s.ok_or_else(|| ErrorKind::AttributeNotFound { name: "url".into() })?,
Err(cek) => return Ok(Err(cek)), Err(cek) => return Ok(Err(cek)),
@ -60,28 +69,19 @@ async fn extract_fetch_args(
Err(cek) => return Ok(Err(cek)), Err(cek) => return Ok(Err(cek)),
}; };
// Disallow other attrset keys, to match Nix' behaviour. Ok(Ok(NixFetchArgs {
// We complain about the first unexpected key we find in the list. url: Url::parse(&url_str).map_err(|e| ErrorKind::SnixError(Rc::new(e)))?,
const VALID_KEYS: [&[u8]; 3] = [b"url", b"name", b"sha256"]; name,
if let Some(first_invalid_key) = attrs.keys().find(|k| !&VALID_KEYS.contains(&k.as_bytes())) { // parse the sha256 string into a digest, and bail out if it's not sha256.
return Err(ErrorKind::UnexpectedArgumentBuiltin( sha256: sha256_str
first_invalid_key.clone(), .map(
)); |sha256_str| match NixHash::from_str(&sha256_str, Some(HashAlgo::Sha256)) {
} Ok(NixHash::Sha256(digest)) => Ok(digest),
_ => Err(ErrorKind::InvalidHash(sha256_str)),
// parse the sha256 string into a digest. },
let sha256 = sha256_str )
.map(|x| { .transpose()?,
NixHash::from_str(&x, Some(HashAlgo::Sha256)) }))
.map(|x| x.digest_as_bytes().try_into().expect("is sha256"))
.map_err(|e| ErrorKind::InvalidHash(e.to_string()))
})
.transpose()?;
// Parse the URL.
let url = Url::parse(&url_str).map_err(|e| ErrorKind::SnixError(Rc::new(e)))?;
Ok(Ok(NixFetchArgs { url, name, sha256 }))
} }
#[allow(unused_variables)] // for the `state` arg, for now #[allow(unused_variables)] // for the `state` arg, for now