Terminal file viewer/editor + per-window app-command lockdown (#60)
Build App / compute-version (push) Successful in 7s
Secret Scan / scan (push) Successful in 8s
Build App / build-macos (push) Successful in 2m53s
Build App / build-linux (push) Successful in 5m12s
Build App / build-windows (push) Successful in 5m15s
Build App / create-tag (push) Successful in 3s
Build App / sync-to-github (push) Successful in 1m5s
Build App / compute-version (push) Successful in 7s
Secret Scan / scan (push) Successful in 8s
Build App / build-macos (push) Successful in 2m53s
Build App / build-linux (push) Successful in 5m12s
Build App / build-windows (push) Successful in 5m15s
Build App / create-tag (push) Successful in 3s
Build App / sync-to-github (push) Successful in 1m5s
Clicking a file path in Claude's terminal output now opens the file in its own window with a CodeMirror 6 editor. The editor highlights the target line, live-reloads while the file changes, and saves explicitly with hash-based conflict detection. The viewer commands are gated by window label. Every app command is now ACL-gated per window through a Tauri AppManifest. build.rs checks the handler list against the capability files and fails the build on any mismatch. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit was merged in pull request #60.
This commit is contained in:
@@ -0,0 +1,581 @@
|
||||
//! The command census shared by `build.rs` and the `cargo test` suite.
|
||||
//!
|
||||
//! `build.rs` pulls this file in with `#[path = "src/command_census.rs"]` and `lib.rs` with
|
||||
//! `#[cfg(test)] mod command_census;`, so the parser that decides what the Tauri `AppManifest`
|
||||
//! declares is the parser the tests exercise, and the rules that decide whether the build
|
||||
//! passes have unit tests. Nothing here may reference the crate: only `std` and `serde_json`
|
||||
//! (a dependency of both the crate and the build script).
|
||||
//!
|
||||
//! Spec: `docs/superpowers/specs/2026-09-22-app-manifest-lockdown-design.md` §3.2.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// The command names inside `generate_handler![ … ])` in `lib.rs`, in registration order,
|
||||
/// duplicates kept (the caller decides whether that is an error). `None` if the block is
|
||||
/// missing or unterminated.
|
||||
///
|
||||
/// Comma-split, not line-split: `// Docker` style comments are stripped from every line first
|
||||
/// (a whole-line comment strips to nothing; a trailing one leaves the code before it), and the
|
||||
/// *cleaned* text is then split on `,` so each grant is its own item regardless of how many
|
||||
/// share a line. A line-split version of this parser shipped first and used
|
||||
/// `rsplit("::").next()` once *per line*: two commands on one line (`a::x, b::y,`) collapsed to
|
||||
/// a single item, silently dropping `a::x` — a denied command at runtime with nothing flagging
|
||||
/// it. Comma-splitting fixes that because it no longer assumes one item per line.
|
||||
pub fn registered_commands(lib_rs: &str) -> Option<Vec<String>> {
|
||||
let (_, rest) = lib_rs.split_once("generate_handler![")?;
|
||||
let (inside, _) = rest.split_once("])")?;
|
||||
let cleaned: String = inside
|
||||
.lines()
|
||||
// Strip a trailing `//` comment (and a whole-line one, which strips to "").
|
||||
.map(|l| l.split("//").next().unwrap_or(""))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
Some(
|
||||
cleaned
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.filter_map(|s| {
|
||||
// `a::b::name` → `name`; a bare `name` (no `::`) is its own last segment.
|
||||
s.rsplit("::").next().map(|n| n.trim().to_string())
|
||||
})
|
||||
.filter(|n| !n.is_empty())
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// `viewer_read_file` → `allow-viewer-read-file`. tauri-utils 2.9.0 (`acl/build.rs:290`)
|
||||
/// replaces only `_`; permission identifiers may not contain `_`, but the command name inside
|
||||
/// the generated permission stays snake_case.
|
||||
pub fn allow_permission(command: &str) -> String {
|
||||
format!("allow-{}", command.replace('_', "-"))
|
||||
}
|
||||
|
||||
/// The `windows` list of the one capability file that may grant `command`. A command that
|
||||
/// must be callable from both windows is a design change: make it here, visibly, rather than
|
||||
/// by widening a capability file.
|
||||
pub fn expected_windows(command: &str) -> &'static [&'static str] {
|
||||
if command.starts_with("viewer_") {
|
||||
&["file-viewer-*"]
|
||||
} else {
|
||||
&["main"]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CapabilityFile {
|
||||
pub name: String,
|
||||
pub windows: Vec<String>,
|
||||
pub bare: Vec<String>,
|
||||
}
|
||||
|
||||
/// One `capabilities/*.json`, reduced to what the census checks. Plugin and core grants
|
||||
/// (anything with a `:`) are not this module's business; the exact-set tests in `lib.rs` and
|
||||
/// `file_viewer/mod.rs` pin those.
|
||||
pub fn capability_file(name: &str, json: &str) -> Result<CapabilityFile, String> {
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(json).map_err(|e| format!("{name}: not valid JSON: {e}"))?;
|
||||
// `webviews` would extend the grants to webviews by label (the browser-view pop-out is
|
||||
// meant to be in no capability), and `remote` would extend them to a remote origin. The
|
||||
// census reasons about `windows` only, so either key is refused rather than half-checked.
|
||||
for key in ["webviews", "remote"] {
|
||||
if value.get(key).is_some() {
|
||||
return Err(format!(
|
||||
"{name}: `{key}` is not allowed; capabilities here are scoped by `windows` only"
|
||||
));
|
||||
}
|
||||
}
|
||||
let windows = value["windows"]
|
||||
.as_array()
|
||||
.ok_or_else(|| format!("{name}: `windows` must be an array"))?
|
||||
.iter()
|
||||
.map(|w| {
|
||||
w.as_str()
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| format!("{name}: `windows` entries must be strings"))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut bare = Vec::new();
|
||||
for grant in value["permissions"]
|
||||
.as_array()
|
||||
.ok_or_else(|| format!("{name}: `permissions` must be an array"))?
|
||||
{
|
||||
let id = match grant {
|
||||
serde_json::Value::String(s) => s.as_str(),
|
||||
serde_json::Value::Object(o) => o
|
||||
.get("identifier")
|
||||
.and_then(|i| i.as_str())
|
||||
.ok_or_else(|| format!("{name}: a scoped grant needs a string `identifier`"))?,
|
||||
_ => return Err(format!("{name}: a grant is a string or an object")),
|
||||
};
|
||||
if !id.contains(':') {
|
||||
bare.push(id.to_string());
|
||||
}
|
||||
}
|
||||
Ok(CapabilityFile { name: name.to_string(), windows, bare })
|
||||
}
|
||||
|
||||
/// Why an entry directly under `capabilities/` cannot be a capability the census reads, or
|
||||
/// `None` if it is one (a top-level `*.json` file). tauri-build loads `capabilities/**/*` with
|
||||
/// the extensions `json`, `toml` and (with a feature) `json5`, subdirectories included; the
|
||||
/// census reads only top-level JSON, so anything else tauri might load is refused rather than
|
||||
/// left for tauri to grant from unchecked. OS and editor junk, which tauri never loads, is the
|
||||
/// caller's to skip first (see [`is_os_junk`]).
|
||||
pub fn stray_capability_entry(name: &str, is_file: bool) -> Option<String> {
|
||||
if !is_file {
|
||||
return Some(format!(
|
||||
"capabilities/{name} is not a regular file; tauri loads capabilities from \
|
||||
subdirectories too, so every capability must be a top-level capabilities/*.json"
|
||||
));
|
||||
}
|
||||
if name.ends_with(".json") {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"capabilities/{name} is not a .json file; tauri may load it (it reads .toml and .json5 \
|
||||
too) but the census cannot check it, so every capability must be a top-level \
|
||||
capabilities/*.json"
|
||||
))
|
||||
}
|
||||
|
||||
/// Files the OS or an editor drops next to real ones (`.DS_Store`, `Thumbs.db`, `desktop.ini`,
|
||||
/// Vim swap files, `name~` backups). tauri-build loads only `json`/`toml`/`json5` from
|
||||
/// `capabilities/` and `permissions/`, so a junk name with one of those extensions (an Emacs
|
||||
/// `.#default.json` lock, a macOS `._default.json`) is *not* junk: tauri would try to load it,
|
||||
/// and the caller must refuse it.
|
||||
pub fn is_os_junk(name: &str) -> bool {
|
||||
let loadable = [".json", ".json5", ".toml"].iter().any(|e| name.ends_with(e));
|
||||
!loadable
|
||||
&& (matches!(name, ".DS_Store" | "Thumbs.db" | "desktop.ini")
|
||||
|| name.ends_with(".swp")
|
||||
|| name.ends_with(".swo")
|
||||
|| name.ends_with('~'))
|
||||
}
|
||||
|
||||
/// Which files next to `Cargo.toml` tauri reads as its config: `tauri.conf.json[5]`,
|
||||
/// `Tauri.toml` and the per-platform `tauri.<platform>.conf.json[5]` / `Tauri.<platform>.toml`
|
||||
/// (tauri-utils `config/parse.rs`). `Some(true)` = JSON the census can read, `Some(false)` = a
|
||||
/// format it cannot (JSON5/TOML), `None` = not a tauri config file.
|
||||
pub fn tauri_config_file(name: &str) -> Option<bool> {
|
||||
if name.starts_with("tauri.") && name.ends_with(".conf.json") {
|
||||
Some(true)
|
||||
} else if (name.starts_with("tauri.") && name.ends_with(".conf.json5"))
|
||||
|| (name.starts_with("Tauri.") && name.ends_with(".toml"))
|
||||
{
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A problem with a tauri config (a `tauri*.conf.json` file, or the `TAURI_CONFIG` JSON that
|
||||
/// tauri-build merges over it), or `None`. `app.security.capabilities` is refused whenever it
|
||||
/// is non-empty: an inline object is a capability the census never sees, and a list of
|
||||
/// identifiers switches every *other* capability file off, which the census also assumes is
|
||||
/// not happening.
|
||||
pub fn tauri_config_problem(name: &str, json: &str) -> Option<String> {
|
||||
let value: serde_json::Value = match serde_json::from_str(json) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return Some(format!("{name}: not valid JSON: {e}")),
|
||||
};
|
||||
match value.pointer("/app/security/capabilities") {
|
||||
None | Some(serde_json::Value::Null) => None,
|
||||
Some(serde_json::Value::Array(a)) if a.is_empty() => None,
|
||||
Some(_) => Some(format!(
|
||||
"{name}: app.security.capabilities is not allowed; every capability lives in a \
|
||||
top-level capabilities/*.json file, where the census checks it"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything that must hold between the handler list and the capability files. Returns every
|
||||
/// violation rather than the first, so a batch of forgotten grants is one build failure; an
|
||||
/// empty vector is a pass.
|
||||
pub fn check(commands: &[String], files: &[CapabilityFile]) -> Vec<String> {
|
||||
let mut problems = Vec::new();
|
||||
if commands.is_empty() {
|
||||
problems.push(
|
||||
"no commands were parsed out of generate_handler! — an empty AppManifest would \
|
||||
silently leave every app command ungated"
|
||||
.to_string(),
|
||||
);
|
||||
return problems;
|
||||
}
|
||||
|
||||
let mut seen: BTreeSet<&str> = BTreeSet::new();
|
||||
for c in commands {
|
||||
if !c.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') {
|
||||
problems.push(format!("{c:?} is not a command name ([a-z0-9_]+)"));
|
||||
}
|
||||
if !seen.insert(c.as_str()) {
|
||||
problems.push(format!("{c} is registered more than once"));
|
||||
}
|
||||
}
|
||||
|
||||
let known: BTreeMap<String, &str> =
|
||||
seen.iter().map(|c| (allow_permission(c), *c)).collect();
|
||||
for f in files {
|
||||
let windows: Vec<&str> = f.windows.iter().map(String::as_str).collect();
|
||||
for id in &f.bare {
|
||||
match known.get(id) {
|
||||
Some(command) => {
|
||||
let want = expected_windows(command);
|
||||
if windows.as_slice() != want {
|
||||
problems.push(format!(
|
||||
"{}: {id} must be granted in the capability file whose windows are \
|
||||
{want:?}, not {windows:?}",
|
||||
f.name
|
||||
));
|
||||
}
|
||||
}
|
||||
None if id.starts_with("deny-") => problems.push(format!(
|
||||
"{}: {id}: deny-* is global in tauri 2.11 — it would deny the command for \
|
||||
every window, not just this one; use allow-lists only",
|
||||
f.name
|
||||
)),
|
||||
None if id.starts_with("allow-") => problems.push(format!(
|
||||
"{}: {id} names no registered command (the identifier is allow-<command> \
|
||||
with every `_` replaced by `-`)",
|
||||
f.name
|
||||
)),
|
||||
None => problems.push(format!(
|
||||
"{}: {id}: only allow-<command> app grants are permitted as bare identifiers",
|
||||
f.name
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for c in &seen {
|
||||
let id = allow_permission(c);
|
||||
let holders: Vec<&str> = files
|
||||
.iter()
|
||||
.filter(|f| f.bare.iter().any(|b| b == &id))
|
||||
.map(|f| f.name.as_str())
|
||||
.collect();
|
||||
match holders.len() {
|
||||
0 => problems.push(format!(
|
||||
"{c} is registered but no capability file grants {id}; add it to the file \
|
||||
whose windows are {:?}",
|
||||
expected_windows(c)
|
||||
)),
|
||||
1 => {}
|
||||
_ => problems.push(format!(
|
||||
"{id} is granted in more than one capability file: {holders:?}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
problems
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn cmds(names: &[&str]) -> Vec<String> {
|
||||
names.iter().map(|n| n.to_string()).collect()
|
||||
}
|
||||
|
||||
fn file(name: &str, windows: &[&str], bare: &[&str]) -> CapabilityFile {
|
||||
CapabilityFile {
|
||||
name: name.to_string(),
|
||||
windows: windows.iter().map(|w| w.to_string()).collect(),
|
||||
bare: bare.iter().map(|b| b.to_string()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The two files as they must look after the lockdown, for a three-command app.
|
||||
fn good_files() -> Vec<CapabilityFile> {
|
||||
vec![
|
||||
file("default.json", &["main"], &["allow-check-docker", "allow-open-file-viewer"]),
|
||||
file("file-viewer.json", &["file-viewer-*"], &["allow-viewer-read-file"]),
|
||||
]
|
||||
}
|
||||
|
||||
const THREE: &[&str] = &["check_docker", "open_file_viewer", "viewer_read_file"];
|
||||
|
||||
#[test]
|
||||
fn the_parser_reads_the_handler_list_in_order_and_ignores_comments() {
|
||||
let lib_rs = r#"
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
// Docker
|
||||
commands::docker_commands::check_docker,
|
||||
commands::docker_commands::build_image, // trailing comment is not a command
|
||||
url_open::open_url_external,
|
||||
|
||||
// Viewer
|
||||
commands::file_viewer_commands::viewer_read_file
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
"#;
|
||||
assert_eq!(
|
||||
registered_commands(lib_rs).unwrap(),
|
||||
cmds(&["check_docker", "build_image", "open_url_external", "viewer_read_file"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parser_keeps_duplicates_so_the_caller_can_report_them() {
|
||||
let lib_rs = "generate_handler![\n a::x,\n b::x,\n])";
|
||||
assert_eq!(registered_commands(lib_rs).unwrap(), cmds(&["x", "x"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parser_returns_none_without_a_handler_block() {
|
||||
assert_eq!(registered_commands("fn main() {}"), None);
|
||||
assert_eq!(registered_commands("generate_handler![ a::b, "), None, "unterminated");
|
||||
}
|
||||
|
||||
/// The bug this regression-tests: a line-split parser applies `rsplit("::").next()` once
|
||||
/// per *line*, so two commands sharing a line collapse into one item and the first is
|
||||
/// silently dropped. Comma-splitting must keep both regardless of layout.
|
||||
#[test]
|
||||
fn two_commands_on_one_line_are_both_kept() {
|
||||
let lib_rs = "generate_handler![\n a::x, b::y,\n])";
|
||||
assert_eq!(registered_commands(lib_rs).unwrap(), cmds(&["x", "y"]));
|
||||
}
|
||||
|
||||
/// Mirrors the real `lib.rs` handler list's shape: `// Section` comments between groups,
|
||||
/// and command paths one (`open_url_external`), two (`url_open::open_url_external`) and
|
||||
/// three (`commands::docker_commands::check_docker`) segments deep, all ending in a comma
|
||||
/// except the last entry before `])`.
|
||||
#[test]
|
||||
fn a_fixture_shaped_like_the_real_handler_list_parses_every_command() {
|
||||
let lib_rs = r#"
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
// Docker
|
||||
commands::docker_commands::check_docker,
|
||||
commands::docker_commands::build_image,
|
||||
// Opening a link in the host browser
|
||||
url_open::open_url_external,
|
||||
// Bare, module-less command
|
||||
open_help,
|
||||
// Terminal file viewer
|
||||
commands::file_viewer_commands::viewer_read_file
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
"#;
|
||||
assert_eq!(
|
||||
registered_commands(lib_rs).unwrap(),
|
||||
cmds(&[
|
||||
"check_docker",
|
||||
"build_image",
|
||||
"open_url_external",
|
||||
"open_help",
|
||||
"viewer_read_file",
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permission_identifiers_replace_only_underscores() {
|
||||
assert_eq!(allow_permission("check_docker"), "allow-check-docker");
|
||||
assert_eq!(allow_permission("viewer_read_file"), "allow-viewer-read-file");
|
||||
assert_eq!(allow_permission("aws_sso_refresh"), "allow-aws-sso-refresh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewer_commands_belong_to_the_viewer_windows_and_nothing_else_does() {
|
||||
assert_eq!(expected_windows("viewer_read_file"), ["file-viewer-*"]);
|
||||
assert_eq!(expected_windows("open_file_viewer"), ["main"]);
|
||||
assert_eq!(expected_windows("check_docker"), ["main"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capability_file_yields_its_windows_and_bare_grants_only() {
|
||||
let json = r#"{
|
||||
"identifier": "default",
|
||||
"description": "x",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:event:allow-listen",
|
||||
{ "identifier": "fs:allow-read", "allow": [{ "path": "$APPDATA/*" }] },
|
||||
"allow-check-docker",
|
||||
{ "identifier": "allow-list-projects" }
|
||||
]
|
||||
}"#;
|
||||
let parsed = capability_file("default.json", json).unwrap();
|
||||
assert_eq!(parsed.name, "default.json");
|
||||
assert_eq!(parsed.windows, vec!["main"]);
|
||||
assert_eq!(parsed.bare, vec!["allow-check-docker", "allow-list-projects"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capability_file_without_windows_or_permissions_is_an_error() {
|
||||
assert!(capability_file("x.json", r#"{"permissions": []}"#).unwrap_err().contains("windows"));
|
||||
assert!(capability_file("x.json", r#"{"windows": ["main"]}"#).unwrap_err().contains("permissions"));
|
||||
assert!(capability_file("x.json", "not json").unwrap_err().contains("x.json"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webviews_and_remote_keys_are_refused() {
|
||||
let with = |extra: &str| {
|
||||
format!(r#"{{"windows": ["main"], {extra}, "permissions": ["allow-check-docker"]}}"#)
|
||||
};
|
||||
let err = capability_file("d.json", &with(r#""webviews": ["browser-view-*"]"#)).unwrap_err();
|
||||
assert!(err.contains("d.json") && err.contains("`webviews`"), "{err}");
|
||||
let err = capability_file("d.json", &with(r#""remote": {"urls": ["https://*"]}"#)).unwrap_err();
|
||||
assert!(err.contains("`remote`"), "{err}");
|
||||
// Present-but-empty is still refused: the key itself is the widening surface.
|
||||
assert!(capability_file("d.json", &with(r#""webviews": []"#)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_top_level_json_files_are_capabilities() {
|
||||
assert_eq!(stray_capability_entry("default.json", true), None);
|
||||
for name in ["extra.toml", "extra.json5", "notes.txt", ".DS_Store"] {
|
||||
let err = stray_capability_entry(name, true).expect(name);
|
||||
assert!(err.contains(name) && err.contains("not a .json file"), "{err}");
|
||||
}
|
||||
let err = stray_capability_entry("sub", false).unwrap();
|
||||
assert!(err.contains("capabilities/sub") && err.contains("not a regular file"), "{err}");
|
||||
// A directory named like a capability is still a directory.
|
||||
assert!(stray_capability_entry("x.json", false).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_junk_is_recognised_but_never_something_tauri_would_load() {
|
||||
for junk in [".DS_Store", "Thumbs.db", "desktop.ini", ".default.json.swp", ".x.swo", "default.json~"] {
|
||||
assert!(is_os_junk(junk), "{junk}");
|
||||
}
|
||||
for real in ["default.json", "x.toml", "x.json5", ".#default.json", "._default.json", "notes.txt", "extra"] {
|
||||
assert!(!is_os_junk(real), "{real}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tauri_config_files_are_found_by_name_and_format() {
|
||||
assert_eq!(tauri_config_file("tauri.conf.json"), Some(true));
|
||||
assert_eq!(tauri_config_file("tauri.linux.conf.json"), Some(true));
|
||||
assert_eq!(tauri_config_file("tauri.conf.json5"), Some(false));
|
||||
assert_eq!(tauri_config_file("tauri.windows.conf.json5"), Some(false));
|
||||
assert_eq!(tauri_config_file("Tauri.toml"), Some(false));
|
||||
assert_eq!(tauri_config_file("Tauri.macos.toml"), Some(false));
|
||||
assert_eq!(tauri_config_file("Cargo.toml"), None);
|
||||
assert_eq!(tauri_config_file("build.rs"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_capabilities_in_the_tauri_config_are_refused() {
|
||||
let ok = r#"{"app": {"security": {"csp": "default-src 'self'"}}}"#;
|
||||
assert_eq!(tauri_config_problem("tauri.conf.json", ok), None);
|
||||
assert_eq!(tauri_config_problem("t", r#"{"app": {"security": {"capabilities": []}}}"#), None);
|
||||
assert_eq!(tauri_config_problem("t", r#"{"build": {"beforeBuildCommand": ""}}"#), None);
|
||||
let inline = r#"{"app": {"security": {"capabilities": [
|
||||
{"identifier": "x", "windows": ["file-viewer-*"], "permissions": ["allow-read-container-file"]}
|
||||
]}}}"#;
|
||||
let err = tauri_config_problem("tauri.conf.json", inline).unwrap();
|
||||
assert!(err.contains("tauri.conf.json") && err.contains("app.security.capabilities"), "{err}");
|
||||
let by_name = r#"{"app": {"security": {"capabilities": ["default"]}}}"#;
|
||||
assert!(tauri_config_problem("TAURI_CONFIG", by_name).unwrap().contains("TAURI_CONFIG"));
|
||||
assert!(tauri_config_problem("t", "{").unwrap().contains("not valid JSON"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_correct_census_has_no_problems() {
|
||||
assert_eq!(check(&cmds(THREE), &good_files()), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_command_list_is_refused_because_it_would_disable_the_acl() {
|
||||
let problems = check(&[], &good_files());
|
||||
assert_eq!(problems.len(), 1);
|
||||
assert!(problems[0].contains("no commands"), "{problems:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_without_a_grant_is_named_together_with_the_file_it_belongs_in() {
|
||||
let files = vec![
|
||||
file("default.json", &["main"], &["allow-check-docker"]),
|
||||
file("file-viewer.json", &["file-viewer-*"], &["allow-viewer-read-file"]),
|
||||
];
|
||||
let problems = check(&cmds(THREE), &files);
|
||||
assert_eq!(problems.len(), 1, "{problems:?}");
|
||||
assert!(problems[0].contains("open_file_viewer"));
|
||||
assert!(problems[0].contains("allow-open-file-viewer"));
|
||||
assert!(problems[0].contains("[\"main\"]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grant_in_two_files_is_reported_once_naming_both() {
|
||||
let files = vec![
|
||||
file("default.json", &["main"], &["allow-check-docker", "allow-open-file-viewer"]),
|
||||
file("extra.json", &["main"], &["allow-check-docker"]),
|
||||
file("file-viewer.json", &["file-viewer-*"], &["allow-viewer-read-file"]),
|
||||
];
|
||||
let problems = check(&cmds(THREE), &files);
|
||||
assert_eq!(problems.len(), 1, "{problems:?}");
|
||||
assert!(problems[0].contains("allow-check-docker"));
|
||||
assert!(problems[0].contains("default.json") && problems[0].contains("extra.json"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grant_that_names_no_command_is_a_typo() {
|
||||
let mut files = good_files();
|
||||
files[0].bare.push("allow-check-dokcer".to_string());
|
||||
let problems = check(&cmds(THREE), &files);
|
||||
assert_eq!(problems.len(), 1, "{problems:?}");
|
||||
assert!(problems[0].contains("default.json: allow-check-dokcer"));
|
||||
assert!(problems[0].contains("no registered command"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deny_grants_are_refused_with_the_reason() {
|
||||
let mut files = good_files();
|
||||
files[1].bare.push("deny-check-docker".to_string());
|
||||
let problems = check(&cmds(THREE), &files);
|
||||
assert_eq!(problems.len(), 1, "{problems:?}");
|
||||
assert!(problems[0].contains("file-viewer.json: deny-check-docker"));
|
||||
assert!(problems[0].contains("global"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_bare_identifiers_are_refused() {
|
||||
let mut files = good_files();
|
||||
files[0].bare.push("default".to_string());
|
||||
let problems = check(&cmds(THREE), &files);
|
||||
assert_eq!(problems.len(), 1, "{problems:?}");
|
||||
assert!(problems[0].contains("default.json: default"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grant_in_the_wrong_file_is_refused_even_though_it_is_granted_exactly_once() {
|
||||
let files = vec![
|
||||
file("default.json", &["main"], &["allow-check-docker", "allow-open-file-viewer", "allow-viewer-read-file"]),
|
||||
file("file-viewer.json", &["file-viewer-*"], &[]),
|
||||
];
|
||||
let problems = check(&cmds(THREE), &files);
|
||||
assert_eq!(problems.len(), 1, "{problems:?}");
|
||||
assert!(problems[0].contains("allow-viewer-read-file"));
|
||||
assert!(problems[0].contains("[\"file-viewer-*\"]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widened_windows_list_is_the_wrong_file_too() {
|
||||
let files = vec![
|
||||
file("default.json", &["main", "file-viewer-*"], &["allow-check-docker", "allow-open-file-viewer"]),
|
||||
file("file-viewer.json", &["file-viewer-*"], &["allow-viewer-read-file"]),
|
||||
];
|
||||
let problems = check(&cmds(THREE), &files);
|
||||
assert_eq!(problems.len(), 2, "{problems:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_names_and_duplicate_registrations_are_refused() {
|
||||
let commands = cmds(&["check_docker", "Check-Docker", "check_docker", "open_file_viewer", "viewer_read_file"]);
|
||||
let problems = check(&commands, &good_files());
|
||||
assert!(problems.iter().any(|p| p.contains("\"Check-Docker\"") && p.contains("[a-z0-9_]+")), "{problems:?}");
|
||||
assert!(problems.iter().any(|p| p.contains("check_docker is registered more than once")), "{problems:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_problem_is_reported_in_one_pass() {
|
||||
let files = vec![
|
||||
file("default.json", &["main"], &["allow-check-docker", "allow-nope", "deny-check-docker"]),
|
||||
file("file-viewer.json", &["file-viewer-*"], &[]),
|
||||
];
|
||||
let problems = check(&cmds(THREE), &files);
|
||||
// typo, deny, open_file_viewer missing, viewer_read_file missing
|
||||
assert_eq!(problems.len(), 4, "{problems:?}");
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ pub struct FileContents {
|
||||
/// Hard ceiling on a single viewer read, whatever the caller asks for. The tar
|
||||
/// path buffers the whole payload in host RAM, so a caller-supplied cap is not
|
||||
/// something to take on trust.
|
||||
const MAX_READ_BYTES: u64 = 8 * 1024 * 1024;
|
||||
pub(crate) const MAX_READ_BYTES: u64 = 8 * 1024 * 1024;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn list_container_files(
|
||||
@@ -352,7 +352,7 @@ const CONTAINER_WRITE_ROOTS: &[&str] = &["/workspace", "/home/claude", "/tmp"];
|
||||
///
|
||||
/// `what` names the parameter in the error, because these messages are shown to
|
||||
/// a user who is looking at a folder, not at argv.
|
||||
fn validate_container_path(what: &str, path: &str) -> Result<(), String> {
|
||||
pub(crate) fn validate_container_path(what: &str, path: &str) -> Result<(), String> {
|
||||
if path.is_empty() {
|
||||
return Err(format!("{} path cannot be empty", what));
|
||||
}
|
||||
@@ -394,7 +394,7 @@ fn validate_container_path(what: &str, path: &str) -> Result<(), String> {
|
||||
/// directly. What it buys is that the *panel* keeps its promise — the roots
|
||||
/// named in the refusal are the roots it writes to — and that a mis-aimed drop
|
||||
/// cannot quietly land outside them.
|
||||
fn validate_container_write_path(what: &str, path: &str) -> Result<(), String> {
|
||||
pub(crate) fn validate_container_write_path(what: &str, path: &str) -> Result<(), String> {
|
||||
validate_container_path(what, path)?;
|
||||
if CONTAINER_WRITE_ROOTS
|
||||
.iter()
|
||||
@@ -1178,12 +1178,12 @@ fn push_capped(buf: &mut String, frame: &[u8]) {
|
||||
}
|
||||
|
||||
/// One regular file's bytes, pulled out of a container.
|
||||
struct FetchedFile {
|
||||
bytes: Vec<u8>,
|
||||
pub(crate) struct FetchedFile {
|
||||
pub(crate) bytes: Vec<u8>,
|
||||
/// The size the tar header declared, i.e. the file's real size — which is
|
||||
/// not `bytes.len()` once `max_bytes` has cut the read short.
|
||||
size: u64,
|
||||
truncated: bool,
|
||||
pub(crate) size: u64,
|
||||
pub(crate) truncated: bool,
|
||||
}
|
||||
|
||||
/// Fetch a single regular file from a container as exact bytes.
|
||||
@@ -1202,7 +1202,7 @@ struct FetchedFile {
|
||||
/// file — or the whole *directory tree*, since the type check happens after the
|
||||
/// read — landed in host RAM twice. This function buffers, so every caller of
|
||||
/// it must name a ceiling.
|
||||
async fn fetch_container_file(
|
||||
pub(crate) async fn fetch_container_file(
|
||||
container_id: &str,
|
||||
container_path: &str,
|
||||
max_bytes: u64,
|
||||
@@ -1448,6 +1448,14 @@ pub async fn create_container_directory(
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
/// Every "container is not running" refusal starts with this, so a caller (the file
|
||||
/// viewer's poll, `app/src/viewer/ipcMessages.ts`) can tell it apart from any other failure.
|
||||
pub(crate) const NOT_RUNNING_PREFIX: &str = "Start the project before";
|
||||
|
||||
pub(crate) fn not_running_message(action: &str, why: &str) -> String {
|
||||
format!("{} {} — {}.", NOT_RUNNING_PREFIX, action, why)
|
||||
}
|
||||
|
||||
/// Refuse, in a sentence, before a Docker error has to speak for us.
|
||||
///
|
||||
/// Both file transfers and the backup run through `docker exec`, which needs a
|
||||
@@ -1456,7 +1464,7 @@ pub async fn create_container_directory(
|
||||
/// upload it surfaces even less usefully: `resolve_container_dir`'s `realpath`
|
||||
/// is the first thing to touch the container, so a stopped project fails inside
|
||||
/// path *validation* and reads like the path was the problem.
|
||||
async fn require_running(container_id: &str, action: &str) -> Result<(), String> {
|
||||
pub(crate) async fn require_running(container_id: &str, action: &str) -> Result<(), String> {
|
||||
let docker = get_docker()?;
|
||||
let running = docker
|
||||
.inspect_container(container_id, None)
|
||||
@@ -1468,10 +1476,7 @@ async fn require_running(container_id: &str, action: &str) -> Result<(), String>
|
||||
if running {
|
||||
return Ok(());
|
||||
}
|
||||
Err(format!(
|
||||
"Start the project before {} — it runs inside the running container.",
|
||||
action
|
||||
))
|
||||
Err(not_running_message(action, "it runs inside the running container"))
|
||||
}
|
||||
|
||||
/// Copy one regular file out of a container onto a host path the user chose in
|
||||
@@ -2011,7 +2016,7 @@ async fn upload_one(
|
||||
/// call site for why each of those three matters; the short version is that
|
||||
/// this text ends up inside a toast that renders above every modal, and its
|
||||
/// author is the container.
|
||||
fn clip_container_text(text: &str) -> String {
|
||||
pub(crate) fn clip_container_text(text: &str) -> String {
|
||||
const MAX: usize = 200;
|
||||
let flattened: String = text
|
||||
.trim()
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
//! IPC for the terminal file viewer. Every command here is gated on the calling
|
||||
//! window's label and reads its target from the registry — no path, no label, no
|
||||
//! project id crosses IPC from a viewer window. See spec §6.
|
||||
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use base64::Engine as _;
|
||||
use serde::Serialize;
|
||||
use tauri::{AppHandle, Emitter, Manager, State};
|
||||
|
||||
use crate::commands::file_commands::{
|
||||
fetch_container_file, not_running_message, require_running, validate_container_write_path, MAX_READ_BYTES,
|
||||
};
|
||||
use crate::file_viewer::is_viewer_label;
|
||||
use crate::file_viewer::poll::{poll_file, ViewerPoll};
|
||||
use crate::file_viewer::registry::{
|
||||
Choice, Location, Reservation, ViewerRegistry, ViewerTarget, ViewerTargetState,
|
||||
};
|
||||
use crate::file_viewer::resolve::{candidate_paths, probe_candidates};
|
||||
use crate::file_viewer::window::open_viewer_window;
|
||||
use crate::file_viewer::write::{sha256_hex, write_file, SavedFile, MAX_WRITE_BYTES};
|
||||
use crate::models::Project;
|
||||
use crate::AppState;
|
||||
|
||||
pub const GOTO_EVENT: &str = "file-viewer-goto";
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct ViewerState {
|
||||
pub project_id: String,
|
||||
pub project_name: String,
|
||||
pub raw_path: String,
|
||||
pub state: ViewerTargetState,
|
||||
pub initial: Location,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct ViewerFile {
|
||||
pub contents_base64: String,
|
||||
pub truncated: bool,
|
||||
pub size: u64,
|
||||
pub hash: String,
|
||||
pub editable: bool,
|
||||
pub readonly_reason: Option<String>,
|
||||
}
|
||||
|
||||
fn require_main(window_label: &str) -> Result<(), String> {
|
||||
if window_label == "main" {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Only the main window can open files.".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn require_viewer(window_label: &str) -> Result<String, String> {
|
||||
if is_viewer_label(window_label) {
|
||||
Ok(window_label.to_string())
|
||||
} else {
|
||||
Err("This command belongs to a file window.".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn viewer_state_of(_label: &str, target: ViewerTarget) -> ViewerState {
|
||||
ViewerState {
|
||||
project_id: target.project_id,
|
||||
project_name: target.project_name,
|
||||
raw_path: target.raw_path,
|
||||
state: target.state,
|
||||
initial: target.initial,
|
||||
}
|
||||
}
|
||||
|
||||
fn window_title(raw_path: &str, project_name: &str) -> String {
|
||||
let base = raw_path.trim_end_matches('/').rsplit('/').next().unwrap_or(raw_path);
|
||||
format!("{} — {}", base, project_name)
|
||||
}
|
||||
|
||||
/// Refuses a save payload before decoding it: base64 of at most
|
||||
/// [`MAX_WRITE_BYTES`] is at most `4 * ceil(MAX_WRITE_BYTES / 3)` characters.
|
||||
/// `write_file` enforces the cap on the decoded bytes too; this stops a
|
||||
/// compromised viewer from making the app allocate and decode an arbitrarily
|
||||
/// large string first.
|
||||
fn check_encoded_len(encoded_len: usize) -> Result<(), String> {
|
||||
if encoded_len > MAX_WRITE_BYTES.div_ceil(3) * 4 {
|
||||
return Err("Files over 1 MiB are read-only in the viewer.".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The caller's registry entry, or a sentence.
|
||||
fn own_target(
|
||||
window: &tauri::Window,
|
||||
registry: &ViewerRegistry,
|
||||
) -> Result<(String, ViewerTarget), String> {
|
||||
let label = require_viewer(window.label())?;
|
||||
let target = registry
|
||||
.get(&label)
|
||||
.ok_or_else(|| "This file window is no longer registered.".to_string())?;
|
||||
Ok((label, target))
|
||||
}
|
||||
|
||||
fn resolved_path(target: &ViewerTarget) -> Result<String, String> {
|
||||
match &target.state {
|
||||
ViewerTargetState::Resolved { container_path } => Ok(container_path.clone()),
|
||||
_ => Err("Choose a file first.".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one place a viewer command looks up its project (P14).
|
||||
fn project_of(state: &AppState, project_id: &str) -> Result<Project, String> {
|
||||
state
|
||||
.projects_store
|
||||
.get(project_id)
|
||||
.ok_or_else(|| "This project no longer exists.".to_string())
|
||||
}
|
||||
|
||||
/// `action` completes "Start the project before …", e.g. "saving this file".
|
||||
async fn running_container_of(project: &Project, action: &str) -> Result<String, String> {
|
||||
let container_id = project
|
||||
.container_id
|
||||
.clone()
|
||||
.ok_or_else(|| not_running_message(action, "files live in its container"))?;
|
||||
require_running(&container_id, action).await?;
|
||||
Ok(container_id)
|
||||
}
|
||||
|
||||
/// The container of the project a viewer window belongs to, if it is running.
|
||||
async fn running_container_for(
|
||||
state: &AppState,
|
||||
target: &ViewerTarget,
|
||||
action: &str,
|
||||
) -> Result<String, String> {
|
||||
running_container_of(&project_of(state, &target.project_id)?, action).await
|
||||
}
|
||||
|
||||
/// Raises an existing viewer window and moves it to `location`.
|
||||
fn focus_viewer(app: &AppHandle, label: &str, location: Location) {
|
||||
if let Some(existing) = app.get_webview_window(label) {
|
||||
let _ = existing.unminimize();
|
||||
let _ = existing.set_focus();
|
||||
let _ = app.emit_to(label, GOTO_EVENT, location);
|
||||
}
|
||||
}
|
||||
|
||||
// Nine parameters are fixed by the IPC contract (P10); four injected by Tauri.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[tauri::command]
|
||||
pub async fn open_file_viewer(
|
||||
project_id: String,
|
||||
path: String,
|
||||
line: Option<u32>,
|
||||
col: Option<u32>,
|
||||
end_line: Option<u32>,
|
||||
window: tauri::Window,
|
||||
app: AppHandle,
|
||||
registry: State<'_, ViewerRegistry>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
require_main(window.label())?;
|
||||
let project = project_of(&state, &project_id)?;
|
||||
let container_id = running_container_of(&project, "opening files").await?;
|
||||
|
||||
let mounts: Vec<String> = project.paths.iter().map(|p| p.mount_name.clone()).collect();
|
||||
let candidates = candidate_paths(&path, &mounts)?;
|
||||
let matches = probe_candidates(&container_id, &candidates).await?;
|
||||
let initial = Location { line, col, end_line };
|
||||
|
||||
let target_state = match matches.len() {
|
||||
0 => ViewerTargetState::NotFound { tried: candidates },
|
||||
1 => ViewerTargetState::Resolved { container_path: matches[0].clone() },
|
||||
_ => ViewerTargetState::Choose { candidates: matches },
|
||||
};
|
||||
|
||||
let title = window_title(&path, &project.name);
|
||||
let target = ViewerTarget {
|
||||
project_id,
|
||||
project_name: project.name.clone(),
|
||||
raw_path: path,
|
||||
state: target_state,
|
||||
initial: initial.clone(),
|
||||
};
|
||||
// Dedupe, stale pruning and the cap are one registry call, so a second click
|
||||
// while the first window is still being built finds it rather than reading
|
||||
// its not-yet-existing window as stale.
|
||||
let label = match registry.reserve(target, |l| app.get_webview_window(l).is_some())? {
|
||||
Reservation::Reserved(label) => label,
|
||||
// Still being built: it opens at its own location in a moment.
|
||||
Reservation::Existing { built: false, .. } => return Ok(()),
|
||||
Reservation::Existing { label, built: true } => {
|
||||
focus_viewer(&app, &label, initial);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
if let Err(e) = open_viewer_window(&app, &label, &title) {
|
||||
registry.remove(&label);
|
||||
return Err(e);
|
||||
}
|
||||
registry.mark_built(&label);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn viewer_get_state(
|
||||
window: tauri::Window,
|
||||
registry: State<'_, ViewerRegistry>,
|
||||
) -> Result<ViewerState, String> {
|
||||
let (label, target) = own_target(&window, ®istry)?;
|
||||
Ok(viewer_state_of(&label, target))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn viewer_choose_file(
|
||||
index: usize,
|
||||
window: tauri::Window,
|
||||
registry: State<'_, ViewerRegistry>,
|
||||
) -> Result<ViewerState, String> {
|
||||
let (label, target) = own_target(&window, ®istry)?;
|
||||
let chosen = match &target.state {
|
||||
ViewerTargetState::Choose { candidates } => candidates
|
||||
.get(index)
|
||||
.cloned()
|
||||
.ok_or_else(|| "That choice is no longer available.".to_string())?,
|
||||
_ => return Err("This window is not choosing a file.".into()),
|
||||
};
|
||||
let app = window.app_handle();
|
||||
match registry.choose(&label, chosen, |l| app.get_webview_window(l).is_some())? {
|
||||
Choice::Resolved(updated) => Ok(viewer_state_of(&label, updated)),
|
||||
// Another window already has this file. This window was only ever a
|
||||
// chooser, so hand over to that one and close this one, as a second
|
||||
// click on the same path would have. The error is what this window
|
||||
// shows if the destroy fails.
|
||||
Choice::AlreadyOpen { label: other, .. } => {
|
||||
focus_viewer(app, &other, target.initial);
|
||||
let _ = window.destroy();
|
||||
Err("This file is already open in another window.".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn viewer_read_file(
|
||||
max_bytes: u64,
|
||||
window: tauri::Window,
|
||||
registry: State<'_, ViewerRegistry>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<ViewerFile, String> {
|
||||
let (_label, target) = own_target(&window, ®istry)?;
|
||||
let path = resolved_path(&target)?;
|
||||
let container_id = running_container_for(&state, &target, "opening files").await?;
|
||||
let cap = max_bytes.clamp(1, MAX_READ_BYTES);
|
||||
let fetched = fetch_container_file(&container_id, &path, cap).await?;
|
||||
let (editable, readonly_reason) = match validate_container_write_path("File", &path) {
|
||||
Ok(()) => (true, None),
|
||||
Err(reason) => (false, Some(reason)),
|
||||
};
|
||||
Ok(ViewerFile {
|
||||
hash: sha256_hex(&fetched.bytes),
|
||||
contents_base64: BASE64.encode(&fetched.bytes),
|
||||
truncated: fetched.truncated,
|
||||
size: fetched.size,
|
||||
editable,
|
||||
readonly_reason,
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn viewer_poll_file(
|
||||
window: tauri::Window,
|
||||
registry: State<'_, ViewerRegistry>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<ViewerPoll, String> {
|
||||
let (_label, target) = own_target(&window, ®istry)?;
|
||||
let path = resolved_path(&target)?;
|
||||
let container_id = running_container_for(&state, &target, "checking this file for changes").await?;
|
||||
poll_file(&container_id, &path).await
|
||||
}
|
||||
|
||||
/// Errors from `write_file` pass through unchanged: the frontend matches the
|
||||
/// `write::CONFLICT_PREFIX`/`GONE_PREFIX` prefixes and `READ_ONLY_MESSAGE` (TS copies in
|
||||
/// `app/src/viewer/ipcMessages.ts`), and anything else (a full disk) is already a
|
||||
/// sentence it shows as is. Success is a `SavedFile`: the new base hash and the hash
|
||||
/// the disk held right after the swap.
|
||||
#[tauri::command]
|
||||
pub async fn viewer_write_file(
|
||||
contents_base64: String,
|
||||
base_hash: String,
|
||||
window: tauri::Window,
|
||||
registry: State<'_, ViewerRegistry>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<SavedFile, String> {
|
||||
let (_label, target) = own_target(&window, ®istry)?;
|
||||
let path = resolved_path(&target)?;
|
||||
validate_container_write_path("File", &path)?;
|
||||
check_encoded_len(contents_base64.len())?;
|
||||
let bytes = BASE64
|
||||
.decode(contents_base64.as_bytes())
|
||||
.map_err(|_| "The editor sent malformed content.".to_string())?;
|
||||
let container_id = running_container_for(&state, &target, "saving this file").await?;
|
||||
write_file(&container_id, &state.exec_manager, &path, &bytes, &base_hash).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn open_is_main_only_and_viewer_commands_are_viewer_only() {
|
||||
assert!(require_main("main").is_ok());
|
||||
assert!(require_main("file-viewer-1").is_err());
|
||||
assert!(require_main("browser-view-x").is_err());
|
||||
assert_eq!(require_viewer("file-viewer-7").unwrap(), "file-viewer-7");
|
||||
assert!(require_viewer("main").is_err());
|
||||
assert!(require_viewer("file-viewer-").is_err());
|
||||
}
|
||||
|
||||
/// Both "no container" refusals a viewer command can give start with the prefix
|
||||
/// the viewer reads as "Container not running" (`ipcMessages.ts`).
|
||||
#[test]
|
||||
fn not_running_refusals_carry_the_shared_prefix() {
|
||||
use crate::commands::file_commands::NOT_RUNNING_PREFIX;
|
||||
let m = not_running_message("checking this file for changes", "files live in its container");
|
||||
assert_eq!(m, "Start the project before checking this file for changes — files live in its container.");
|
||||
assert!(m.starts_with(NOT_RUNNING_PREFIX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_file_serialises_both_hashes() {
|
||||
let json = serde_json::to_value(SavedFile { hash: "a".into(), disk_hash: "b".into() }).unwrap();
|
||||
assert_eq!(json, serde_json::json!({ "hash": "a", "disk_hash": "b" }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_title_is_basename_then_project() {
|
||||
assert_eq!(window_title("app/src/lib/urlRelay.ts", "Triple-C"), "urlRelay.ts — Triple-C");
|
||||
assert_eq!(window_title("/workspace/x/README.md", "x"), "README.md — x");
|
||||
assert_eq!(window_title("Makefile", "p"), "Makefile — p");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewer_state_serialises_the_ipc_shape() {
|
||||
let target = ViewerTarget {
|
||||
project_id: "pid".into(),
|
||||
project_name: "P".into(),
|
||||
raw_path: "src/a.rs".into(),
|
||||
state: ViewerTargetState::Resolved { container_path: "/workspace/p/src/a.rs".into() },
|
||||
initial: Location { line: Some(3), col: Some(2), end_line: None },
|
||||
};
|
||||
let json = serde_json::to_value(viewer_state_of("file-viewer-1", target)).unwrap();
|
||||
assert_eq!(json["project_id"], "pid");
|
||||
assert_eq!(json["state"]["kind"], "resolved");
|
||||
assert_eq!(json["state"]["container_path"], "/workspace/p/src/a.rs");
|
||||
assert_eq!(json["initial"]["line"], 3);
|
||||
assert!(json["initial"]["end_line"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_encoded_length_is_capped_before_decoding() {
|
||||
let at_cap = BASE64.encode(vec![0u8; MAX_WRITE_BYTES]);
|
||||
assert!(check_encoded_len(at_cap.len()).is_ok());
|
||||
// MAX + 1 and MAX + 2 bytes pad to the same length as MAX; `write_file`'s
|
||||
// decoded check refuses those. The first size this bound itself refuses:
|
||||
let over_cap = BASE64.encode(vec![0u8; MAX_WRITE_BYTES + 3]);
|
||||
assert!(check_encoded_len(over_cap.len()).is_err());
|
||||
assert!(check_encoded_len(at_cap.len() + 1).is_err());
|
||||
assert!(check_encoded_len(0).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ pub mod auth_token_commands;
|
||||
pub mod aws_commands;
|
||||
pub mod docker_commands;
|
||||
pub mod file_commands;
|
||||
pub mod file_viewer_commands;
|
||||
pub mod gateway_commands;
|
||||
pub mod help_commands;
|
||||
pub mod inspect_commands;
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
//! The terminal file viewer: one OS window per clicked path.
|
||||
//!
|
||||
//! Every window is a `file-viewer-<n>` label registered in [`registry::ViewerRegistry`];
|
||||
//! the commands in `commands/file_viewer_commands.rs` gate on the label and act only on
|
||||
//! the caller's own entry, which is why nothing here takes a path from a window.
|
||||
//!
|
||||
//! `file-viewer-*` is also the `windows` glob of `capabilities/file-viewer.json`, which grants
|
||||
//! exactly the five `viewer_*` commands and nothing else. Labels are minted only here; a window
|
||||
//! created anywhere else with a matching label would inherit those grants.
|
||||
|
||||
pub mod poll;
|
||||
pub mod registry;
|
||||
pub mod resolve;
|
||||
pub mod window;
|
||||
pub mod write;
|
||||
|
||||
/// Spec §3: the 21st click is refused with a toast.
|
||||
pub const MAX_VIEWER_WINDOWS: usize = 20;
|
||||
pub const VIEWER_LABEL_PREFIX: &str = "file-viewer-";
|
||||
|
||||
pub fn is_viewer_label(label: &str) -> bool {
|
||||
label
|
||||
.strip_prefix(VIEWER_LABEL_PREFIX)
|
||||
.is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_numbered_viewer_labels_pass() {
|
||||
assert!(is_viewer_label("file-viewer-1"));
|
||||
assert!(is_viewer_label("file-viewer-20"));
|
||||
assert!(!is_viewer_label("file-viewer-"));
|
||||
assert!(!is_viewer_label("file-viewer-x"));
|
||||
assert!(!is_viewer_label("main"));
|
||||
assert!(!is_viewer_label("browser-view-abc"));
|
||||
}
|
||||
|
||||
/// Both Vite's dev server and Tauri's asset lookup fall back to `index.html`
|
||||
/// when `viewer.html` is missing, so a broken entry opens the *main app* in
|
||||
/// the viewer window with no error anywhere. Pin the two files the entry needs.
|
||||
#[test]
|
||||
fn the_viewer_entry_exists_and_is_a_vite_input() {
|
||||
let app_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
|
||||
let html = std::fs::read_to_string(app_dir.join("viewer.html")).expect("app/viewer.html");
|
||||
assert!(html.contains("/src/viewer/main.tsx"));
|
||||
assert!(!html.contains("<style"), "an inline <style> makes Tauri add a style nonce, which disables 'unsafe-inline' and breaks CodeMirror");
|
||||
let vite = std::fs::read_to_string(app_dir.join("vite.config.ts")).expect("vite.config.ts");
|
||||
assert!(vite.contains("viewer.html"), "vite.config.ts must list viewer.html in build.rollupOptions.input");
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Capability {
|
||||
windows: Vec<String>,
|
||||
permissions: Vec<String>,
|
||||
}
|
||||
|
||||
/// Task 12: a substring check on the capability JSON (the form this test used to take)
|
||||
/// only proves a permission string appears *somewhere* in the file — it would not catch
|
||||
/// `windows` widened past `file-viewer-*`, nor an extra grant slipped in beside the ones
|
||||
/// this window actually needs. Parse both capability files and pin `windows`/`permissions`
|
||||
/// exactly, so a later widening of either file is a failing test, not a silent threat-model
|
||||
/// drift — this file *is* the reviewed threat model of record (see its own description).
|
||||
#[test]
|
||||
fn the_viewer_capability_grants_exactly_the_reviewed_windows_and_permissions() {
|
||||
let app_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
|
||||
let raw = std::fs::read_to_string(app_dir.join("src-tauri/capabilities/file-viewer.json"))
|
||||
.expect("capabilities/file-viewer.json");
|
||||
let cap: Capability = serde_json::from_str(&raw).expect("file-viewer.json must be valid JSON");
|
||||
|
||||
assert_eq!(cap.windows, vec!["file-viewer-*"]);
|
||||
|
||||
let mut permissions = cap.permissions;
|
||||
permissions.sort();
|
||||
assert_eq!(
|
||||
permissions,
|
||||
vec![
|
||||
// App commands (bare): the five viewer commands, and nothing else — build.rs
|
||||
// refuses any other bare grant in this file.
|
||||
"allow-viewer-choose-file",
|
||||
"allow-viewer-get-state",
|
||||
"allow-viewer-poll-file",
|
||||
"allow-viewer-read-file",
|
||||
"allow-viewer-write-file",
|
||||
// Plugin/core grants, unchanged.
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-unlisten",
|
||||
"core:webview:allow-internal-toggle-devtools",
|
||||
"core:window:allow-destroy",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The main window's capability file must stay scoped to `main` — a `windows` list that
|
||||
/// grew to include `file-viewer-*` would hand every viewer window the dialog/store surface
|
||||
/// `default.json` grants `main`, which is a much larger IPC surface than the one
|
||||
/// `file-viewer.json` was deliberately kept small.
|
||||
#[test]
|
||||
fn the_default_capability_is_scoped_to_the_main_window_only() {
|
||||
let app_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
|
||||
let raw = std::fs::read_to_string(app_dir.join("src-tauri/capabilities/default.json"))
|
||||
.expect("capabilities/default.json");
|
||||
let cap: Capability = serde_json::from_str(&raw).expect("default.json must be valid JSON");
|
||||
|
||||
assert_eq!(cap.windows, vec!["main"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
//! One cheap exec per tick: the file's full hash and size, or "gone".
|
||||
//!
|
||||
//! This is what the 2 s poll asks, instead of re-downloading up to 1 MiB of archive per
|
||||
//! window per tick. The hash is coreutils `sha256sum`, which equals `write::sha256_hex`
|
||||
//! of the bytes whenever the read was not truncated — the only case in which the
|
||||
//! editor uses a hash as its save base.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::docker::exec::exec_oneshot_streams_as;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
|
||||
pub struct ViewerPoll {
|
||||
pub exists: bool,
|
||||
pub hash: Option<String>,
|
||||
pub size: Option<u64>,
|
||||
}
|
||||
|
||||
/// Exit 4 = gone. A failure after `test -f` passed is re-checked: if the file vanished
|
||||
/// in between (deleted while being hashed), that is "gone", not an error (M6).
|
||||
pub const POLL_SCRIPT: &str = r#"test -f "$1" || exit 4
|
||||
sha256sum -- "$1" && stat -c %s -- "$1" && exit 0
|
||||
test -f "$1" || exit 4
|
||||
exit 1"#;
|
||||
|
||||
pub fn parse_poll_output(code: i64, stdout: &str) -> ViewerPoll {
|
||||
if code == 4 {
|
||||
return ViewerPoll { exists: false, hash: None, size: None };
|
||||
}
|
||||
let mut lines = stdout.lines();
|
||||
let hash = lines
|
||||
.next()
|
||||
.and_then(|l| l.split_whitespace().next())
|
||||
// GNU `sha256sum` prefixes the line with `\` when the name contains a
|
||||
// backslash or a newline; strip it before validating the hex (P15).
|
||||
.map(|h| h.trim_start_matches('\\'))
|
||||
.filter(|h| super::write::is_sha256_hex(h))
|
||||
.map(str::to_string);
|
||||
let size = lines.next().and_then(|l| l.trim().parse::<u64>().ok());
|
||||
ViewerPoll { exists: true, hash, size }
|
||||
}
|
||||
|
||||
pub async fn poll_file(container_id: &str, container_path: &str) -> Result<ViewerPoll, String> {
|
||||
let cmd = vec![
|
||||
"sh".to_string(),
|
||||
"-c".to_string(),
|
||||
POLL_SCRIPT.to_string(),
|
||||
"poll".to_string(),
|
||||
container_path.to_string(),
|
||||
];
|
||||
let (stdout, stderr, code) =
|
||||
exec_oneshot_streams_as(container_id, "claude", cmd, Vec::new()).await?;
|
||||
if code != 0 && code != 4 {
|
||||
return Err(format!(
|
||||
"Could not check the file: {}",
|
||||
crate::commands::file_commands::clip_container_text(&stderr)
|
||||
));
|
||||
}
|
||||
Ok(parse_poll_output(code, &stdout))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_present_file_yields_hash_and_size() {
|
||||
let out = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 /workspace/x\n42\n";
|
||||
assert_eq!(
|
||||
parse_poll_output(0, out),
|
||||
ViewerPoll {
|
||||
exists: true,
|
||||
hash: Some("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".into()),
|
||||
size: Some(42)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_four_means_gone() {
|
||||
assert_eq!(parse_poll_output(4, ""), ViewerPoll { exists: false, hash: None, size: None });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_is_not_a_hash() {
|
||||
let p = parse_poll_output(0, "not a hash /x\nabc\n");
|
||||
assert_eq!(p, ViewerPoll { exists: true, hash: None, size: None });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_script_tests_existence_before_hashing() {
|
||||
assert!(POLL_SCRIPT.contains("test -f \"$1\" || exit 4"));
|
||||
assert!(POLL_SCRIPT.contains("sha256sum -- \"$1\""));
|
||||
assert!(POLL_SCRIPT.contains("stat -c %s -- \"$1\""));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn run_poll_script(path_env: Option<&str>, target: &std::path::Path) -> (i64, String, String) {
|
||||
let mut cmd = std::process::Command::new("sh");
|
||||
if let Some(p) = path_env {
|
||||
cmd.env("PATH", p);
|
||||
}
|
||||
let out = cmd.arg("-c").arg(POLL_SCRIPT).arg("poll").arg(target).output().unwrap();
|
||||
(
|
||||
out.status.code().unwrap_or(-1) as i64,
|
||||
String::from_utf8_lossy(&out.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&out.stderr).into_owned(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn test_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("tc-poll-{}-{}", name, uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn on_the_host_the_poll_script_reports_hash_size_and_gone() {
|
||||
let dir = test_dir("plain");
|
||||
let target = dir.join("t.txt");
|
||||
std::fs::write(&target, b"hello\n").unwrap();
|
||||
let (code, stdout, stderr) = run_poll_script(None, &target);
|
||||
assert_eq!(code, 0, "stderr={stderr}");
|
||||
let p = parse_poll_output(code, &stdout);
|
||||
assert_eq!(p.hash.as_deref(), Some(super::super::write::sha256_hex(b"hello\n").as_str()));
|
||||
assert_eq!(p.size, Some(6));
|
||||
|
||||
let (code, _, _) = run_poll_script(None, &dir.join("missing"));
|
||||
assert_eq!(code, 4);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// M6: the file is deleted after `test -f` passed but before `sha256sum` read it
|
||||
/// (a `sha256sum` shim on PATH deletes it and fails). That is "gone", not an error
|
||||
/// the viewer would have to explain.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn on_the_host_a_file_deleted_mid_poll_reads_as_gone() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = test_dir("race");
|
||||
let bin = dir.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let shim = bin.join("sha256sum");
|
||||
std::fs::write(&shim, "#!/bin/sh\nrm -f -- \"$2\"\necho 'sha256sum: No such file or directory' >&2\nexit 1\n").unwrap();
|
||||
std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let target = dir.join("t.txt");
|
||||
std::fs::write(&target, b"x").unwrap();
|
||||
let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default());
|
||||
|
||||
let (code, stdout, stderr) = run_poll_script(Some(&path), &target);
|
||||
|
||||
assert_eq!(code, 4, "stderr={stderr}");
|
||||
assert_eq!(parse_poll_output(code, &stdout), ViewerPoll { exists: false, hash: None, size: None });
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A failure with the file still present stays a real error (exit 1), which
|
||||
/// `poll_file` turns into "Could not check the file: …".
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn on_the_host_a_hash_failure_on_a_present_file_is_an_error() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = test_dir("fail");
|
||||
let bin = dir.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let shim = bin.join("sha256sum");
|
||||
std::fs::write(&shim, "#!/bin/sh\necho 'sha256sum: Permission denied' >&2\nexit 1\n").unwrap();
|
||||
std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let target = dir.join("t.txt");
|
||||
std::fs::write(&target, b"x").unwrap();
|
||||
let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default());
|
||||
|
||||
let (code, _stdout, stderr) = run_poll_script(Some(&path), &target);
|
||||
|
||||
assert_eq!(code, 1, "stderr={stderr}");
|
||||
assert!(stderr.contains("Permission denied"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// P15: a path containing a backslash makes GNU `sha256sum` prefix the whole
|
||||
/// line with `\`; that must not blind change detection by yielding `hash: None`.
|
||||
#[test]
|
||||
fn a_backslash_prefixed_hash_is_still_recognised() {
|
||||
let out = "\\e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 /workspace/x\\y\n7\n";
|
||||
let p = parse_poll_output(0, out);
|
||||
assert_eq!(
|
||||
p.hash.as_deref(),
|
||||
Some("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
|
||||
);
|
||||
assert_eq!(p.size, Some(7));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
//! Which viewer window is looking at what.
|
||||
//!
|
||||
//! Managed with `app.manage(ViewerRegistry::default())` rather than as a field on
|
||||
//! `AppState`, like the browser view keeps its own state. A label is reserved *before*
|
||||
//! the window is built so two concurrent clicks cannot both pass the cap check.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{MAX_VIEWER_WINDOWS, VIEWER_LABEL_PREFIX};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
pub struct Location {
|
||||
pub line: Option<u32>,
|
||||
pub col: Option<u32>,
|
||||
pub end_line: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum ViewerTargetState {
|
||||
Resolved { container_path: String },
|
||||
Choose { candidates: Vec<String> },
|
||||
NotFound { tried: Vec<String> },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
|
||||
pub struct ViewerTarget {
|
||||
pub project_id: String,
|
||||
pub project_name: String,
|
||||
pub raw_path: String,
|
||||
pub state: ViewerTargetState,
|
||||
pub initial: Location,
|
||||
}
|
||||
|
||||
/// What [`ViewerRegistry::reserve`] decided.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Reservation {
|
||||
/// A window is already registered on this file. `built` is false while that
|
||||
/// window is still being created: it has no `WebviewWindow` to focus yet, and
|
||||
/// it will open at its own location, so the caller should simply return.
|
||||
Existing { label: String, built: bool },
|
||||
/// A new label, registered and counted against the cap; build its window,
|
||||
/// then call [`ViewerRegistry::mark_built`] (or `remove` if building failed).
|
||||
Reserved(String),
|
||||
}
|
||||
|
||||
/// What [`ViewerRegistry::choose`] decided.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Choice {
|
||||
/// The caller's entry now points at the chosen file.
|
||||
Resolved(ViewerTarget),
|
||||
/// Another window already has that file; the caller's entry is unchanged.
|
||||
AlreadyOpen { label: String, built: bool },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Entry {
|
||||
target: ViewerTarget,
|
||||
/// Set once the window's `build()` has returned. Until then the label has no
|
||||
/// window by design, so "registered but windowless" means "being built", not
|
||||
/// "stale" — only built entries are ever pruned.
|
||||
built: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ViewerRegistry {
|
||||
entries: Mutex<HashMap<String, Entry>>,
|
||||
next: AtomicU64,
|
||||
}
|
||||
|
||||
fn same_file(t: &ViewerTarget, project_id: &str, container_path: &str) -> bool {
|
||||
t.project_id == project_id
|
||||
&& matches!(&t.state, ViewerTargetState::Resolved { container_path: p } if p == container_path)
|
||||
}
|
||||
|
||||
fn open_on(
|
||||
entries: &HashMap<String, Entry>,
|
||||
project_id: &str,
|
||||
container_path: &str,
|
||||
except: Option<&str>,
|
||||
) -> Option<(String, bool)> {
|
||||
entries
|
||||
.iter()
|
||||
.find(|(label, e)| Some(label.as_str()) != except && same_file(&e.target, project_id, container_path))
|
||||
.map(|(label, e)| (label.clone(), e.built))
|
||||
}
|
||||
|
||||
/// Drops built entries whose window is gone, whatever their state. `Destroyed`
|
||||
/// normally removes an entry; this is the backstop for one it missed, so a leak
|
||||
/// can never hold a cap slot for good.
|
||||
fn prune(entries: &mut HashMap<String, Entry>, is_live: &dyn Fn(&str) -> bool) {
|
||||
entries.retain(|label, e| !e.built || is_live(label));
|
||||
}
|
||||
|
||||
impl ViewerRegistry {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Entry>> {
|
||||
self.entries.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Finds the window already open on a resolved target, or reserves a label,
|
||||
/// in one critical section, after pruning built entries `is_live` says are
|
||||
/// gone. `is_live` runs under the registry lock and must not call back into
|
||||
/// the registry.
|
||||
pub fn reserve(
|
||||
&self,
|
||||
target: ViewerTarget,
|
||||
is_live: impl Fn(&str) -> bool,
|
||||
) -> Result<Reservation, String> {
|
||||
let mut entries = self.lock();
|
||||
prune(&mut entries, &is_live);
|
||||
if let ViewerTargetState::Resolved { container_path } = &target.state {
|
||||
if let Some((label, built)) = open_on(&entries, &target.project_id, container_path, None) {
|
||||
return Ok(Reservation::Existing { label, built });
|
||||
}
|
||||
}
|
||||
if entries.len() >= MAX_VIEWER_WINDOWS {
|
||||
return Err(format!(
|
||||
"{} file windows are already open — close one before opening another.",
|
||||
MAX_VIEWER_WINDOWS
|
||||
));
|
||||
}
|
||||
let n = self.next.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
let label = format!("{}{}", VIEWER_LABEL_PREFIX, n);
|
||||
entries.insert(label.clone(), Entry { target, built: false });
|
||||
Ok(Reservation::Reserved(label))
|
||||
}
|
||||
|
||||
/// Records that `label`'s window exists. A no-op if it was already removed
|
||||
/// (a window destroyed the moment it appeared).
|
||||
pub fn mark_built(&self, label: &str) {
|
||||
if let Some(e) = self.lock().get_mut(label) {
|
||||
e.built = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Points `label`'s entry at `container_path`, unless another window already
|
||||
/// has that file open — then the entry is left alone, so no two entries are
|
||||
/// ever resolved to the same file.
|
||||
pub fn choose(
|
||||
&self,
|
||||
label: &str,
|
||||
container_path: String,
|
||||
is_live: impl Fn(&str) -> bool,
|
||||
) -> Result<Choice, String> {
|
||||
let mut entries = self.lock();
|
||||
prune(&mut entries, &is_live);
|
||||
let project_id = entries
|
||||
.get(label)
|
||||
.ok_or_else(|| "This file window is no longer registered.".to_string())?
|
||||
.target
|
||||
.project_id
|
||||
.clone();
|
||||
if let Some((other, built)) = open_on(&entries, &project_id, &container_path, Some(label)) {
|
||||
return Ok(Choice::AlreadyOpen { label: other, built });
|
||||
}
|
||||
let entry = entries.get_mut(label).expect("checked above under the same lock");
|
||||
entry.target.state = ViewerTargetState::Resolved { container_path };
|
||||
Ok(Choice::Resolved(entry.target.clone()))
|
||||
}
|
||||
|
||||
pub fn get(&self, label: &str) -> Option<ViewerTarget> {
|
||||
self.lock().get(label).map(|e| e.target.clone())
|
||||
}
|
||||
|
||||
pub fn set_state(&self, label: &str, state: ViewerTargetState) -> Result<ViewerTarget, String> {
|
||||
let mut entries = self.lock();
|
||||
let entry = entries
|
||||
.get_mut(label)
|
||||
.ok_or_else(|| "This file window is no longer registered.".to_string())?;
|
||||
entry.target.state = state;
|
||||
Ok(entry.target.clone())
|
||||
}
|
||||
|
||||
pub fn remove(&self, label: &str) {
|
||||
self.lock().remove(label);
|
||||
}
|
||||
|
||||
pub fn find_open(&self, project_id: &str, container_path: &str) -> Option<String> {
|
||||
open_on(&self.lock(), project_id, container_path, None).map(|(label, _)| label)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.lock().len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn target(project: &str, path: &str) -> ViewerTarget {
|
||||
ViewerTarget {
|
||||
project_id: project.into(),
|
||||
project_name: "Demo".into(),
|
||||
raw_path: path.into(),
|
||||
state: ViewerTargetState::Resolved { container_path: path.into() },
|
||||
initial: Location { line: Some(3), col: None, end_line: None },
|
||||
}
|
||||
}
|
||||
|
||||
fn all_live(_: &str) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Reserves a label that must be new.
|
||||
fn fresh(r: &ViewerRegistry, t: ViewerTarget) -> String {
|
||||
match r.reserve(t, all_live).unwrap() {
|
||||
Reservation::Reserved(label) => label,
|
||||
other => panic!("expected a new label, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
fn choosing(project: &str, candidates: &[&str]) -> ViewerTarget {
|
||||
ViewerTarget {
|
||||
state: ViewerTargetState::Choose { candidates: candidates.iter().map(|c| c.to_string()).collect() },
|
||||
..target(project, "a")
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_are_sequential_and_never_reused() {
|
||||
let r = ViewerRegistry::default();
|
||||
let a = fresh(&r, target("p", "/workspace/a"));
|
||||
let b = fresh(&r, target("p", "/workspace/b"));
|
||||
assert_eq!(a, "file-viewer-1");
|
||||
assert_eq!(b, "file-viewer-2");
|
||||
r.remove(&a);
|
||||
let c = fresh(&r, target("p", "/workspace/c"));
|
||||
assert_eq!(c, "file-viewer-3");
|
||||
assert_eq!(r.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cap_refuses_the_twenty_first_window() {
|
||||
let r = ViewerRegistry::default();
|
||||
for i in 0..MAX_VIEWER_WINDOWS {
|
||||
fresh(&r, target("p", &format!("/workspace/{}", i)));
|
||||
}
|
||||
let err = r.reserve(target("p", "/workspace/one-more"), all_live).unwrap_err();
|
||||
assert!(err.contains("20"), "{}", err);
|
||||
assert_eq!(r.len(), MAX_VIEWER_WINDOWS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_resolved_file_is_found_by_project_and_path() {
|
||||
let r = ViewerRegistry::default();
|
||||
let label = fresh(&r, target("p", "/workspace/a"));
|
||||
assert_eq!(r.find_open("p", "/workspace/a"), Some(label.clone()));
|
||||
assert_eq!(r.find_open("other", "/workspace/a"), None);
|
||||
// A window still choosing is not "open on" any path.
|
||||
r.set_state(&label, ViewerTargetState::Choose { candidates: vec!["/workspace/a".into()] }).unwrap();
|
||||
assert_eq!(r.find_open("p", "/workspace/a"), None);
|
||||
r.remove(&label);
|
||||
assert_eq!(r.get(&label), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_state_on_an_unknown_label_is_an_error() {
|
||||
let r = ViewerRegistry::default();
|
||||
assert!(r.set_state("file-viewer-9", ViewerTargetState::NotFound { tried: vec![] }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_state_serialises_with_a_kind_tag() {
|
||||
let s = serde_json::to_string(&ViewerTargetState::NotFound { tried: vec!["/x".into()] }).unwrap();
|
||||
assert_eq!(s, r#"{"kind":"not_found","tried":["/x"]}"#);
|
||||
}
|
||||
|
||||
/// I1: a second click while the first window is still being built must find
|
||||
/// that window, not read it as stale and reserve a second one.
|
||||
#[test]
|
||||
fn a_window_being_built_is_found_not_replaced() {
|
||||
let r = ViewerRegistry::default();
|
||||
let a = fresh(&r, target("p", "/workspace/a"));
|
||||
// No window exists yet for `a`: `is_live` says so, and it must not matter.
|
||||
let second = r.reserve(target("p", "/workspace/a"), |_| false).unwrap();
|
||||
assert_eq!(second, Reservation::Existing { label: a.clone(), built: false });
|
||||
assert!(r.get(&a).is_some());
|
||||
assert_eq!(r.len(), 1);
|
||||
|
||||
r.mark_built(&a);
|
||||
let third = r.reserve(target("p", "/workspace/a"), all_live).unwrap();
|
||||
assert_eq!(third, Reservation::Existing { label: a, built: true });
|
||||
assert_eq!(r.len(), 1);
|
||||
}
|
||||
|
||||
/// A built entry whose window is gone is stale: pruned, and the file reopens.
|
||||
#[test]
|
||||
fn a_built_entry_without_a_window_is_pruned_and_the_file_reopens() {
|
||||
let r = ViewerRegistry::default();
|
||||
let a = fresh(&r, target("p", "/workspace/a"));
|
||||
r.mark_built(&a);
|
||||
let again = r.reserve(target("p", "/workspace/a"), |_| false).unwrap();
|
||||
assert_eq!(again, Reservation::Reserved("file-viewer-2".into()));
|
||||
assert_eq!(r.get(&a), None);
|
||||
assert_eq!(r.len(), 1);
|
||||
}
|
||||
|
||||
/// M2: a leaked entry of any state cannot hold a cap slot once built and gone,
|
||||
/// and an entry still being built always keeps its slot.
|
||||
#[test]
|
||||
fn leaked_entries_of_every_state_free_their_cap_slot() {
|
||||
let r = ViewerRegistry::default();
|
||||
let mut labels = Vec::new();
|
||||
for i in 0..MAX_VIEWER_WINDOWS {
|
||||
let t = match i % 3 {
|
||||
0 => target("p", &format!("/workspace/{}", i)),
|
||||
1 => choosing("p", &["/workspace/x", "/workspace/y"]),
|
||||
_ => ViewerTarget { state: ViewerTargetState::NotFound { tried: vec![] }, ..target("p", "z") },
|
||||
};
|
||||
labels.push(fresh(&r, t));
|
||||
}
|
||||
// All still being built: none may be pruned, so the cap holds.
|
||||
assert!(r.reserve(target("p", "/workspace/new"), |_| false).is_err());
|
||||
for l in &labels {
|
||||
r.mark_built(l);
|
||||
}
|
||||
// Built, and one of each state has lost its window.
|
||||
let dead = [labels[0].clone(), labels[1].clone(), labels[2].clone()];
|
||||
let live = |l: &str| !dead.iter().any(|d| d == l);
|
||||
assert!(matches!(r.reserve(target("p", "/workspace/new"), live), Ok(Reservation::Reserved(_))));
|
||||
assert_eq!(r.len(), MAX_VIEWER_WINDOWS - 2);
|
||||
for d in &dead {
|
||||
assert_eq!(r.get(d), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mark_built_on_a_removed_label_is_a_no_op() {
|
||||
let r = ViewerRegistry::default();
|
||||
let a = fresh(&r, target("p", "/workspace/a"));
|
||||
r.remove(&a);
|
||||
r.mark_built(&a);
|
||||
assert_eq!(r.get(&a), None);
|
||||
}
|
||||
|
||||
/// M5: choosing a file another window already has leaves the chooser alone,
|
||||
/// so two entries are never resolved to the same file.
|
||||
#[test]
|
||||
fn choosing_a_file_open_elsewhere_does_not_resolve_a_second_entry() {
|
||||
let r = ViewerRegistry::default();
|
||||
let open = fresh(&r, target("p", "/workspace/x"));
|
||||
r.mark_built(&open);
|
||||
let chooser = fresh(&r, choosing("p", &["/workspace/x", "/workspace/y"]));
|
||||
r.mark_built(&chooser);
|
||||
|
||||
let c = r.choose(&chooser, "/workspace/x".into(), all_live).unwrap();
|
||||
assert_eq!(c, Choice::AlreadyOpen { label: open.clone(), built: true });
|
||||
assert!(matches!(r.get(&chooser).unwrap().state, ViewerTargetState::Choose { .. }));
|
||||
|
||||
match r.choose(&chooser, "/workspace/y".into(), all_live).unwrap() {
|
||||
Choice::Resolved(t) => assert_eq!(t.state, ViewerTargetState::Resolved { container_path: "/workspace/y".into() }),
|
||||
other => panic!("expected Resolved, got {:?}", other),
|
||||
}
|
||||
assert_eq!(r.find_open("p", "/workspace/y"), Some(chooser));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choosing_the_same_path_in_another_project_is_not_a_duplicate() {
|
||||
let r = ViewerRegistry::default();
|
||||
fresh(&r, target("other", "/workspace/x"));
|
||||
let chooser = fresh(&r, choosing("p", &["/workspace/x"]));
|
||||
assert!(matches!(r.choose(&chooser, "/workspace/x".into(), all_live), Ok(Choice::Resolved(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choose_on_an_unknown_label_is_an_error() {
|
||||
let r = ViewerRegistry::default();
|
||||
assert!(r.choose("file-viewer-9", "/workspace/x".into(), all_live).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Turning what Claude printed into a container path that exists.
|
||||
//!
|
||||
//! Relative paths are the common case (Claude prints project-relative paths). The
|
||||
//! terminal exec's cwd is `/workspace`, and each project path is mounted at
|
||||
//! `/workspace/<mount_name>`, so those are the roots probed, in that order. The probe
|
||||
//! is one exec as the container user and prints `realpath -e` of every candidate that
|
||||
//! is a regular file: `fetch_container_file` refuses a symlink, so the registry must
|
||||
//! hold the resolved path, not the one that was clicked.
|
||||
|
||||
use crate::commands::file_commands::validate_container_path;
|
||||
use crate::docker::exec::exec_oneshot_streams_as;
|
||||
|
||||
pub const MAX_CANDIDATES: usize = 16;
|
||||
const MAX_RAW_LEN: usize = 4096;
|
||||
|
||||
/// `$@` are the candidates. For each regular file, print its resolved path.
|
||||
pub const PROBE_SCRIPT: &str = r#"for c in "$@"; do if test -f "$c"; then realpath -e -- "$c" 2>/dev/null; fi; done; exit 0"#;
|
||||
|
||||
pub fn candidate_paths(raw: &str, mount_names: &[String]) -> Result<Vec<String>, String> {
|
||||
if raw.is_empty() {
|
||||
return Err("The path is empty.".into());
|
||||
}
|
||||
if raw.len() > MAX_RAW_LEN {
|
||||
return Err("The path is too long.".into());
|
||||
}
|
||||
if raw.contains('\0') {
|
||||
return Err("The path contains a NUL byte.".into());
|
||||
}
|
||||
if raw.split('/').any(|seg| seg == "..") {
|
||||
return Err(format!("{} climbs out of its folder with `..`; refusing.", raw));
|
||||
}
|
||||
|
||||
if raw.starts_with('/') {
|
||||
let normalised = collapse(raw);
|
||||
validate_container_path("File", &normalised)?;
|
||||
return Ok(vec![normalised]);
|
||||
}
|
||||
|
||||
let rel = collapse(raw.strip_prefix("./").unwrap_or(raw));
|
||||
let rel = rel.trim_start_matches("./");
|
||||
if rel.is_empty() {
|
||||
return Err("The path is empty.".into());
|
||||
}
|
||||
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let mut push = |candidate: String| {
|
||||
if out.len() < MAX_CANDIDATES && !out.contains(&candidate) {
|
||||
out.push(candidate);
|
||||
}
|
||||
};
|
||||
push(format!("/workspace/{}", rel));
|
||||
for mount in mount_names {
|
||||
if mount.is_empty() || mount.contains('/') || mount == "." || mount == ".." {
|
||||
continue;
|
||||
}
|
||||
push(format!("/workspace/{}/{}", mount, rel));
|
||||
}
|
||||
for c in &out {
|
||||
validate_container_path("File", c)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `a//b/./c` → `a/b/c`. Never touches `..` (rejected before this runs).
|
||||
fn collapse(path: &str) -> String {
|
||||
let absolute = path.starts_with('/');
|
||||
let joined = path
|
||||
.split('/')
|
||||
.filter(|seg| !seg.is_empty() && *seg != ".")
|
||||
.collect::<Vec<_>>()
|
||||
.join("/");
|
||||
if absolute { format!("/{}", joined) } else { joined }
|
||||
}
|
||||
|
||||
/// One resolved path per line; anything that is not an absolute, valid container path is
|
||||
/// dropped (the script's own diagnostics go to stderr, but a hostile `realpath` output is
|
||||
/// still container-authored text).
|
||||
pub fn parse_probe_output(stdout: &str) -> Vec<String> {
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
for line in stdout.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || validate_container_path("File", line).is_err() {
|
||||
continue;
|
||||
}
|
||||
if !seen.iter().any(|s| s == line) {
|
||||
seen.push(line.to_string());
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
pub async fn probe_candidates(
|
||||
container_id: &str,
|
||||
candidates: &[String],
|
||||
) -> Result<Vec<String>, String> {
|
||||
let mut cmd: Vec<String> = vec!["sh".into(), "-c".into(), PROBE_SCRIPT.into(), "probe".into()];
|
||||
cmd.extend(candidates.iter().cloned());
|
||||
let (stdout, _stderr, _code) =
|
||||
exec_oneshot_streams_as(container_id, "claude", cmd, Vec::new()).await?;
|
||||
Ok(parse_probe_output(&stdout))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn mounts(names: &[&str]) -> Vec<String> {
|
||||
names.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absolute_path_is_its_own_only_candidate() {
|
||||
let c = candidate_paths("/workspace/api/src/main.rs", &mounts(&["api"])).unwrap();
|
||||
assert_eq!(c, vec!["/workspace/api/src/main.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_relative_path_probes_workspace_then_each_mount() {
|
||||
let c = candidate_paths("src/main.rs", &mounts(&["api", "web"])).unwrap();
|
||||
assert_eq!(
|
||||
c,
|
||||
vec!["/workspace/src/main.rs", "/workspace/api/src/main.rs", "/workspace/web/src/main.rs"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_prefix_and_duplicate_slashes_are_normalised_and_candidates_deduped() {
|
||||
let c = candidate_paths("./src//main.rs", &mounts(&["api", "api", ""])).unwrap();
|
||||
assert_eq!(c, vec!["/workspace/src/main.rs", "/workspace/api/src/main.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traversal_nul_and_oversize_are_refused() {
|
||||
assert!(candidate_paths("../etc/passwd", &[]).is_err());
|
||||
assert!(candidate_paths("src/../../x", &[]).is_err());
|
||||
assert!(candidate_paths("/workspace/../etc/passwd", &[]).is_err());
|
||||
assert!(candidate_paths("a\0b", &[]).is_err());
|
||||
assert!(candidate_paths("", &[]).is_err());
|
||||
assert!(candidate_paths(&"a".repeat(5000), &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidate_list_is_capped() {
|
||||
let many: Vec<String> = (0..40).map(|i| format!("m{}", i)).collect();
|
||||
let c = candidate_paths("x.rs", &many).unwrap();
|
||||
assert_eq!(c.len(), MAX_CANDIDATES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_output_keeps_valid_resolved_regular_files_only() {
|
||||
let out = "/workspace/api/src/main.rs\n/workspace/api/src/main.rs\n\nrelative/junk\n/etc/../x\n/workspace/web/src/main.rs\n";
|
||||
assert_eq!(
|
||||
parse_probe_output(out),
|
||||
vec!["/workspace/api/src/main.rs", "/workspace/web/src/main.rs"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_probe_script_prints_resolved_paths_of_regular_files() {
|
||||
// Shape assertions: the script is data handed to `sh -c`, and these are the
|
||||
// three things a later edit must not lose.
|
||||
assert!(PROBE_SCRIPT.contains("test -f"));
|
||||
assert!(PROBE_SCRIPT.contains("realpath -e --"));
|
||||
assert!(PROBE_SCRIPT.contains("for c in \"$@\""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! The viewer window itself. Mirrors `browser_view/popout.rs`, with two differences:
|
||||
//! the URL is the app's own second entry (`WebviewUrl::App`), so the capability in
|
||||
//! `capabilities/file-viewer.json` applies; and the registry entry is removed on
|
||||
//! `Destroyed`, which fires for both the X button (after JS calls `destroy()`) and a
|
||||
//! Rust-side `destroy()`.
|
||||
|
||||
use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent};
|
||||
|
||||
use super::registry::ViewerRegistry;
|
||||
|
||||
pub fn open_viewer_window(app: &AppHandle, label: &str, title: &str) -> Result<(), String> {
|
||||
let window = WebviewWindowBuilder::new(app, label, WebviewUrl::App("viewer.html".into()))
|
||||
.title(title)
|
||||
.inner_size(900.0, 700.0)
|
||||
.min_inner_size(480.0, 320.0)
|
||||
.build()
|
||||
.map_err(|e| format!("Could not open the file window: {}", e))?;
|
||||
|
||||
let app_for_event = app.clone();
|
||||
let label_owned = label.to_string();
|
||||
window.on_window_event(move |event| {
|
||||
if let WindowEvent::Destroyed = event {
|
||||
app_for_event.state::<ViewerRegistry>().remove(&label_owned);
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
//! Saving: stage in `/tmp`, then swap in as the container user.
|
||||
//!
|
||||
//! The Docker archive API writes as root, so it is used for exactly one thing — landing
|
||||
//! the payload at `/tmp/triple-c-viewer-<uuid>`, owned by the container user (the
|
||||
//! existing `write_file_to_container`). Everything that touches the *target directory*
|
||||
//! runs in an exec as `claude`, so a save can do nothing the user's own shell could not.
|
||||
//! A non-root process cannot `chown`, so the saved file is owned by the container user,
|
||||
//! as it would be after Claude Code edited it; mode is kept with `chmod --reference`.
|
||||
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::commands::file_commands::clip_container_text;
|
||||
use crate::docker::exec::{exec_oneshot_streams_as, ExecSessionManager};
|
||||
|
||||
/// Spec §4/§5: only untruncated (≤ 1 MiB) text is editable, so nothing larger is saved.
|
||||
pub const MAX_WRITE_BYTES: usize = 1024 * 1024;
|
||||
|
||||
pub fn sha256_hex(bytes: &[u8]) -> String {
|
||||
let digest = Sha256::digest(bytes);
|
||||
digest.iter().map(|b| format!("{:02x}", b)).collect()
|
||||
}
|
||||
|
||||
pub fn is_sha256_hex(s: &str) -> bool {
|
||||
s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
|
||||
}
|
||||
|
||||
/// `$1` target, `$2` staged payload in /tmp, `$3` the hash the editor loaded from.
|
||||
/// Exit 1 = a step failed (unreadable target, a failed stage/replace, …), 3 = changed
|
||||
/// on disk, 4 = gone, 5 = the target is not writable by the container user; stdout on
|
||||
/// success is `sha256sum` of the target *after* the write. That is not necessarily the
|
||||
/// hash of what we wrote: another writer (Claude Code, on the same file) can land
|
||||
/// between `mv` and `sha256sum`. `saved_file` therefore takes the save's base from the
|
||||
/// bytes and only reports this one as what the disk held afterwards (M2).
|
||||
///
|
||||
/// P15: `sha256sum -- "$target"` prefixes its whole line with `\` when the path
|
||||
/// contains a backslash or a newline, so `$actual` has that prefix stripped before
|
||||
/// it is compared with `$expect` (which never carries one) — otherwise such a path
|
||||
/// would conflict forever.
|
||||
///
|
||||
/// I1: `$actual` is read from a plain `sha256sum` command substitution, not a
|
||||
/// pipeline into `cut` — POSIX sh has no `pipefail`, so `cmd | cut … || exit 1` tests
|
||||
/// only `cut`'s exit status and an unreadable file (EACCES, EIO) fell through as a
|
||||
/// false "changed on disk" conflict (empty `$actual` never equals `$expect`) instead
|
||||
/// of a real error, hiding the actual failure from the user and from `classify_write`.
|
||||
///
|
||||
/// I2/M3: `$staged` is created by `mktemp` (exclusive — never follows a planted
|
||||
/// symlink or stale leftover at that name) and is part of the `EXIT` trap from the
|
||||
/// moment it is assigned, so a failure at any later step (`cp`, `chmod`, `mv`) cannot
|
||||
/// leave a partial `.<name>.triple-c-<suffix>` behind in the user's own directory —
|
||||
/// including on a signal, for the steps after the trap covers it.
|
||||
pub const WRITE_SCRIPT: &str = r#"target=$1; tmp=$2; expect=$3
|
||||
staged=
|
||||
trap 'rm -f -- "$tmp" ${staged:+"$staged"}' EXIT
|
||||
test -f "$target" || exit 4
|
||||
actual=$(sha256sum -- "$target") || exit 1
|
||||
actual=${actual%% *}; actual=${actual#\\}
|
||||
[ "$actual" = "$expect" ] || exit 3
|
||||
# I3: the file's own mode is a boundary the user set from outside the container (0444,
|
||||
# a different owning uid, a read-only bind mount, …). Replacing it via rename or
|
||||
# truncating it in place would silently cross that boundary even though `claude` is
|
||||
# allowed to — an editor such as vim, or a plain `echo > file` in the user's own shell,
|
||||
# would refuse. This is stricter than spec §5 step 3's literal "if the directory is
|
||||
# writable" branch, which never looks at the file's own permissions; the branch below
|
||||
# only ever chooses *how* to write, never *whether*.
|
||||
#
|
||||
# The rename branch replaces whatever is at "$target" (a symlink planted there after
|
||||
# the window opened is replaced, not followed). The in-place `cat >` fallback, taken
|
||||
# only for a writable file in a read-only directory, DOES follow such a symlink and
|
||||
# writes through it. That is accepted: the write runs as `claude`, so it can reach
|
||||
# nothing Claude Code in the same container cannot already write.
|
||||
[ -w "$target" ] || { echo "The file is read-only for the container user." >&2; exit 5; }
|
||||
dir=$(dirname -- "$target"); name=$(basename -- "$target")
|
||||
if [ -w "$dir" ]; then
|
||||
staged=$(mktemp -- "$dir/.$name.triple-c-XXXXXX") || exit 1
|
||||
cp -- "$tmp" "$staged" || exit 1
|
||||
chmod --reference="$target" "$staged" 2>/dev/null
|
||||
mv -f -- "$staged" "$target" || exit 1
|
||||
else
|
||||
cat -- "$tmp" > "$target" || exit 1
|
||||
fi
|
||||
sha256sum -- "$target""#;
|
||||
|
||||
/// A save refused because the file changed since its base hash. The frontend matches
|
||||
/// this prefix; its copy lives in `app/src/viewer/ipcMessages.ts` (pinned by a test).
|
||||
pub const CONFLICT_PREFIX: &str = "conflict:";
|
||||
/// A save refused because the file no longer exists; mirrored in `ipcMessages.ts`.
|
||||
pub const GONE_PREFIX: &str = "gone:";
|
||||
/// The read-only refusal. The script echoes the same sentence (pinned by a test), but
|
||||
/// the caller always gets this constant, whatever the script printed; mirrored in
|
||||
/// `ipcMessages.ts`.
|
||||
pub const READ_ONLY_MESSAGE: &str = "The file is read-only for the container user.";
|
||||
|
||||
/// I3: distinct from the generic failure code so the caller can hand back a specific,
|
||||
/// readable message instead of whatever the script's own diagnostic text says.
|
||||
const EXIT_READ_ONLY: i64 = 5;
|
||||
|
||||
pub enum WriteOutcome {
|
||||
Saved(String),
|
||||
Conflict,
|
||||
Gone,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
pub fn classify_write(code: i64, stdout: &str, stderr: &str) -> WriteOutcome {
|
||||
match code {
|
||||
3 => WriteOutcome::Conflict,
|
||||
4 => WriteOutcome::Gone,
|
||||
EXIT_READ_ONLY => WriteOutcome::Failed(READ_ONLY_MESSAGE.into()),
|
||||
0 => match stdout
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.map(|h| h.trim_start_matches('\\'))
|
||||
.filter(|h| is_sha256_hex(h))
|
||||
{
|
||||
Some(h) => WriteOutcome::Saved(h.to_string()),
|
||||
None => WriteOutcome::Failed(
|
||||
"The container did not report the saved file's hash.".into(),
|
||||
),
|
||||
},
|
||||
_ => WriteOutcome::Failed(clip_container_text(stderr)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The write script's argv beyond `sh -c SCRIPT`: `$0=save`, `$1=target`, `$2=tmp`,
|
||||
/// `$3=base_hash` — pulled out pure so the argument shape has a unit test (P8).
|
||||
fn write_command(target: &str, tmp: &str, base_hash: &str) -> Vec<String> {
|
||||
vec![
|
||||
"sh".to_string(),
|
||||
"-c".to_string(),
|
||||
WRITE_SCRIPT.to_string(),
|
||||
"save".to_string(),
|
||||
target.to_string(),
|
||||
tmp.to_string(),
|
||||
base_hash.to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Refuses a payload too large to be editable, or a malformed base hash, before
|
||||
/// anything is staged in the container (P8).
|
||||
fn check_write_input(len: usize, base_hash: &str) -> Result<(), String> {
|
||||
if len > MAX_WRITE_BYTES {
|
||||
return Err("Files over 1 MiB are read-only in the viewer.".into());
|
||||
}
|
||||
if !is_sha256_hex(base_hash) {
|
||||
return Err("The editor's base hash is malformed; reload the file.".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What a successful save reports: `hash` is the new base, `sha256_hex` of the bytes
|
||||
/// we wrote; `disk_hash` is what the container hashed right after the swap. They differ
|
||||
/// only when another writer landed in between, and then the editor must show "Changed
|
||||
/// on disk" rather than adopt the other writer's hash as its base (M2).
|
||||
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
|
||||
pub struct SavedFile {
|
||||
pub hash: String,
|
||||
pub disk_hash: String,
|
||||
}
|
||||
|
||||
/// `viewer_write_file`'s result, pure so the error-prefix contract has a unit test.
|
||||
fn saved_file(outcome: WriteOutcome, bytes: &[u8]) -> Result<SavedFile, String> {
|
||||
match outcome {
|
||||
WriteOutcome::Saved(disk_hash) => Ok(SavedFile { hash: sha256_hex(bytes), disk_hash }),
|
||||
WriteOutcome::Conflict => Err(format!(
|
||||
"{} the file changed on disk since it was loaded.",
|
||||
CONFLICT_PREFIX
|
||||
)),
|
||||
WriteOutcome::Gone => Err(format!("{} the file no longer exists.", GONE_PREFIX)),
|
||||
WriteOutcome::Failed(msg) => Err(format!("Could not save the file: {}", msg)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn write_file(
|
||||
container_id: &str,
|
||||
exec_manager: &ExecSessionManager,
|
||||
target: &str,
|
||||
bytes: &[u8],
|
||||
base_hash: &str,
|
||||
) -> Result<SavedFile, String> {
|
||||
check_write_input(bytes.len(), base_hash)?;
|
||||
let tmp_name = format!("triple-c-viewer-{}", uuid::Uuid::new_v4().simple());
|
||||
let tmp_path = exec_manager
|
||||
.write_file_to_container(container_id, &tmp_name, bytes)
|
||||
.await?;
|
||||
let cmd = write_command(target, &tmp_path, base_hash);
|
||||
let (stdout, stderr, code) =
|
||||
exec_oneshot_streams_as(container_id, "claude", cmd, Vec::new()).await?;
|
||||
saved_file(classify_write(code, &stdout, &stderr), bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sha256_matches_coreutils() {
|
||||
// `printf 'hello\n' | sha256sum`
|
||||
assert_eq!(
|
||||
sha256_hex(b"hello\n"),
|
||||
"5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03"
|
||||
);
|
||||
assert!(is_sha256_hex(&sha256_hex(b"")));
|
||||
assert!(!is_sha256_hex("ABC"));
|
||||
assert!(!is_sha256_hex(&"g".repeat(64)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_codes_map_to_outcomes() {
|
||||
let h = "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";
|
||||
assert!(matches!(classify_write(0, &format!("{} /x\n", h), ""), WriteOutcome::Saved(s) if s == h));
|
||||
assert!(matches!(classify_write(3, "", ""), WriteOutcome::Conflict));
|
||||
assert!(matches!(classify_write(4, "", ""), WriteOutcome::Gone));
|
||||
assert!(matches!(classify_write(1, "", "cp: Permission denied"), WriteOutcome::Failed(m) if m.contains("Permission denied")));
|
||||
// Success without a parseable hash is still a failure: the editor's base would be wrong.
|
||||
assert!(matches!(classify_write(0, "junk", ""), WriteOutcome::Failed(_)));
|
||||
}
|
||||
|
||||
/// I3: exit 5 is the script's read-only refusal, and it must not be swallowed by
|
||||
/// the generic `_ => Failed(stderr)` arm — the caller gets a fixed, readable
|
||||
/// message regardless of exactly what the script printed.
|
||||
#[test]
|
||||
fn exit_five_is_a_distinct_read_only_refusal() {
|
||||
assert!(matches!(
|
||||
classify_write(5, "", "The file is read-only for the container user."),
|
||||
WriteOutcome::Failed(m) if m.contains("read-only")
|
||||
));
|
||||
}
|
||||
|
||||
/// M2: the new base is the hash of the bytes we wrote, never the script's
|
||||
/// post-`mv` hash, which may belong to a writer that landed after us.
|
||||
#[test]
|
||||
fn a_save_takes_its_base_from_the_written_bytes() {
|
||||
let ours = sha256_hex(b"new\n");
|
||||
let same = saved_file(WriteOutcome::Saved(ours.clone()), b"new\n").unwrap();
|
||||
assert_eq!(same, SavedFile { hash: ours.clone(), disk_hash: ours.clone() });
|
||||
|
||||
let foreign = sha256_hex(b"someone else's\n");
|
||||
let raced = saved_file(WriteOutcome::Saved(foreign.clone()), b"new\n").unwrap();
|
||||
assert_eq!(raced.hash, ours, "the base must be what we wrote");
|
||||
assert_eq!(raced.disk_hash, foreign, "the foreign hash is reported, not adopted");
|
||||
}
|
||||
|
||||
/// Important #4: the frontend matches these exact strings
|
||||
/// (`app/src/viewer/ipcMessages.ts`), so pin them here too.
|
||||
#[test]
|
||||
fn save_errors_keep_the_prefix_contract() {
|
||||
let conflict = saved_file(WriteOutcome::Conflict, b"").unwrap_err();
|
||||
assert!(conflict.starts_with("conflict:"), "{conflict}");
|
||||
assert_eq!(conflict, "conflict: the file changed on disk since it was loaded.");
|
||||
|
||||
let gone = saved_file(WriteOutcome::Gone, b"").unwrap_err();
|
||||
assert!(gone.starts_with("gone:"), "{gone}");
|
||||
assert_eq!(gone, "gone: the file no longer exists.");
|
||||
|
||||
let read_only = saved_file(classify_write(5, "", "whatever the script said"), b"").unwrap_err();
|
||||
assert_eq!(read_only, "Could not save the file: The file is read-only for the container user.");
|
||||
assert!(!read_only.starts_with(CONFLICT_PREFIX) && !read_only.starts_with(GONE_PREFIX));
|
||||
|
||||
let other = saved_file(classify_write(1, "", "No space left on device"), b"").unwrap_err();
|
||||
assert_eq!(other, "Could not save the file: No space left on device");
|
||||
|
||||
// The script's own refusal text is the same sentence the caller is given.
|
||||
assert!(WRITE_SCRIPT.contains(&format!("echo \"{}\" >&2; exit 5", READ_ONLY_MESSAGE)));
|
||||
}
|
||||
|
||||
/// The TypeScript side keeps one copy of each matched string; a change on either
|
||||
/// side without the other fails here.
|
||||
#[test]
|
||||
fn the_frontend_copies_of_the_ipc_messages_match() {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../src/viewer/ipcMessages.ts");
|
||||
let ts = std::fs::read_to_string(&path).expect("app/src/viewer/ipcMessages.ts");
|
||||
for (name, value) in [
|
||||
("CONFLICT_PREFIX", CONFLICT_PREFIX),
|
||||
("GONE_PREFIX", GONE_PREFIX),
|
||||
("READ_ONLY_MESSAGE", READ_ONLY_MESSAGE),
|
||||
("NOT_RUNNING_PREFIX", crate::commands::file_commands::NOT_RUNNING_PREFIX),
|
||||
] {
|
||||
let line = format!("export const {} = \"{}\";", name, value);
|
||||
assert!(ts.contains(&line), "ipcMessages.ts must contain `{line}`");
|
||||
}
|
||||
}
|
||||
|
||||
/// P15: a target path with a backslash makes `sha256sum` prefix the line;
|
||||
/// the parsed hash must still be recognised as the saved hash.
|
||||
#[test]
|
||||
fn a_backslash_prefixed_saved_hash_is_still_recognised() {
|
||||
let h = "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";
|
||||
assert!(matches!(
|
||||
classify_write(0, &format!("\\{} /x\\y\n", h), ""),
|
||||
WriteOutcome::Saved(s) if s == h
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_write_script_checks_then_swaps_and_always_cleans_up() {
|
||||
for needle in [
|
||||
"test -f \"$target\" || exit 4",
|
||||
"exit 3",
|
||||
"chmod --reference=\"$target\"",
|
||||
"mv -f --",
|
||||
"cat -- \"$tmp\" > \"$target\"",
|
||||
// I2/M3: the trap covers the staged file too, and it comes from `mktemp`.
|
||||
"trap 'rm -f -- \"$tmp\" ${staged:+\"$staged\"}' EXIT",
|
||||
"mktemp -- \"$dir/.$name.triple-c-XXXXXX\"",
|
||||
// I1: a plain command substitution, not a pipeline `cut` could mask.
|
||||
"actual=$(sha256sum -- \"$target\") || exit 1",
|
||||
// I3: a read-only target is refused before any write is attempted.
|
||||
"[ -w \"$target\" ] || { echo \"The file is read-only for the container user.\" >&2; exit 5; }",
|
||||
] {
|
||||
assert!(WRITE_SCRIPT.contains(needle), "missing: {}", needle);
|
||||
}
|
||||
// The old pipeline form must be gone, not merely superseded.
|
||||
assert!(!WRITE_SCRIPT.contains("cut -d' ' -f1"));
|
||||
}
|
||||
|
||||
/// P8: the write script's test list is binding, and the argument order is
|
||||
/// exactly what a later edit could silently break.
|
||||
#[test]
|
||||
fn write_command_has_the_expected_argv_shape() {
|
||||
let cmd = write_command("/w/t.txt", "/tmp/x", "abc123");
|
||||
assert_eq!(
|
||||
cmd,
|
||||
vec![
|
||||
"sh".to_string(),
|
||||
"-c".to_string(),
|
||||
WRITE_SCRIPT.to_string(),
|
||||
"save".to_string(),
|
||||
"/w/t.txt".to_string(),
|
||||
"/tmp/x".to_string(),
|
||||
"abc123".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// P8: the size cap and base-hash checks are unit-testable in isolation from
|
||||
/// the async `write_file`.
|
||||
#[test]
|
||||
fn check_write_input_refuses_oversized_payload_and_malformed_hash() {
|
||||
let h = "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";
|
||||
assert!(check_write_input(MAX_WRITE_BYTES, h).is_ok());
|
||||
assert!(check_write_input(MAX_WRITE_BYTES + 1, h).is_err());
|
||||
assert!(check_write_input(0, "not-a-hash").is_err());
|
||||
}
|
||||
|
||||
// ── M10: WRITE_SCRIPT run for real, against a temp dir on the host ──────────
|
||||
//
|
||||
// The needle test above only proves the script *contains* certain substrings; it
|
||||
// cannot catch the pipefail-shaped bug I1 was (the needle text was correct, the
|
||||
// shell semantics were not). These run the exact `sh -c SCRIPT save target tmp
|
||||
// hash` invocation `write_command` builds, so they pin the exit codes and cleanup
|
||||
// behaviour that `write_file`/`classify_write` actually depend on. `sh` and the
|
||||
// coreutils used here (`sha256sum`, `mktemp`, `dirname`, `basename`) are present
|
||||
// on dev machines and CI alike.
|
||||
|
||||
#[cfg(unix)]
|
||||
fn run_write_script(
|
||||
target: &std::path::Path,
|
||||
tmp: &std::path::Path,
|
||||
base_hash: &str,
|
||||
) -> (i32, String, String) {
|
||||
let out = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(WRITE_SCRIPT)
|
||||
.arg("save")
|
||||
.arg(target)
|
||||
.arg(tmp)
|
||||
.arg(base_hash)
|
||||
.output()
|
||||
.expect("sh must be on PATH to run this test");
|
||||
(
|
||||
out.status.code().unwrap_or(-1),
|
||||
String::from_utf8_lossy(&out.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&out.stderr).into_owned(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn unique_test_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("tc-write-{}-{}", name, uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn on_the_host_a_clean_save_replaces_the_file_and_cleans_up() {
|
||||
let dir = unique_test_dir("clean");
|
||||
let target = dir.join("t.txt");
|
||||
let tmp = dir.join("payload");
|
||||
std::fs::write(&target, b"old\n").unwrap();
|
||||
std::fs::write(&tmp, b"new\n").unwrap();
|
||||
let base = sha256_hex(b"old\n");
|
||||
|
||||
let (code, stdout, stderr) = run_write_script(&target, &tmp, &base);
|
||||
|
||||
assert_eq!(code, 0, "stdout={stdout} stderr={stderr}");
|
||||
let new_hash = sha256_hex(b"new\n");
|
||||
assert!(stdout.contains(&new_hash), "stdout={stdout}");
|
||||
// With no other writer, the reported disk hash is ours, so no conflict is shown.
|
||||
let saved = saved_file(classify_write(code as i64, &stdout, &stderr), b"new\n").unwrap();
|
||||
assert_eq!(saved, SavedFile { hash: new_hash.clone(), disk_hash: new_hash.clone() });
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"new\n");
|
||||
assert!(!tmp.exists(), "the staged /tmp payload must be cleaned up");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// M2, for real: another writer lands between the script's `mv` and its final
|
||||
/// `sha256sum` (simulated by a `sha256sum` shim on PATH that rewrites the target on
|
||||
/// its second call). The save's base must still be the hash of our bytes, and the
|
||||
/// foreign hash must come back as `disk_hash`, so the editor shows "Changed on disk".
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn on_the_host_a_write_that_lands_after_ours_is_reported_not_adopted() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let real = std::process::Command::new("sh")
|
||||
.args(["-c", "command -v sha256sum"])
|
||||
.output()
|
||||
.expect("sh");
|
||||
let real = String::from_utf8_lossy(&real.stdout).trim().to_string();
|
||||
assert!(!real.is_empty(), "sha256sum must be on PATH");
|
||||
|
||||
let dir = unique_test_dir("race");
|
||||
let bin = dir.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let mark = dir.join("called-once");
|
||||
let shim = bin.join("sha256sum");
|
||||
std::fs::write(
|
||||
&shim,
|
||||
format!(
|
||||
"#!/bin/sh\nif [ -e '{mark}' ]; then printf 'theirs\\n' > \"$2\"; fi\n: > '{mark}'\nexec '{real}' \"$@\"\n",
|
||||
mark = mark.display(),
|
||||
real = real
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let target = dir.join("t.txt");
|
||||
let tmp = dir.join("payload");
|
||||
std::fs::write(&target, b"old\n").unwrap();
|
||||
std::fs::write(&tmp, b"new\n").unwrap();
|
||||
let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default());
|
||||
let out = std::process::Command::new("sh")
|
||||
.env("PATH", path)
|
||||
.arg("-c")
|
||||
.arg(WRITE_SCRIPT)
|
||||
.arg("save")
|
||||
.arg(&target)
|
||||
.arg(&tmp)
|
||||
.arg(sha256_hex(b"old\n"))
|
||||
.output()
|
||||
.unwrap();
|
||||
let (stdout, stderr) = (String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||
assert_eq!(out.status.code(), Some(0), "stdout={stdout} stderr={stderr}");
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"theirs\n", "the shim's write landed last");
|
||||
|
||||
let saved = saved_file(classify_write(0, &stdout, &stderr), b"new\n").unwrap();
|
||||
assert_eq!(saved.hash, sha256_hex(b"new\n"));
|
||||
assert_eq!(saved.disk_hash, sha256_hex(b"theirs\n"));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn on_the_host_a_stale_base_hash_conflicts_and_leaves_everything_untouched() {
|
||||
let dir = unique_test_dir("stale");
|
||||
let target = dir.join("t.txt");
|
||||
let tmp = dir.join("payload");
|
||||
std::fs::write(&target, b"old\n").unwrap();
|
||||
std::fs::write(&tmp, b"new\n").unwrap();
|
||||
let wrong_base = sha256_hex(b"not what is on disk\n");
|
||||
|
||||
let (code, _stdout, stderr) = run_write_script(&target, &tmp, &wrong_base);
|
||||
|
||||
assert_eq!(code, 3, "stderr={stderr}");
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"old\n", "must be untouched");
|
||||
assert!(!tmp.exists(), "the staged /tmp payload must still be cleaned up");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn on_the_host_a_missing_target_reports_gone() {
|
||||
let dir = unique_test_dir("gone");
|
||||
let target = dir.join("does-not-exist");
|
||||
let tmp = dir.join("payload");
|
||||
std::fs::write(&tmp, b"new\n").unwrap();
|
||||
|
||||
let (code, _stdout, stderr) = run_write_script(&target, &tmp, &sha256_hex(b"whatever"));
|
||||
|
||||
assert_eq!(code, 4, "stderr={stderr}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// I1: a real read failure must be a real error (exit 1), never the exit-3
|
||||
/// conflict a bare `sha256sum | cut` pipeline (no `pipefail` in POSIX sh) would
|
||||
/// silently produce.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn on_the_host_an_unreadable_target_is_an_error_not_a_conflict() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = unique_test_dir("unreadable");
|
||||
let target = dir.join("t.txt");
|
||||
let tmp = dir.join("payload");
|
||||
std::fs::write(&target, b"old\n").unwrap();
|
||||
std::fs::write(&tmp, b"new\n").unwrap();
|
||||
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o000)).unwrap();
|
||||
|
||||
if std::fs::read(&target).is_ok() {
|
||||
// Running as root (or some other bypass): 0o000 does not block reads,
|
||||
// so this scenario cannot be reproduced here.
|
||||
eprintln!("skipping: still able to read a 0o000 file (root?)");
|
||||
let _ = std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
return;
|
||||
}
|
||||
|
||||
let (code, _stdout, stderr) = run_write_script(&target, &tmp, &sha256_hex(b"old\n"));
|
||||
|
||||
assert_eq!(
|
||||
code, 1,
|
||||
"an unreadable target must be a real error, not exit 3; stderr={stderr}"
|
||||
);
|
||||
assert!(!tmp.exists(), "the staged /tmp payload must still be cleaned up");
|
||||
|
||||
let _ = std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// I3: a target the container user cannot write is refused outright, never
|
||||
/// replaced via rename.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn on_the_host_a_read_only_target_is_refused_not_replaced() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = unique_test_dir("readonly");
|
||||
let target = dir.join("t.txt");
|
||||
let tmp = dir.join("payload");
|
||||
std::fs::write(&target, b"old\n").unwrap();
|
||||
std::fs::write(&tmp, b"new\n").unwrap();
|
||||
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o444)).unwrap();
|
||||
|
||||
if std::fs::OpenOptions::new().write(true).open(&target).is_ok() {
|
||||
eprintln!("skipping: still able to write a 0o444 file (root?)");
|
||||
let _ = std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
return;
|
||||
}
|
||||
|
||||
let (code, _stdout, stderr) = run_write_script(&target, &tmp, &sha256_hex(b"old\n"));
|
||||
|
||||
assert_eq!(code as i64, EXIT_READ_ONLY, "stderr={stderr}");
|
||||
assert!(stderr.contains("read-only"), "stderr={stderr}");
|
||||
assert_eq!(
|
||||
std::fs::read(&target).unwrap(),
|
||||
b"old\n",
|
||||
"a read-only file must not be replaced"
|
||||
);
|
||||
assert!(!tmp.exists(), "the staged /tmp payload must still be cleaned up");
|
||||
|
||||
let _ = std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// I2: a failed stage (here: an unreadable source payload, so `cp` fails after
|
||||
/// `mktemp` has already created the destination) must not leave a partial
|
||||
/// `.<name>.triple-c-<suffix>` behind in the user's own directory.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn on_the_host_a_failed_stage_leaves_no_partial_file_behind() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = unique_test_dir("cpfail");
|
||||
let target = dir.join("t.txt");
|
||||
let tmp = dir.join("payload");
|
||||
std::fs::write(&target, b"old\n").unwrap();
|
||||
std::fs::write(&tmp, b"new\n").unwrap();
|
||||
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o000)).unwrap();
|
||||
|
||||
if std::fs::read(&tmp).is_ok() {
|
||||
eprintln!("skipping: still able to read a 0o000 file (root?)");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
return;
|
||||
}
|
||||
|
||||
let (code, _stdout, stderr) = run_write_script(&target, &tmp, &sha256_hex(b"old\n"));
|
||||
|
||||
assert_eq!(code, 1, "stderr={stderr}");
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"old\n", "must be untouched");
|
||||
let leftovers: Vec<_> = std::fs::read_dir(&dir)
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.starts_with(".t.txt.triple-c-"))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty(), "staged file(s) left behind: {leftovers:?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
+141
-40
@@ -1,7 +1,10 @@
|
||||
mod auth_bridge;
|
||||
mod browser_view;
|
||||
#[cfg(test)]
|
||||
mod command_census;
|
||||
mod commands;
|
||||
mod docker;
|
||||
pub mod file_viewer;
|
||||
mod install_helper;
|
||||
mod logging;
|
||||
mod models;
|
||||
@@ -240,6 +243,7 @@ pub fn run() {
|
||||
lifecycle,
|
||||
pending_settings_import: Arc::new(tokio::sync::Mutex::new(None)),
|
||||
})
|
||||
.manage(file_viewer::registry::ViewerRegistry::default())
|
||||
.setup(move |app| {
|
||||
match tauri::image::Image::from_bytes(include_bytes!("../icons/icon.png")) {
|
||||
Ok(icon) => {
|
||||
@@ -545,6 +549,13 @@ pub fn run() {
|
||||
commands::file_commands::read_container_file,
|
||||
commands::file_commands::rename_container_path,
|
||||
commands::file_commands::create_container_directory,
|
||||
// Terminal file viewer
|
||||
commands::file_viewer_commands::open_file_viewer,
|
||||
commands::file_viewer_commands::viewer_get_state,
|
||||
commands::file_viewer_commands::viewer_choose_file,
|
||||
commands::file_viewer_commands::viewer_read_file,
|
||||
commands::file_viewer_commands::viewer_poll_file,
|
||||
commands::file_viewer_commands::viewer_write_file,
|
||||
// AWS
|
||||
commands::aws_commands::aws_sso_refresh,
|
||||
// Updates
|
||||
@@ -835,30 +846,11 @@ mod tests {
|
||||
&mut defined,
|
||||
);
|
||||
|
||||
// The registration list, read from this file rather than from a macro
|
||||
// expansion so the test does not depend on `generate_handler!`'s shape.
|
||||
let this = include_str!("lib.rs");
|
||||
let handler = this
|
||||
.split_once("generate_handler![")
|
||||
.and_then(|(_, rest)| rest.split_once("])"))
|
||||
.map(|(inside, _)| inside)
|
||||
// The registration list, read from this file by the same parser `build.rs` uses to
|
||||
// declare the AppManifest — so if this test can see a command, the ACL can too.
|
||||
let ordered = crate::command_census::registered_commands(include_str!("lib.rs"))
|
||||
.expect("lib.rs should contain a generate_handler! list");
|
||||
// Line-based, not `split(',')`: the list is grouped under `// Docker`
|
||||
// style comments, and splitting on commas glues each comment to the
|
||||
// command that follows it. A `starts_with("//")` filter then drops that
|
||||
// command — silently, and once per group.
|
||||
let registered: BTreeSet<String> = handler
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty() && !l.starts_with("//"))
|
||||
.filter_map(|l| {
|
||||
l.trim_end_matches(',')
|
||||
.rsplit("::")
|
||||
.next()
|
||||
.map(|n| n.trim().to_string())
|
||||
})
|
||||
.filter(|n| !n.is_empty())
|
||||
.collect();
|
||||
let registered: BTreeSet<String> = ordered.iter().cloned().collect();
|
||||
|
||||
assert!(
|
||||
!defined.is_empty() && !registered.is_empty(),
|
||||
@@ -887,21 +879,11 @@ mod tests {
|
||||
// passed here.
|
||||
let mut seen: Vec<&str> = Vec::new();
|
||||
let mut duplicated: Vec<&str> = Vec::new();
|
||||
for line in handler
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty() && !l.starts_with("//"))
|
||||
{
|
||||
if let Some(name) = line.trim_end_matches(',').rsplit("::").next() {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if seen.contains(&name) {
|
||||
duplicated.push(name);
|
||||
} else {
|
||||
seen.push(name);
|
||||
}
|
||||
for name in &ordered {
|
||||
if seen.contains(&name.as_str()) {
|
||||
duplicated.push(name);
|
||||
} else {
|
||||
seen.push(name);
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
@@ -930,7 +912,10 @@ mod tests {
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut sorted = listed.clone();
|
||||
// Plugin and core grants: the exact reviewed list, unchanged by the lockdown.
|
||||
let (bare, prefixed): (Vec<String>, Vec<String>) =
|
||||
listed.iter().cloned().partition(|g| !g.contains(':'));
|
||||
let mut sorted = prefixed;
|
||||
sorted.sort();
|
||||
let mut expected = vec![
|
||||
"core:event:allow-listen",
|
||||
@@ -942,11 +927,31 @@ mod tests {
|
||||
expected.sort();
|
||||
assert_eq!(
|
||||
sorted, expected,
|
||||
"the capability set changed. That is allowed — but it is the IPC \
|
||||
"the plugin/core capability set changed. That is allowed — but it is the IPC \
|
||||
surface a compromised webview can call, so update this list \
|
||||
deliberately rather than to make the test pass."
|
||||
);
|
||||
|
||||
// App commands: since build.rs declares the AppManifest, the bare `allow-*` grants
|
||||
// are the complete list of app commands the main window may call. `build.rs` already
|
||||
// fails the build when they disagree with generate_handler!; this keeps the reviewed
|
||||
// rule ("every non-viewer command, exactly") visible where the plugin census lives.
|
||||
let registered = crate::command_census::registered_commands(include_str!("lib.rs"))
|
||||
.expect("lib.rs should contain a generate_handler! list");
|
||||
let mut expected_bare: Vec<String> = registered
|
||||
.iter()
|
||||
.filter(|c| crate::command_census::expected_windows(c) == ["main"])
|
||||
.map(|c| crate::command_census::allow_permission(c))
|
||||
.collect();
|
||||
expected_bare.sort();
|
||||
let mut bare = bare;
|
||||
bare.sort();
|
||||
assert_eq!(
|
||||
bare, expected_bare,
|
||||
"default.json's app-command grants must be exactly the main-window commands"
|
||||
);
|
||||
assert!(bare.len() >= 100, "the census found {} app grants; the parser has stopped seeing the list", bare.len());
|
||||
|
||||
// Belt and braces: the `*:default` aliases are the specific trap here,
|
||||
// because they expand to a set the file never spells out. `store:*` in
|
||||
// particular was an arbitrary host-file read/write primitive.
|
||||
@@ -964,4 +969,100 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `build.rs` derives the AppManifest from the handler list and this reads back what
|
||||
/// tauri-build actually embedded. `cargo test` runs the build script first, so
|
||||
/// `gen/schemas/acl-manifests.json` is fresh. This guards against the committed/generated
|
||||
/// artifact diverging from `generate_handler!` — a stale `acl-manifests.json`, or a
|
||||
/// tauri-build naming change — using the same `registered_commands` parser `build.rs` used
|
||||
/// to derive the manifest in the first place. It is *not* independent of a parser dropout on
|
||||
/// its own: if `registered_commands` lost half the list, `build.rs` would declare half a
|
||||
/// manifest and this would still compare it against the same half. That guarantee is
|
||||
/// transitive, not local — `every_command_is_registered_exactly_once` covers it, by
|
||||
/// cross-checking the parser's output against an independent `#[tauri::command]` scan, so a
|
||||
/// parser regression that silently dropped commands fails there rather than going unnoticed
|
||||
/// here.
|
||||
#[test]
|
||||
fn the_generated_app_manifest_matches_the_handler_list() {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/gen/schemas/acl-manifests.json");
|
||||
let raw = std::fs::read_to_string(path)
|
||||
.expect("gen/schemas/acl-manifests.json is written by build.rs on every build");
|
||||
let manifests: serde_json::Value =
|
||||
serde_json::from_str(&raw).expect("acl-manifests.json must parse");
|
||||
let app = manifests.get("__app-acl__").expect(
|
||||
"build.rs must declare an AppManifest — without it tauri skips the ACL for every \
|
||||
app command",
|
||||
);
|
||||
let embedded: BTreeSet<String> = app["permissions"]
|
||||
.as_object()
|
||||
.expect("the app manifest has a permissions map")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
let registered = crate::command_census::registered_commands(include_str!("lib.rs"))
|
||||
.expect("lib.rs should contain a generate_handler! list");
|
||||
let expected: BTreeSet<String> = registered
|
||||
.iter()
|
||||
.flat_map(|c| {
|
||||
let allow = crate::command_census::allow_permission(c);
|
||||
let deny = format!("deny-{}", &allow["allow-".len()..]);
|
||||
[allow, deny]
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert!(registered.len() >= 100, "the parser sees {} commands", registered.len());
|
||||
assert_eq!(
|
||||
embedded, expected,
|
||||
"the embedded app manifest and generate_handler! disagree: build.rs and \
|
||||
tauri-build should have produced the same list"
|
||||
);
|
||||
assert!(
|
||||
app["permission_sets"].as_object().is_some_and(|s| s.is_empty()),
|
||||
"no permission sets: every grant is a literal allow-* string in a capability file"
|
||||
);
|
||||
assert!(app["default_permission"].is_null(), "no app `default` permission set");
|
||||
}
|
||||
|
||||
/// `build.rs`'s `check_tauri_config` (inline `app.security.capabilities`, a JSON5/TOML tauri
|
||||
/// config, `TAURI_CONFIG`) only runs inside the build script, so it only re-runs on a clean
|
||||
/// build or in CI — cargo's incremental build has no reason to notice a new
|
||||
/// `tauri.<platform>.conf.json` dropped into an already-built tree (CLAUDE.md, "Known
|
||||
/// limit"). This runs the same check, using the same `command_census` functions build.rs
|
||||
/// calls, directly against the real `app/src-tauri` directory on every `cargo test`, so that
|
||||
/// gap is closed locally too.
|
||||
#[test]
|
||||
fn the_tauri_config_capability_check_runs_against_the_real_tree() {
|
||||
let dir = env!("CARGO_MANIFEST_DIR");
|
||||
let mut problems = Vec::new();
|
||||
for entry in std::fs::read_dir(dir).expect("readable src-tauri/") {
|
||||
let path = entry.expect("readable entry in src-tauri/").path();
|
||||
let name = path
|
||||
.file_name()
|
||||
.expect("a directory entry has a file name")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
match crate::command_census::tauri_config_file(&name) {
|
||||
None => {}
|
||||
Some(false) => problems.push(format!(
|
||||
"{name}: the census reads JSON tauri configs only; a JSON5/TOML config \
|
||||
could declare capabilities it cannot see"
|
||||
)),
|
||||
Some(true) => {
|
||||
let json =
|
||||
std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
problems.extend(crate::command_census::tauri_config_problem(&name, &json));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(json) = std::env::var("TAURI_CONFIG") {
|
||||
problems.extend(crate::command_census::tauri_config_problem("TAURI_CONFIG", &json));
|
||||
}
|
||||
assert!(
|
||||
problems.is_empty(),
|
||||
"cargo test found what build.rs would refuse on a clean build: {problems:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user