Skip to content

Commit 9bca5ed

Browse files
authored
Merge pull request #616 from OpenCoven/fix/577-policy-diagnostics
Identify failed workspace policy admission checks
2 parents 808e04b + 837a10a commit 9bca5ed

4 files changed

Lines changed: 225 additions & 28 deletions

File tree

‎src-rust/crates/cli/src/main.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,10 @@ async fn run() -> anyhow::Result<()> {
507507
anyhow::bail!("Workspace sandbox verification requires exactly one policy file.");
508508
};
509509
let file = Path::new(file);
510-
workspace_scope::WorkspaceScope::read(file, &std::env::current_dir()?)?
510+
let cwd = std::env::current_dir().with_context(|| {
511+
format!("Could not locate the working folder for workspace policy {file:?}")
512+
})?;
513+
workspace_scope::WorkspaceScope::read(file, &cwd)?
511514
.verify(file)
512515
.await?
513516
.write_receipt(std::io::stdout().lock())?;
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
use std::{fs, process::Command};
2+
3+
#[test]
4+
fn both_admission_commands_identify_a_missing_policy_before_emitting_output() {
5+
let temp = tempfile::tempdir().unwrap();
6+
let file = temp.path().join("missing-policy.json");
7+
let cause = fs::symlink_metadata(&file).unwrap_err().to_string();
8+
for args in [
9+
&["--verify-workspace-policy-v1"][..],
10+
&[
11+
"--print",
12+
"--output-format",
13+
"stream-json",
14+
"--chat-workspace-policy-v1",
15+
],
16+
] {
17+
let output = Command::new(env!("CARGO_BIN_EXE_coven-code"))
18+
.args(args)
19+
.arg(&file)
20+
.current_dir(temp.path())
21+
.env_clear()
22+
.envs(
23+
["PATH", "SystemRoot"]
24+
.into_iter()
25+
.filter_map(|key| std::env::var_os(key).map(|value| (key, value))),
26+
)
27+
.env("HOME", temp.path())
28+
.env("COVEN_CODE_HOME", temp.path())
29+
.output()
30+
.unwrap();
31+
assert_eq!(output.status.code(), Some(1), "{output:?}");
32+
assert!(output.stdout.is_empty(), "{output:?}");
33+
let stderr = String::from_utf8(output.stderr).unwrap();
34+
for part in ["inspect workspace policy", &format!("{file:?}"), &cause] {
35+
assert!(stderr.contains(part), "{args:?}: {stderr}");
36+
}
37+
}
38+
}

‎src-rust/crates/tools/src/workspace_scope.rs‎

Lines changed: 85 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -33,19 +33,38 @@ fn invalid(message: &str) -> io::Error {
3333
io::Error::new(io::ErrorKind::InvalidInput, message)
3434
}
3535

