1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-24 15:19:26 -05:00

fix(runtime): better error message with Deno.env.get/set (#15966)

This commit is contained in:
Yoshiya Hinosawa 2022-09-21 15:18:58 +09:00 committed by GitHub
parent 35fe9ee530
commit cc32a297da
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 6 deletions

View file

@ -116,6 +116,40 @@ Deno.test(
},
);
Deno.test({ permissions: { env: true } }, function envInvalidChars() {
assertThrows(() => Deno.env.get(""), TypeError, "Key is an empty string");
assertThrows(
() => Deno.env.get("\0"),
TypeError,
'Key contains invalid characters: "\\0"',
);
assertThrows(
() => Deno.env.get("="),
TypeError,
'Key contains invalid characters: "="',
);
assertThrows(
() => Deno.env.set("", "foo"),
TypeError,
"Key is an empty string",
);
assertThrows(
() => Deno.env.set("\0", "foo"),
TypeError,
'Key contains invalid characters: "\\0"',
);
assertThrows(
() => Deno.env.set("=", "foo"),
TypeError,
'Key contains invalid characters: "="',
);
assertThrows(
() => Deno.env.set("foo", "\0"),
TypeError,
'Value contains invalid characters: "\\0"',
);
});
Deno.test(function osPid() {
assert(Deno.pid > 0);
});

View file

@ -80,10 +80,20 @@ fn op_set_env(
value: String,
) -> Result<(), AnyError> {
state.borrow_mut::<Permissions>().env.check(&key)?;
let invalid_key = key.is_empty() || key.contains(&['=', '\0'] as &[char]);
let invalid_value = value.contains('\0');
if invalid_key || invalid_value {
return Err(type_error("Key or value contains invalid characters."));
if key.is_empty() {
return Err(type_error("Key is an empty string."));
}
if key.contains(&['=', '\0'] as &[char]) {
return Err(type_error(format!(
"Key contains invalid characters: {:?}",
key
)));
}
if value.contains('\0') {
return Err(type_error(format!(
"Value contains invalid characters: {:?}",
value
)));
}
env::set_var(key, value);
Ok(())
@ -108,9 +118,17 @@ fn op_get_env(
state.borrow_mut::<Permissions>().env.check(&key)?;
}
if key.is_empty() || key.contains(&['=', '\0'] as &[char]) {
return Err(type_error("Key contains invalid characters."));
if key.is_empty() {
return Err(type_error("Key is an empty string."));
}
if key.contains(&['=', '\0'] as &[char]) {
return Err(type_error(format!(
"Key contains invalid characters: {:?}",
key
)));
}
let r = match env::var(key) {
Err(env::VarError::NotPresent) => None,
v => Some(v?),