Skip to content

Commit cc32a29

Browse files
authored
fix(runtime): better error message with Deno.env.get/set (#15966)
1 parent 35fe9ee commit cc32a29

File tree

2 files changed

+58
-6
lines changed

2 files changed

+58
-6
lines changed

cli/tests/unit/os_test.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,40 @@ Deno.test(
116116
},
117117
);
118118

119+
Deno.test({ permissions: { env: true } }, function envInvalidChars() {
120+
assertThrows(() => Deno.env.get(""), TypeError, "Key is an empty string");
121+
assertThrows(
122+
() => Deno.env.get("\0"),
123+
TypeError,
124+
'Key contains invalid characters: "\\0"',
125+
);
126+
assertThrows(
127+
() => Deno.env.get("="),
128+
TypeError,
129+
'Key contains invalid characters: "="',
130+
);
131+
assertThrows(
132+
() => Deno.env.set("", "foo"),
133+
TypeError,
134+
"Key is an empty string",
135+
);
136+
assertThrows(
137+
() => Deno.env.set("\0", "foo"),
138+
TypeError,
139+
'Key contains invalid characters: "\\0"',
140+
);
141+
assertThrows(
142+
() => Deno.env.set("=", "foo"),
143+
TypeError,
144+
'Key contains invalid characters: "="',
145+
);
146+
assertThrows(
147+
() => Deno.env.set("foo", "\0"),
148+
TypeError,
149+
'Value contains invalid characters: "\\0"',
150+
);
151+
});
152+
119153
Deno.test(function osPid() {
120154
assert(Deno.pid > 0);
121155
});

runtime/ops/os.rs

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,20 @@ fn op_set_env(
8080
value: String,
8181
) -> Result<(), AnyError> {
8282
state.borrow_mut::<Permissions>().env.check(&key)?;
83-
let invalid_key = key.is_empty() || key.contains(&['=', '\0'] as &[char]);
84-
let invalid_value = value.contains('\0');
85-
if invalid_key || invalid_value {
86-
return Err(type_error("Key or value contains invalid characters."));
83+
if key.is_empty() {
84+
return Err(type_error("Key is an empty string."));
85+
}
86+
if key.contains(&['=', '\0'] as &[char]) {
87+
return Err(type_error(format!(
88+
"Key contains invalid characters: {:?}",
89+
key
90+
)));
91+
}
92+
if value.contains('\0') {
93+
return Err(type_error(format!(
94+
"Value contains invalid characters: {:?}",
95+
value
96+
)));
8797
}
8898
env::set_var(key, value);
8999
Ok(())
@@ -108,9 +118,17 @@ fn op_get_env(
108118
state.borrow_mut::<Permissions>().env.check(&key)?;
109119
}
110120

111-
if key.is_empty() || key.contains(&['=', '\0'] as &[char]) {
112-
return Err(type_error("Key contains invalid characters."));
121+
if key.is_empty() {
122+
return Err(type_error("Key is an empty string."));
113123
}
124+
125+
if key.contains(&['=', '\0'] as &[char]) {
126+
return Err(type_error(format!(
127+
"Key contains invalid characters: {:?}",
128+
key
129+
)));
130+
}
131+
114132
let r = match env::var(key) {
115133
Err(env::VarError::NotPresent) => None,
116134
v => Some(v?),

0 commit comments

Comments
 (0)