36+
fn path_error(operation: &str, path: &Path, error: io::Error) -> io::Error {
37+
io::Error::new(
38+
error.kind(),
39+
format!("Could not {operation} {path:?}: {error}"),
40+
)
41+
}
42+
3643
impl WorkspaceScope {
3744
pub fn read(file: &Path, cwd: &Path) -> io::Result<Self> {
38-
if !file.symlink_metadata()?.is_file() {
39-
return Err(invalid("Workspace access requires a regular policy file."));
45+
if !file
46+
.symlink_metadata()
47+
.map_err(|e| path_error("inspect workspace policy", file, e))?
48+
.is_file()
49+
{
50+
return Err(invalid(&format!(
51+
"Workspace access requires a regular policy file: {file:?}."
52+
)));
4053
}
4154
let mut bytes = Vec::new();
42-
fs::File::open(file)?
55+
fs::File::open(file)
56+
.map_err(|e| path_error("open workspace policy", file, e))?
4357
.take(MAX_POLICY_BYTES + 1)
44-
.read_to_end(&mut bytes)?;
58+
.read_to_end(&mut bytes)
59+
.map_err(|e| path_error("read workspace policy", file, e))?;
4560
if bytes.len() as u64 > MAX_POLICY_BYTES {
46-
return Err(invalid("Workspace access policy exceeds its size limit."));
61+
return Err(invalid(&format!(
62+
"Workspace access policy {file:?} exceeds its size limit."
63+
)));
4764
}
48-
let policy: Self = serde_json::from_slice(&bytes).map_err(io::Error::other)?;
65+
let policy: Self = serde_json::from_slice(&bytes).map_err(|e| {
66+
io::Error::other(format!("Could not parse workspace policy {file:?}: {e}"))
67+
})?;
4968
policy.validate(cwd, file)?;
5069
Ok(policy)
5170
}
@@ -62,29 +81,55 @@ impl WorkspaceScope {
6281
|| self.writable_roots.is_empty()
6382
|| self.writable_roots.len() > 128
6483
|| self.read_only_roots.len() > 128
65-
|| self.primary_root != cwd.canonicalize()?
6684
{
67-
return Err(invalid("Invalid workspace access scope for this run."));
85+
return Err(invalid(&format!(
86+
"Invalid workspace access scope in policy {file:?} for this run."
87+
)));
6888
}
69-
let policy_path = file.canonicalize()?;
89+
let working_folder = cwd
90+
.canonicalize()
91+
.map_err(|e| path_error("resolve working folder", cwd, e))?;
92+
if self.primary_root != working_folder {
93+
return Err(invalid(&format!(
94+
"Workspace policy {file:?} names primary root {:?}, which does not match working folder {cwd:?}.",
95+
self.primary_root
96+
)));
97+
}
98+
let policy_path = file
99+
.canonicalize()
100+
.map_err(|e| path_error("resolve workspace policy", file, e))?;
70101
let home = dirs::home_dir().and_then(|path| path.canonicalize().ok());
71102
for roots in [&self.writable_roots, &self.read_only_roots] {
72103
if roots.windows(2).any(|pair| pair[0] >= pair[1]) {
73-
return Err(invalid("Workspace access roots must be sorted and unique."));
104+
return Err(invalid(&format!(
105+
"Workspace access roots in {file:?} must be sorted and unique."
106+
)));
74107
}
75108
for root in roots {
76-
if !root.is_absolute()
77-
|| root.parent().is_none()
78-
|| !root.is_dir()
79-
|| root.canonicalize()? != *root
109+
const ROOT_REQUIREMENT: &str =
110+
"Workspace access requires existing canonical dedicated folders.";
111+
let invalid_root =
112+
|| invalid(&format!("{ROOT_REQUIREMENT} Invalid folder: {root:?}."));
113+
if !root.is_absolute() || root.parent().is_none() {
114+
return Err(invalid_root());
115+
}
116+
// Preserve InvalidInput for metadata failures previously rejected by is_dir().
117+
let metadata = root.metadata().map_err(|e| {
118+
invalid(&format!(
119+
"{ROOT_REQUIREMENT} Could not inspect workspace folder {root:?}: {e}"
120+
))
121+
})?;
122+
if !metadata.is_dir()
123+
|| root
124+
.canonicalize()
125+
.map_err(|e| path_error("resolve workspace folder", root, e))?
126+
!= *root
80127
|| home.as_ref() == Some(root)
81128
|| root
82129
.to_str()
83130
.is_none_or(|path| path.chars().any(char::is_control))
84131
{
85-
return Err(invalid(
86-
"Workspace access requires existing canonical dedicated folders.",
87-
));
132+
return Err(invalid_root());
88133
}
89134
}
90135
}
@@ -102,9 +147,7 @@ impl WorkspaceScope {
102147
.any(|write| read.starts_with(write))
103148
})
104149
{
105-
return Err(invalid(
106-
"Workspace access overlaps a protected or read-only folder.",
107-
));
150+
return Err(invalid(&format!("Workspace access overlaps a protected or read-only folder. Check the roots in {file:?}.")));
108151
}
109152
Ok(())
110153
}
@@ -181,7 +224,9 @@ impl WorkspaceScope {
181224
pub async fn verify(self, policy_file: &Path) -> io::Result<VerifiedScope> {
182225
self.validate(&self.primary_root, policy_file)?;
183226
let mut args = vec![KERNEL_PROBE.into(), self.writable_roots.len().to_string()];
184-
let outside = policy_file.canonicalize()?;
227+
let outside = policy_file
228+
.canonicalize()
229+
.map_err(|e| path_error("resolve workspace policy", policy_file, e))?;
185230
for path in self
186231
.writable_roots
187232
.iter()
@@ -190,14 +235,26 @@ impl WorkspaceScope {
190235
{
191236
args.push(
192237
path.to_str()
193-
.ok_or_else(|| invalid("Invalid workspace folder path."))?
238+
.ok_or_else(|| {
239+
invalid(&format!(
240+
"Workspace verification requires a UTF-8 folder path: {path:?}."
241+
))
242+
})?
194243
.into(),
195244
);
196245
}
197-
let (program, argv) = self.command_parts(&std::env::current_exe()?, &args)?;
246+
let executable = std::env::current_exe().map_err(|e| {
247+
io::Error::new(
248+
e.kind(),
249+
format!("Could not locate the running executable for workspace verification: {e}"),
250+
)
251+
})?;
252+
let (program, argv) = self
253+
.command_parts(&executable, &args)
254+
.map_err(|e| path_error("prepare workspace verification for policy", policy_file, e))?;
198255
let status = tokio::time::timeout(
199256
Duration::from_secs(5),
200-
tokio::process::Command::new(program)
257+
tokio::process::Command::new(&program)
201258
.args(argv)
202259
.current_dir(&self.primary_root)
203260
.stdin(Stdio::null())
@@ -210,11 +267,12 @@ impl WorkspaceScope {
210267
.map_err(|_| {
211268
io::Error::new(
212269
io::ErrorKind::TimedOut,
213-
"Workspace sandbox verification timed out.",
270+
format!("Workspace sandbox verification timed out for policy {policy_file:?}."),
214271
)
215-
})??;
272+
})?
273+
.map_err(|e| path_error("run workspace verification command", &program, e))?;
216274
if !status.success() {
217-
return Err(io::Error::other("The workspace sandbox did not allow exactly the saved folders. Check folder access and update Coven Code before retrying."));
275+
return Err(io::Error::other(format!("The workspace sandbox did not allow exactly the saved folders. Verification of policy {policy_file:?} returned {status}. Check folder access and update Coven Code before retrying.")));
218276
}
219277
Ok(VerifiedScope(self))
220278
}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
use claurst_tools::workspace_scope::WorkspaceScope;
2+
use std::{fs, io, path::Path};
3+
4+
fn assert_diagnostic(
5+
error: io::Error,
6+
kind: io::ErrorKind,
7+
operation: &str,
8+
path: &Path,
9+
cause: &str,
10+
) {
11+
assert_eq!(error.kind(), kind);
12+
let message = error.to_string();
13+
for part in [operation, &format!("{path:?}"), cause] {
14+
assert!(message.contains(part), "missing {part:?} in {message:?}");
15+
}
16+
}
17+
18+
#[test]
19+
fn policy_input_failures_identify_the_operation_and_keep_the_cause() {
20+
let temp = tempfile::tempdir().unwrap();
21+
let work = temp.path().canonicalize().unwrap();
22+
let file = work.join("policy.json");
23+
let missing = file.symlink_metadata().unwrap_err();
24+
assert_diagnostic(
25+
WorkspaceScope::read(&file, &work).unwrap_err(),
26+
missing.kind(),
27+
"inspect workspace policy",
28+
&file,
29+
&missing.to_string(),
30+
);
31+
32+
fs::write(&file, "{").unwrap();
33+
assert_diagnostic(
34+
WorkspaceScope::read(&file, &work).unwrap_err(),
35+
io::ErrorKind::Other,
36+
"parse workspace policy",
37+
&file,
38+
"line 1 column 1",
39+
);
40+
41+
let cwd = work.join("missing-work");
42+
fs::write(
43+
&file,
44+
serde_json::json!({
45+
"version":1, "runId":"admission", "access":"workspace-write",
46+
"primaryRoot":cwd, "writableRoots":[cwd], "readOnlyRoots":[]
47+
})
48+
.to_string(),
49+
)
50+
.unwrap();
51+
let missing = cwd.canonicalize().unwrap_err();
52+
assert_diagnostic(
53+
WorkspaceScope::read(&file, &cwd).unwrap_err(),
54+
missing.kind(),
55+
"resolve working folder",
56+
&cwd,
57+
&missing.to_string(),
58+
);
59+
60+
let project = work.join("missing-project");
61+
fs::write(
62+
&file,
63+
serde_json::json!({
64+
"version": 1, "runId": "admission", "access": "workspace-write",
65+
"primaryRoot": work, "writableRoots": [work, project], "readOnlyRoots": []
66+
})
67+
.to_string(),
68+
)
69+
.unwrap();
70+
assert_diagnostic(
71+
WorkspaceScope::read(&file, &work).unwrap_err(),
72+
io::ErrorKind::InvalidInput,
73+
"inspect workspace folder",
74+
&project,
75+
&project.metadata().unwrap_err().to_string(),
76+
);
77+
}
78+
79+
#[cfg(unix)]
80+
#[test]
81+
fn unreadable_policy_names_the_file_and_keeps_permission_denied() {
82+
use std::os::unix::fs::PermissionsExt;
83+
if nix::unistd::geteuid().is_root() {
84+
return; // Root can read mode-000 files.
85+
}
86+
let temp = tempfile::tempdir().unwrap();
87+
let file = temp.path().join("unreadable-policy");
88+
fs::write(&file, "{}").unwrap();
89+
fs::set_permissions(&file, fs::Permissions::from_mode(0o000)).unwrap();
90+
let denied = fs::File::open(&file).unwrap_err();
91+
assert_diagnostic(
92+
WorkspaceScope::read(&file, temp.path()).unwrap_err(),
93+
io::ErrorKind::PermissionDenied,
94+
"open workspace policy",
95+
&file,
96+
&denied.to_string(),
97+
);
98+
}

0 commit comments

Comments
 (0)