Skip to content

The design language that makes your AI harness better at design.

JavaScript

Fix non-UTF-8 environment handling (#888)

Paul Bakaus909726c7e8be
diff --git a/Cargo.lock b/Cargo.lock
index e2d032b70..542c16dc3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -548,6 +548,7 @@ name = "impeccable-browser"
version = "0.1.8"
dependencies = [
"base64",
+ "impeccable-common",
"impeccable-core",
"impeccable-detect",
"percent-encoding",
diff --git a/crates/browser/Cargo.toml b/crates/browser/Cargo.toml
index 2a0a7c9c2..97ebac58e 100644
--- a/crates/browser/Cargo.toml
+++ b/crates/browser/Cargo.toml
@@ -6,6 +6,7 @@ license.workspace = true
publish.workspace = true
[dependencies]
+impeccable-common = { workspace = true }
impeccable-core = { workspace = true }
impeccable-detect = { workspace = true }
serde_json = { workspace = true, features = ["preserve_order", "float_roundtrip"] }
diff --git a/crates/browser/src/lib.rs b/crates/browser/src/lib.rs
index a30db2a74..8bbf9b302 100644
--- a/crates/browser/src/lib.rs
+++ b/crates/browser/src/lib.rs
@@ -55,7 +55,7 @@ impl BrowserEngine {
/// An engine reading the real process environment.
pub fn from_process_env() -> Self {
- BrowserEngine::new(std::env::vars().collect())
+ BrowserEngine::new(impeccable_common::process_env())
}
/// JS `launchArgs = process.env.CI ? ['--no-sandbox','--disable-setuid-sandbox'] : []`.
diff --git a/crates/cli/src/asset_capture.rs b/crates/cli/src/asset_capture.rs
index 8921962aa..bc2b87087 100644
--- a/crates/cli/src/asset_capture.rs
+++ b/crates/cli/src/asset_capture.rs
@@ -21,7 +21,7 @@ pub struct CdpAssetRenderer {
impl CdpAssetRenderer {
pub fn from_process_env() -> Self {
Self {
- env: std::env::vars().collect(),
+ env: impeccable_common::process_env(),
}
}
}
diff --git a/crates/cli/src/component_capture.rs b/crates/cli/src/component_capture.rs
index 9815dca45..992e576db 100644
--- a/crates/cli/src/component_capture.rs
+++ b/crates/cli/src/component_capture.rs
@@ -239,7 +239,7 @@ impl ComponentCapturer for NativeComponentCapturer {
if reference_size["width"] != width || reference_size["height"] != height {
return Err("comp dimensions do not match its image".into());
}
- let env = std::env::vars().collect();
+ let env = impeccable_common::process_env();
let exe =
discovery::find_browser(&env).map_err(|e| format!("browser unavailable: {e:?}"))?;
let mut browser = Browser::launch(&exe, &[], false).map_err(|e| e.message)?;
diff --git a/crates/cli/src/font_render.rs b/crates/cli/src/font_render.rs
index fbb41b48a..d2399a946 100644
--- a/crates/cli/src/font_render.rs
+++ b/crates/cli/src/font_render.rs
@@ -26,7 +26,7 @@ pub struct CdpFontRenderer {
impl CdpFontRenderer {
pub fn from_process_env() -> Self {
- CdpFontRenderer { env: std::env::vars().collect() }
+ CdpFontRenderer { env: impeccable_common::process_env() }
}
fn launch(&self) -> Option<Browser> {
diff --git a/crates/cli/tests/non_utf8_env.rs b/crates/cli/tests/non_utf8_env.rs
new file mode 100644
index 000000000..c6e3f19ad
--- /dev/null
+++ b/crates/cli/tests/non_utf8_env.rs
@@ -0,0 +1,43 @@
+#![cfg(unix)]
+
+use std::ffi::OsString;
+use std::os::unix::ffi::OsStringExt;
+use std::path::PathBuf;
+use std::process::Command;
+
+fn command_with_non_utf8_env() -> Command {
+ let mut command = Command::new(env!("CARGO_BIN_EXE_impeccable"));
+ command.env("ABBR_TIPS_PROMPT", OsString::from_vec(vec![0xff]));
+ command
+}
+
+#[test]
+fn context_ignores_non_utf8_environment_values() {
+ let output = command_with_non_utf8_env()
+ .arg("context")
+ .output()
+ .expect("run context");
+
+ assert!(
+ output.status.success(),
+ "context failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+}
+
+#[test]
+fn detect_ignores_non_utf8_environment_values() {
+ let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../../tests/fixtures/antipatterns/radial-spotlight-glow.html");
+ let output = command_with_non_utf8_env()
+ .args(["detect", "--json", "--scope", "layout"])
+ .arg(fixture)
+ .output()
+ .expect("run detect");
+
+ assert!(
+ output.status.success(),
+ "detect failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+}
diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs
index f4b27deea..c699e39c6 100644
--- a/crates/common/src/lib.rs
+++ b/crates/common/src/lib.rs
@@ -10,9 +10,27 @@ pub mod jsp;
pub mod proc;
use std::collections::HashMap;
+use std::ffi::OsString;
use std::io::{Read, Write};
use std::path::PathBuf;
+/// The process environment entries whose names and values are valid UTF-8.
+///
+/// Unix permits arbitrary bytes in both halves of an environment entry, while
+/// the engine's verb APIs intentionally use strings. `std::env::vars()` panics
+/// on the first non-Unicode entry, so collect from `vars_os()` and ignore only
+/// entries that cannot be represented by those APIs.
+pub fn process_env() -> HashMap<String, String> {
+ utf8_env(std::env::vars_os())
+}
+
+fn utf8_env(entries: impl IntoIterator<Item = (OsString, OsString)>) -> HashMap<String, String> {
+ entries
+ .into_iter()
+ .filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?)))
+ .collect()
+}
+
/// Ceiling on how much stdin a verb will ever read. Deliberately generous:
/// the largest legitimate payloads (context/detect JSON, hook envelopes
/// carrying a whole proposed file write) are a few MB at most, so 64 MiB
@@ -40,7 +58,7 @@ impl Io {
stderr: Box::new(std::io::stderr()),
stdin: Some(Box::new(std::io::stdin())),
stdin_cache: None,
- env: std::env::vars().collect(),
+ env: process_env(),
cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
stdin_is_tty: is_stdin_tty(),
}
@@ -173,6 +191,21 @@ impl Io {
mod tests {
use super::*;
+ #[cfg(unix)]
+ #[test]
+ fn utf8_env_ignores_non_unicode_entries() {
+ use std::os::unix::ffi::OsStringExt;
+
+ let env = utf8_env([
+ (OsString::from("HOME"), OsString::from("/tmp/home")),
+ (OsString::from("BAD_VALUE"), OsString::from_vec(vec![0xff])),
+ (OsString::from_vec(vec![0xfe]), OsString::from("bad key")),
+ ]);
+
+ assert_eq!(env.get("HOME").map(String::as_str), Some("/tmp/home"));
+ assert_eq!(env.len(), 1);
+ }
+
#[test]
fn stdin_is_capped_at_the_ceiling() {
// An unbounded pipe (here: an infinite reader) must not grow the