Mountain/Environment/Utility/PathSecurity.rs
1//! # Path Security Utilities
2//!
3//! Functions for validating filesystem access and enforcing workspace trust.
4
5use std::path::{Path, PathBuf};
6
7use CommonLibrary::Error::CommonError::CommonError;
8
9use crate::{ApplicationState::State::ApplicationState::ApplicationState, dev_log};
10
11/// A critical security helper that checks if a given filesystem path is
12/// allowed for access.
13///
14/// The access model has two tiers:
15///
16/// 1. **Trusted system paths** - directories Land itself owns (user extensions,
17/// agent plugins, app-support storage, bundled extension roots). These are
18/// never "user content" and the extension scanner, VSIX installer, and
19/// global-storage probes must be able to read/write them regardless of which
20/// workspace folder is open. They bypass the workspace-folder check
21/// entirely.
22///
23/// 2. **Workspace content** - everything else is only reachable when the
24/// resolved path is a descendant of a currently registered, trusted
25/// workspace folder. That's the sandbox boundary that keeps extensions from
26/// rifling through `$HOME` via `vscode.workspace.fs`.
27///
28/// Without tier 1, the scanner's read of `~/.land/extensions` is
29/// rejected as "Path is outside of the registered workspace folders", so
30/// user-installed VSIXes never reach the Extensions sidebar even though
31/// they are present on disk.
32pub fn IsPathAllowedForAccess(ApplicationState:&ApplicationState, PathToCheck:&Path) -> Result<(), CommonError> {
33 // Per-call verification line is one of the highest-volume tags
34 // (~15k hits per long session). The failure path below logs its own
35 // line; the success path is auditable from IPC-side request logs.
36 // Keep under `vfs-verbose` for deep debugging only.
37 dev_log!("vfs-verbose", "[EnvironmentSecurity] Verifying path: {}", PathToCheck.display());
38
39 // Defensive: empty path would slip through the trusted-system
40 // check (no allow-list segment matches) AND the workspace-
41 // descendant check (`Path::starts_with("")` returns true). Without
42 // this guard, an extension probing `vscode.workspace.fs.stat("")`
43 // would be authorised against ANY registered workspace folder.
44 // Reject up front so the caller falls through to its not-found
45 // handler.
46 if PathToCheck.as_os_str().is_empty() {
47 return Err(CommonError::FileSystemPermissionDenied {
48 Path:PathToCheck.to_path_buf(),
49 Reason:"Empty path: caller must supply an explicit filesystem path.".to_string(),
50 });
51 }
52
53 // Tier 1: trusted system paths bypass workspace gating. See
54 // `IsTrustedSystemPath` for the complete allow-list. Scanner reads,
55 // VSIX installs, agent-plugin probes, and per-extension global-storage
56 // stats hit this path on every boot.
57 if IsTrustedSystemPath(PathToCheck) {
58 return Ok(());
59 }
60
61 if !ApplicationState.Workspace.IsTrusted.load(std::sync::atomic::Ordering::Relaxed) {
62 return Err(CommonError::FileSystemPermissionDenied {
63 Path:PathToCheck.to_path_buf(),
64 Reason:"Workspace is not trusted. File access is denied.".to_string(),
65 });
66 }
67
68 let FoldersGuard = ApplicationState
69 .Workspace
70 .WorkspaceFolders
71 .lock()
72 .map_err(super::ErrorMapping::MapApplicationStateLockErrorToCommonError)?;
73
74 if FoldersGuard.is_empty() {
75 // Allow access if no folder is open, as operations are likely on user-chosen
76 // files. A stricter model could deny this.
77 return Ok(());
78 }
79
80 // Use canonical paths on both sides so that prefix-matching survives
81 // macOS's `/Volumes/<vol>/...` vs `/private/var/...` resolution and
82 // any symlinked submodule roots. Cocoon's URI strip yields the user-
83 // visible path (`/Volumes/<vol>/.../Land/Dependency/...`) while the
84 // workspace folder URL stays as built from `from_directory_path` -
85 // these can disagree on platforms where the resolved canonical path
86 // differs from the URI-derived one (encoded mount-point indirection,
87 // case-insensitive HFS+, etc.). Without this, a workspace with deep
88 // submodule trees rejects every read that walks past the first level
89 // even though the path is a literal descendant of the open folder.
90 let CanonicalPathToCheck =
91 crate::Cache::PathCanon::Canonicalize::Fn(PathToCheck).unwrap_or_else(|_| PathToCheck.to_path_buf());
92
93 let IsAllowed = FoldersGuard.iter().any(|Folder| {
94 let FolderPath = match Folder.URI.to_file_path() {
95 Ok(P) => P,
96 Err(_) => return false,
97 };
98 let CanonicalFolderPath =
99 crate::Cache::PathCanon::Canonicalize::Fn(&FolderPath).unwrap_or_else(|_| FolderPath.clone());
100 // Try both canonical-canonical AND raw-raw - either match wins.
101 PathToCheck.starts_with(&FolderPath)
102 || PathToCheck.starts_with(&CanonicalFolderPath)
103 || CanonicalPathToCheck.starts_with(&FolderPath)
104 || CanonicalPathToCheck.starts_with(&CanonicalFolderPath)
105 });
106
107 if IsAllowed {
108 Ok(())
109 } else {
110 // Surface the comparison details so a workspace-mismatch bug
111 // (URL-to-path conversion, canonicalisation drift) is debuggable
112 // without rebuilding. Tag is `vfs` so it appears under the
113 // default `short` trace set.
114 let FolderPaths:Vec<String> = FoldersGuard
115 .iter()
116 .map(|F| {
117 F.URI
118 .to_file_path()
119 .map(|P| P.display().to_string())
120 .unwrap_or_else(|_| format!("<bad-uri:{}>", F.URI))
121 })
122 .collect();
123
124 dev_log!(
125 "vfs",
126 "[PathSecurity] reject path={} canonical={} folders=[{}]",
127 PathToCheck.display(),
128 CanonicalPathToCheck.display(),
129 FolderPaths.join(", ")
130 );
131
132 Err(CommonError::FileSystemPermissionDenied {
133 Path:PathToCheck.to_path_buf(),
134 Reason:"Path is outside of the registered workspace folders.".to_string(),
135 })
136 }
137}
138
139/// Return `true` when `PathToCheck` falls under a directory that Land itself
140/// manages and the sandbox should not gate.
141///
142/// Covered roots:
143///
144/// - `${Lodge}` (explicit override, if set).
145/// - `$HOME/.land/**` - the canonical namespace for user-installed extensions,
146/// agent plugins, global storage, and any other Land-owned state that lives
147/// outside the VS Code-style profile tree.
148/// - The Mountain executable's own `extensions/`, `../Resources/extensions/`
149/// and `../Resources/app/extensions/` neighbours - built-in extension roots
150/// that ship inside the `.app` bundle.
151/// - `$APPDATA`-equivalents: Tauri's resolved app-data / app-config / app-local
152/// directories (via `$XDG_DATA_HOME`, `$XDG_CONFIG_HOME` if set; on macOS the
153/// `Library/Application Support/land.editor.*` tree).
154/// - `${TMPDIR}` + `/tmp`, `/private/tmp`, `/var/tmp` - scratch dirs language
155/// servers write their port-handoff / socket / lock files to. `TMPDIR` on
156/// macOS points at `/var/folders/.../T/` but extensions hardcode
157/// `/tmp/<tool>` directly.
158/// - Third-party tool state under `$HOME/{.gitkraken,.gk,.copilot,
159/// .config/git}` - probed by GitLens, copilot-chat, etc. Application state,
160/// not user content.
161///
162/// Anything outside this list still flows through the workspace-folder
163/// check. The set is intentionally narrow: it unblocks Land's *own*
164/// bookkeeping reads + cooperating neighbour-tool probes without
165/// handing extensions an unbounded filesystem.
166fn IsTrustedSystemPath(PathToCheck:&Path) -> bool {
167 // Canonicalising is best-effort - when the path doesn't exist yet
168 // (e.g. first-boot probes for `globalStorage/<extension>/state.json`)
169 // `canonicalize` returns Err and we compare against the raw path.
170 let Candidate =
171 crate::Cache::PathCanon::Canonicalize::Fn(PathToCheck).unwrap_or_else(|_| PathToCheck.to_path_buf());
172
173 if let Ok(Override) = std::env::var("Lodge") {
174 if !Override.is_empty() {
175 let OverridePath = PathBuf::from(&Override);
176 if Candidate.starts_with(&OverridePath) || PathToCheck.starts_with(&OverridePath) {
177 return true;
178 }
179 }
180 }
181
182 if let Ok(Home) = std::env::var("HOME") {
183 let LandRoot = PathBuf::from(&Home).join(".land");
184 if Candidate.starts_with(&LandRoot) || PathToCheck.starts_with(&LandRoot) {
185 return true;
186 }
187
188 // macOS / Linux Application-Support trees that host Land's per-profile
189 // state. `land.editor.*` prefix matches every build profile variant.
190 let MacAppSupport = PathBuf::from(&Home).join("Library/Application Support");
191 if (Candidate.starts_with(&MacAppSupport) || PathToCheck.starts_with(&MacAppSupport))
192 && ContainsLandEditorSegment(PathToCheck)
193 {
194 return true;
195 }
196
197 let XdgConfig = std::env::var("XDG_CONFIG_HOME")
198 .map(PathBuf::from)
199 .unwrap_or_else(|_| PathBuf::from(&Home).join(".config"));
200 if (Candidate.starts_with(&XdgConfig) || PathToCheck.starts_with(&XdgConfig))
201 && ContainsLandEditorSegment(PathToCheck)
202 {
203 return true;
204 }
205
206 let XdgData = std::env::var("XDG_DATA_HOME")
207 .map(PathBuf::from)
208 .unwrap_or_else(|_| PathBuf::from(&Home).join(".local/share"));
209 if (Candidate.starts_with(&XdgData) || PathToCheck.starts_with(&XdgData))
210 && ContainsLandEditorSegment(PathToCheck)
211 {
212 return true;
213 }
214 }
215
216 if let Ok(Exe) = std::env::current_exe() {
217 if let Some(ExeParent) = Exe.parent() {
218 let BundleRoots = [
219 ExeParent.join("extensions"),
220 ExeParent.join("../Resources/extensions"),
221 ExeParent.join("../Resources/app/extensions"),
222 // Sky's Static/Application/extensions root is reached via
223 // `../../../Sky/Target/Static/Application/extensions` in the
224 // debug profile - match the canonical `Sky/Target/Static/Application/extensions`
225 // segment regardless of how many `..` hops the scan path used.
226 ];
227 for Root in BundleRoots {
228 let Normalised = crate::Cache::PathCanon::Canonicalize::Fn(&Root).unwrap_or(Root.clone());
229 if Candidate.starts_with(&Normalised) || PathToCheck.starts_with(&Root) {
230 return true;
231 }
232 }
233 }
234 }
235
236 // Sky / Dependency bundled extension trees. These are debug-profile
237 // layouts where the scanner reaches the bundle root via relative hops
238 // from the Mountain executable directory - canonicalising already
239 // resolves that, but we also fall back to a path-segment match so a
240 // missing file (first-boot probe) still clears the check.
241 if ContainsPathSegments(PathToCheck, &["Sky", "Target", "Static", "Application", "extensions"])
242 || ContainsPathSegments(PathToCheck, &["Dependency", "Microsoft", "Dependency", "Editor", "extensions"])
243 {
244 return true;
245 }
246
247 // Sky's Target tree as a whole is build output Land controls (product.json,
248 // nls bundles, package.json, workbench bundle artifacts). gitlens reads
249 // `Sky/Target/product.json` to detect the host product; the workbench reads
250 // its own bundled metadata. None of these are user content - allowing the
251 // whole `Sky/Target/` subtree mirrors the bundled-extension carve-out
252 // above and keeps third-party probes from getting "outside workspace"
253 // rejections for files Land itself shipped.
254 if ContainsPathSegments(PathToCheck, &["Sky", "Target"])
255 || ContainsPathSegments(PathToCheck, &["Output", "Target"])
256 || ContainsPathSegments(PathToCheck, &["Dependency", "Microsoft", "Dependency", "Editor", "out"])
257 || ContainsPathSegments(
258 PathToCheck,
259 &["Dependency", "Microsoft", "Dependency", "Editor", "product.json"],
260 ) {
261 return true;
262 }
263
264 if let Ok(TempDir) = std::env::var("TMPDIR") {
265 let TempPath = PathBuf::from(&TempDir);
266 if !TempPath.as_os_str().is_empty() && (Candidate.starts_with(&TempPath) || PathToCheck.starts_with(&TempPath))
267 {
268 return true;
269 }
270 }
271
272 // Platform-conventional scratch roots that don't show up in `TMPDIR`
273 // on macOS/Linux. Language servers (ruby-lsp, solargraph, jdtls,
274 // pyright, …) write port-handoff / reporter / socket files under
275 // `/tmp/<tool>/` as a matter of course. `/var/folders/.../T/` IS
276 // covered by `TMPDIR` on macOS, but `/tmp` and `/private/tmp` are
277 // the ones extensions actually target. Guarding these under the
278 // system-trust tier is safe: extensions run inside Cocoon's Node
279 // host, which already has unconstrained process-level filesystem
280 // access - the sandbox only gates IPC round-trips through Mountain,
281 // not the extension's own `fs.writeFileSync`.
282 for Root in ["/tmp", "/private/tmp", "/var/tmp"] {
283 let RootPath = PathBuf::from(Root);
284 if Candidate.starts_with(&RootPath) || PathToCheck.starts_with(&RootPath) {
285 return true;
286 }
287 }
288
289 // Third-party tool state directories extensions commonly probe.
290 // GitLens stats `~/.gitkraken/workspaces/workspaces.json` to offer a
291 // "Open in GitKraken" menu; copilot-chat stats `~/.copilot/` for
292 // cached completions. These live outside Land's namespace but are
293 // not user-content either - they're application state from another
294 // tool, safe to read/stat.
295 if let Ok(Home) = std::env::var("HOME") {
296 for Suffix in [".gitkraken", ".gk", ".copilot", ".config/git"] {
297 let ToolRoot = PathBuf::from(&Home).join(Suffix);
298 if Candidate.starts_with(&ToolRoot) || PathToCheck.starts_with(&ToolRoot) {
299 return true;
300 }
301 }
302 }
303
304 // Read-only POSIX OS-info files. Many extensions (csharp, ruby-lsp,
305 // rust-analyzer, debug adapters, telemetry SDKs) probe these to
306 // branch on distro / kernel for spawning the correct binary. They
307 // are world-readable system files - the workspace-folder check
308 // rejects them as "outside workspace" but there's no plausible
309 // abuse vector. Match by full equality to keep the carve-out tight.
310 for SystemFile in [
311 "/etc/os-release",
312 "/etc/lsb-release",
313 "/etc/system-release",
314 "/etc/redhat-release",
315 "/etc/SuSE-release",
316 "/etc/debian_version",
317 "/etc/alpine-release",
318 "/etc/machine-id",
319 "/etc/timezone",
320 "/etc/localtime",
321 "/proc/version",
322 "/proc/cpuinfo",
323 "/proc/meminfo",
324 "/proc/self/status",
325 "/proc/self/cgroup",
326 ] {
327 let SysPath = PathBuf::from(SystemFile);
328 if Candidate == SysPath || PathToCheck == SysPath {
329 return true;
330 }
331 }
332
333 false
334}
335
336/// True when `path` contains a directory segment whose name starts with
337/// `land.editor.`. Used to tighten the Application-Support / XDG checks so
338/// we only trust directories that Land itself provisioned, not every file
339/// under `$HOME/Library/Application Support`.
340fn ContainsLandEditorSegment(path:&Path) -> bool {
341 path.components().any(|Component| {
342 Component
343 .as_os_str()
344 .to_str()
345 .map(|Name| Name.starts_with("land.editor."))
346 .unwrap_or(false)
347 })
348}
349
350/// True when every element of `segments` appears in order as consecutive
351/// path components of `path`. Used to match Sky / Dependency extension
352/// roots regardless of which relative-path prefix the scanner used.
353fn ContainsPathSegments(path:&Path, segments:&[&str]) -> bool {
354 let Names:Vec<&str> = path.components().filter_map(|C| C.as_os_str().to_str()).collect();
355 if segments.is_empty() || Names.len() < segments.len() {
356 return false;
357 }
358 Names
359 .windows(segments.len())
360 .any(|Window| Window.iter().zip(segments.iter()).all(|(A, B)| A == B))
361}