返回 CodeWhale
session_export_host.rs
根目录 / crates / tui / src / commands / session_export_host.rs
1 //! TUI-owned host services for the session-export slice (FEAT-025 D5/D7).
2 //!
3 //! This module deliberately lives outside `commands/groups/session`, which
4 //! FEAT-043 moves into `codewhale-commands`. It owns the filesystem services
5 //! the `/export` slice needs from the host:
6 //!
7 //! * the shared `last-copy.md` recovery writer reused by `/export` and `/copy`
8 //! (D5),
9 //! * the protected export-destination resolver/writer used only by `/export`
10 //! (D7), and
11 //! * the default export directory (`<home>/exports`) for exports that name no
12 //! path.
13 //!
14 //! The check order, error text, and platform behavior are the baseline
15 //! implementations relocated, extended only by leading-`~` expansion and the
16 //! default export directory. The portable `/export`
17 //! handler reaches these services only through
18 //! `CommandSessionExportContext` — never by importing this module — so the
19 //! future portable group keeps no host dependency.
20
21 use std::fs::{self, OpenOptions};
22 use std::io::Write as _;
23 use std::path::{Component, Path, PathBuf};
24
25 /// Write the export to a predictable last-copy file under the Codewhale home
26 /// (#5555): a clipboard-only export on SSH/headless must never dead-end the
27 /// user, so the same content lands at `<home>/exports/last-copy.md` and every
28 /// failure message names it. Returns the path when the write succeeded.
29 pub(crate) fn write_last_copy(markdown: &str) -> Option<PathBuf> {
30 let (exports_dir, _) = exports_dirs()?;
31 write_last_copy_to(&exports_dir, markdown).ok()
32 }
33
34 /// The Codewhale exports directory as `(logical, physical)` paths, created on
35 /// demand and confined to the Codewhale home: `None` when the home is
36 /// unresolvable or `exports` resolves outside it through a symlink.
37 fn exports_dirs() -> Option<(PathBuf, PathBuf)> {
38 let home = codewhale_paths::codewhale_home().ok().flatten()?;
39 let exports_dir = home.join("exports");
40 std::fs::create_dir_all(&exports_dir).ok()?;
41 let physical_home = std::fs::canonicalize(&home).ok()?;
42 let physical_exports = std::fs::canonicalize(&exports_dir).ok()?;
43 if !physical_exports.starts_with(&physical_home) {
44 return None;
45 }
46 Some((exports_dir, physical_exports))
47 }
48
49 /// Default destination for an export that named no path: `file_name` inside
50 /// the Codewhale exports directory. The physical directory is used so the
51 /// symlink-component guard in `write_export_file` is not tripped by platform
52 /// aliases such as macOS `/var -> /private/var` in the home path.
53 pub(crate) fn default_export_path(file_name: &str) -> Result<PathBuf, String> {
54 let mut components = Path::new(file_name).components();
55 if !matches!(
56 (components.next(), components.next()),
57 (Some(Component::Normal(_)), None)
58 ) {
59 return Err(format!(
60 "export file name must be a single path component: {file_name}"
61 ));
62 }
63 let (_, physical_exports) = exports_dirs()
64 .ok_or_else(|| "could not prepare the Codewhale exports directory".to_string())?;
65 Ok(physical_exports.join(file_name))
66 }
67
68 fn write_last_copy_to(exports_dir: &Path, markdown: &str) -> std::io::Result<PathBuf> {
69 std::fs::create_dir_all(exports_dir)?;
70 let path = exports_dir.join("last-copy.md");
71 // Reuse the private atomic writer: random same-directory temp names,
72 // restrictive creation mode, symlink-safe replacement, and Windows
73 // replace retries are all part of the existing persistence contract.
74 codewhale_util::utils::write_atomic(&path, markdown.as_bytes())?;
75 Ok(path)
76 }
77
78 /// Resolve a requested export destination against the trusted workspace root.
79 ///
80 /// Baseline algorithm (D7) plus home expansion: trim; empty → `export path is
81 /// empty`; expand a leading `~`/`~/`; reject `..` components; canonicalize the
82 /// workspace with its current fallback; rebase workspace-absolute paths (raw or
83 /// canonicalized); otherwise join workspace-relative; require a file name.
84 /// Errors are returned unwrapped so the portable handler keeps the exact text.
85 pub(crate) fn resolve_export_path(workspace: &Path, raw: &str) -> Result<PathBuf, String> {
86 let raw = raw.trim();
87 if raw.is_empty() {
88 return Err("export path is empty".to_string());
89 }
90 let requested = PathBuf::from(crate::commands::config_main_host::expand_tilde(raw));
91 if requested
92 .components()
93 .any(|component| component == Component::ParentDir)
94 {
95 return Err(
96 "export paths may not contain `..`; use an explicit normalized absolute path instead"
97 .to_string(),
98 );
99 }
100 // Resolve the trusted workspace root once so platform aliases such as
101 // macOS `/var -> /private/var` do not make every workspace-relative
102 // export look like it traverses a user-controlled symlink. Requested
103 // components beneath that root remain lexical and are checked below.
104 let resolved_workspace =
105 fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf());
106 let path = if requested.is_absolute() {
107 if let Ok(relative) = requested.strip_prefix(workspace) {
108 resolved_workspace.join(relative)
109 } else if let Ok(relative) = requested.strip_prefix(&resolved_workspace) {
110 resolved_workspace.join(relative)
111 } else {
112 requested
113 }
114 } else {
115 resolved_workspace.join(requested)
116 };
117 if path.file_name().is_none() {
118 return Err(format!("export path must name a file: {}", path.display()));
119 }
120 Ok(path)
121 }
122
123 /// Write rendered export bytes to a resolved destination with the exact
124 /// baseline protections (D7): parent presence/directory checks, symlink
125 /// rejection (leaf and ancestors), no overwrite by default, non-regular-file
126 /// rejection, exclusive creation with `0o600` on Unix, `fsync`, cleanup after a
127 /// failed write, forced atomic replacement, and owner-only permissions.
128 pub(crate) fn write_export_file(path: &Path, contents: &[u8], force: bool) -> Result<(), String> {
129 let parent = path
130 .parent()
131 .filter(|parent| !parent.as_os_str().is_empty())
132 .ok_or_else(|| format!("path has no parent directory: {}", path.display()))?;
133 let parent_metadata = fs::metadata(parent).map_err(|err| {
134 format!(
135 "parent directory {} is unavailable: {err}",
136 parent.display()
137 )
138 })?;
139 if !parent_metadata.is_dir() {
140 return Err(format!("parent is not a directory: {}", parent.display()));
141 }
142 reject_symlink_components(path)?;
143
144 match fs::symlink_metadata(path) {
145 Ok(_) if !force => {
146 return Err(format!(
147 "destination already exists: {}. Re-run with `/export file --force <path>` to replace it",
148 path.display()
149 ));
150 }
151 Ok(metadata) if !metadata.file_type().is_file() => {
152 return Err(format!(
153 "refusing to replace a non-regular file: {}",
154 path.display()
155 ));
156 }
157 Ok(_) => {}
158 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
159 Err(err) => return Err(format!("could not inspect {}: {err}", path.display())),
160 }
161
162 if force {
163 codewhale_util::utils::write_atomic(path, contents).map_err(|err| err.to_string())?;
164 set_owner_only(path).map_err(|err| format!("could not secure file permissions: {err}"))?;
165 return Ok(());
166 }
167
168 let mut options = OpenOptions::new();
169 options.write(true).create_new(true);
170 #[cfg(unix)]
171 {
172 use std::os::unix::fs::OpenOptionsExt;
173 options.mode(0o600);
174 }
175 let mut file = options.open(path).map_err(|err| {
176 if err.kind() == std::io::ErrorKind::AlreadyExists {
177 format!(
178 "destination already exists: {}. Re-run with `/export file --force <path>` to replace it",
179 path.display()
180 )
181 } else {
182 err.to_string()
183 }
184 })?;
185 if let Err(err) = file.write_all(contents).and_then(|()| file.sync_all()) {
186 drop(file);
187 let _ = fs::remove_file(path);
188 return Err(err.to_string());
189 }
190 set_owner_only(path).map_err(|err| format!("could not secure file permissions: {err}"))?;
191 #[cfg(unix)]
192 if let Err(err) = fs::File::open(parent).and_then(|dir| dir.sync_all())
193 && !codewhale_util::utils::is_directory_sync_refusal(&err)
194 {
195 tracing::warn!(dir = %parent.display(), %err, "could not sync export directory");
196 return Err(format!(
197 "could not sync export directory {}: {err}",
198 parent.display()
199 ));
200 }
201 Ok(())
202 }
203
204 fn reject_symlink_components(path: &Path) -> Result<(), String> {
205 for component_path in path.ancestors() {
206 match fs::symlink_metadata(component_path) {
207 Ok(metadata) if metadata.file_type().is_symlink() => {
208 return Err(format!(
209 "refusing export through symlink component: {}",
210 component_path.display()
211 ));
212 }
213 Ok(_) => {}
214 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
215 Err(err) => {
216 return Err(format!(
217 "could not inspect path component {}: {err}",
218 component_path.display()
219 ));
220 }
221 }
222 }
223 Ok(())
224 }
225
226 #[cfg(unix)]
227 fn set_owner_only(path: &Path) -> std::io::Result<()> {
228 use std::os::unix::fs::PermissionsExt;
229 fs::set_permissions(path, fs::Permissions::from_mode(0o600))
230 }
231
232 #[cfg(not(unix))]
233 fn set_owner_only(_path: &Path) -> std::io::Result<()> {
234 Ok(())
235 }
236
237 #[cfg(test)]
238 mod tests {
239 use super::*;
240 use tempfile::TempDir;
241
242 #[test]
243 fn last_copy_writes_the_export_without_leaving_a_temp_artifact() {
244 let tmp = TempDir::new().expect("tempdir");
245 let dir = tmp.path().join("exports");
246 let path = write_last_copy_to(&dir, "# export\n\nhello\n").expect("write");
247 assert_eq!(path, dir.join("last-copy.md"));
248 assert_eq!(
249 std::fs::read_to_string(&path).expect("read"),
250 "# export\n\nhello\n"
251 );
252 // The next export overwrites the same predictable path.
253 write_last_copy_to(&dir, "# second\n").expect("rewrite");
254 assert_eq!(std::fs::read_to_string(&path).expect("read"), "# second\n");
255 assert_eq!(
256 std::fs::read_dir(&dir).expect("read exports").count(),
257 1,
258 "the atomic writer must not leave a temp artifact"
259 );
260
261 #[cfg(unix)]
262 {
263 use std::os::unix::fs::PermissionsExt;
264 let mode = std::fs::metadata(&path)
265 .expect("metadata")
266 .permissions()
267 .mode();
268 assert_eq!(mode & 0o077, 0, "recovery copy must remain private");
269 }
270 }
271
272 #[test]
273 fn last_copy_stays_inside_an_explicit_codewhale_home() {
274 let ambient = TempDir::new().expect("ambient home");
275 let isolated = TempDir::new().expect("isolated Codewhale home");
276 let _env_lock = crate::test_support::lock_test_env();
277 let _home = crate::test_support::EnvVarGuard::set("HOME", ambient.path());
278 let _codewhale_home =
279 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", isolated.path());
280
281 let path = write_last_copy("isolated response").expect("recovery copy");
282
283 assert_eq!(path, isolated.path().join("exports/last-copy.md"));
284 assert_eq!(
285 std::fs::read_to_string(&path).expect("read recovery copy"),
286 "isolated response"
287 );
288 assert!(
289 !ambient.path().join("exports/last-copy.md").exists(),
290 "explicit CODEWHALE_HOME must prevent ambient-home writes"
291 );
292 }
293
294 #[cfg(unix)]
295 #[test]
296 fn last_copy_refuses_an_exports_symlink_outside_codewhale_home() {
297 use std::os::unix::fs::symlink;
298
299 let ambient = TempDir::new().expect("ambient home");
300 let isolated = TempDir::new().expect("isolated Codewhale home");
301 let external = TempDir::new().expect("external dir");
302 symlink(external.path(), isolated.path().join("exports")).expect("exports symlink");
303 let _env_lock = crate::test_support::lock_test_env();
304 let _home = crate::test_support::EnvVarGuard::set("HOME", ambient.path());
305 let _codewhale_home =
306 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", isolated.path());
307
308 assert_eq!(write_last_copy("must stay isolated"), None);
309 assert!(
310 !external.path().join("last-copy.md").exists(),
311 "recovery content must not escape through a nested symlink"
312 );
313 }
314 }
315
315 lines RUST