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 let IsAllowed = FoldersGuard.iter().any(|Folder| {
93 let FolderPath = match Folder.URI.to_file_path() {
94 Ok(P) => P,
95 Err(_) => return false,
96 };
97 let CanonicalFolderPath =
98 crate::Cache::PathCanon::Canonicalize::Fn(&FolderPath).unwrap_or_else(|_| FolderPath.clone());
99 // Try both canonical-canonical AND raw-raw - either match wins.
100 PathToCheck.starts_with(&FolderPath)
101 || PathToCheck.starts_with(&CanonicalFolderPath)
102 || CanonicalPathToCheck.starts_with(&FolderPath)
103 || CanonicalPathToCheck.starts_with(&CanonicalFolderPath)
104 });
105
106 if IsAllowed {
107 Ok(())
108 } else {
109 // Surface the comparison details so a workspace-mismatch bug
110 // (URL-to-path conversion, canonicalisation drift) is debuggable
111 // without rebuilding. Tag is `vfs` so it appears under the
112 // default `short` trace set.
113 let FolderPaths:Vec<String> = FoldersGuard
114 .iter()
115 .map(|F| {
116 F.URI
117 .to_file_path()
118 .map(|P| P.display().to_string())
119 .unwrap_or_else(|_| format!("<bad-uri:{}>", F.URI))
120 })
121 .collect();
122 dev_log!(
123 "vfs",
124 "[PathSecurity] reject path={} canonical={} folders=[{}]",
125 PathToCheck.display(),
126 CanonicalPathToCheck.display(),
127 FolderPaths.join(", ")
128 );
129 Err(CommonError::FileSystemPermissionDenied {
130 Path:PathToCheck.to_path_buf(),
131 Reason:"Path is outside of the registered workspace folders.".to_string(),
132 })
133 }
134}
135
136/// Return `true` when `PathToCheck` falls under a directory that Land itself
137/// manages and the sandbox should not gate.
138///
139/// Covered roots:
140///
141/// - `${Lodge}` (explicit override, if set).
142/// - `$HOME/.land/**` - the canonical namespace for user-installed extensions,
143/// agent plugins, global storage, and any other Land-owned state that lives
144/// outside the VS Code-style profile tree.
145/// - The Mountain executable's own `extensions/`, `../Resources/extensions/`
146/// and `../Resources/app/extensions/` neighbours - built-in extension roots
147/// that ship inside the `.app` bundle.
148/// - `$APPDATA`-equivalents: Tauri's resolved app-data / app-config / app-local
149/// directories (via `$XDG_DATA_HOME`, `$XDG_CONFIG_HOME` if set; on macOS the
150/// `Library/Application Support/land.editor.*` tree).
151/// - `${TMPDIR}` + `/tmp`, `/private/tmp`, `/var/tmp` - scratch dirs language
152/// servers write their port-handoff / socket / lock files to. `TMPDIR` on
153/// macOS points at `/var/folders/.../T/` but extensions hardcode
154/// `/tmp/<tool>` directly.
155/// - Third-party tool state under `$HOME/{.gitkraken,.gk,.copilot,
156/// .config/git}` - probed by GitLens, copilot-chat, etc. Application state,
157/// not user content.
158///
159/// Anything outside this list still flows through the workspace-folder
160/// check. The set is intentionally narrow: it unblocks Land's *own*
161/// bookkeeping reads + cooperating neighbour-tool probes without
162/// handing extensions an unbounded filesystem.
163fn IsTrustedSystemPath(PathToCheck:&Path) -> bool {
164 // Canonicalising is best-effort - when the path doesn't exist yet
165 // (e.g. first-boot probes for `globalStorage/<extension>/state.json`)
166 // `canonicalize` returns Err and we compare against the raw path.
167 let Candidate =
168 crate::Cache::PathCanon::Canonicalize::Fn(PathToCheck).unwrap_or_else(|_| PathToCheck.to_path_buf());
169
170 if let Ok(Override) = std::env::var("Lodge") {
171 if !Override.is_empty() {
172 let OverridePath = PathBuf::from(&Override);
173 if Candidate.starts_with(&OverridePath) || PathToCheck.starts_with(&OverridePath) {
174 return true;
175 }
176 }
177 }
178
179 if let Ok(Home) = std::env::var("HOME") {
180 let LandRoot = PathBuf::from(&Home).join(".land");
181 if Candidate.starts_with(&LandRoot) || PathToCheck.starts_with(&LandRoot) {
182 return true;
183 }
184
185 // macOS / Linux Application-Support trees that host Land's per-profile
186 // state. `land.editor.*` prefix matches every build profile variant.
187 let MacAppSupport = PathBuf::from(&Home).join("Library/Application Support");
188 if (Candidate.starts_with(&MacAppSupport) || PathToCheck.starts_with(&MacAppSupport))
189 && ContainsLandEditorSegment(PathToCheck)
190 {
191 return true;
192 }
193
194 let XdgConfig = std::env::var("XDG_CONFIG_HOME")
195 .map(PathBuf::from)
196 .unwrap_or_else(|_| PathBuf::from(&Home).join(".config"));
197 if (Candidate.starts_with(&XdgConfig) || PathToCheck.starts_with(&XdgConfig))
198 && ContainsLandEditorSegment(PathToCheck)
199 {
200 return true;
201 }
202
203 let XdgData = std::env::var("XDG_DATA_HOME")
204 .map(PathBuf::from)
205 .unwrap_or_else(|_| PathBuf::from(&Home).join(".local/share"));
206 if (Candidate.starts_with(&XdgData) || PathToCheck.starts_with(&XdgData))
207 && ContainsLandEditorSegment(PathToCheck)
208 {
209 return true;
210 }
211 }
212
213 if let Ok(Exe) = std::env::current_exe() {
214 if let Some(ExeParent) = Exe.parent() {
215 let BundleRoots = [
216 ExeParent.join("extensions"),
217 ExeParent.join("../Resources/extensions"),
218 ExeParent.join("../Resources/app/extensions"),
219 // Sky's Static/Application/extensions root is reached via
220 // `../../../Sky/Target/Static/Application/extensions` in the
221 // debug profile - match the canonical `Sky/Target/Static/Application/extensions`
222 // segment regardless of how many `..` hops the scan path used.
223 ];
224 for Root in BundleRoots {
225 let Normalised = crate::Cache::PathCanon::Canonicalize::Fn(&Root).unwrap_or(Root.clone());
226 if Candidate.starts_with(&Normalised) || PathToCheck.starts_with(&Root) {
227 return true;
228 }
229 }
230 }
231 }
232
233 // Sky / Dependency bundled extension trees. These are debug-profile
234 // layouts where the scanner reaches the bundle root via relative hops
235 // from the Mountain executable directory - canonicalising already
236 // resolves that, but we also fall back to a path-segment match so a
237 // missing file (first-boot probe) still clears the check.
238 if ContainsPathSegments(PathToCheck, &["Sky", "Target", "Static", "Application", "extensions"])
239 || ContainsPathSegments(PathToCheck, &["Dependency", "Microsoft", "Dependency", "Editor", "extensions"])
240 {
241 return true;
242 }
243
244 // Sky's Target tree as a whole is build output Land controls (product.json,
245 // nls bundles, package.json, workbench bundle artifacts). gitlens reads
246 // `Sky/Target/product.json` to detect the host product; the workbench reads
247 // its own bundled metadata. None of these are user content - allowing the
248 // whole `Sky/Target/` subtree mirrors the bundled-extension carve-out
249 // above and keeps third-party probes from getting "outside workspace"
250 // rejections for files Land itself shipped.
251 if ContainsPathSegments(PathToCheck, &["Sky", "Target"])
252 || ContainsPathSegments(PathToCheck, &["Output", "Target"])
253 || ContainsPathSegments(PathToCheck, &["Dependency", "Microsoft", "Dependency", "Editor", "out"])
254 || ContainsPathSegments(
255 PathToCheck,
256 &["Dependency", "Microsoft", "Dependency", "Editor", "product.json"],
257 ) {
258 return true;
259 }
260
261 if let Ok(TempDir) = std::env::var("TMPDIR") {
262 let TempPath = PathBuf::from(&TempDir);
263 if !TempPath.as_os_str().is_empty() && (Candidate.starts_with(&TempPath) || PathToCheck.starts_with(&TempPath))
264 {
265 return true;
266 }
267 }
268
269 // Platform-conventional scratch roots that don't show up in `TMPDIR`
270 // on macOS/Linux. Language servers (ruby-lsp, solargraph, jdtls,
271 // pyright, …) write port-handoff / reporter / socket files under
272 // `/tmp/<tool>/` as a matter of course. `/var/folders/.../T/` IS
273 // covered by `TMPDIR` on macOS, but `/tmp` and `/private/tmp` are
274 // the ones extensions actually target. Guarding these under the
275 // system-trust tier is safe: extensions run inside Cocoon's Node
276 // host, which already has unconstrained process-level filesystem
277 // access - the sandbox only gates IPC round-trips through Mountain,
278 // not the extension's own `fs.writeFileSync`.
279 for Root in ["/tmp", "/private/tmp", "/var/tmp"] {
280 let RootPath = PathBuf::from(Root);
281 if Candidate.starts_with(&RootPath) || PathToCheck.starts_with(&RootPath) {
282 return true;
283 }
284 }
285
286 // Third-party tool state directories extensions commonly probe.
287 // GitLens stats `~/.gitkraken/workspaces/workspaces.json` to offer a
288 // "Open in GitKraken" menu; copilot-chat stats `~/.copilot/` for
289 // cached completions. These live outside Land's namespace but are
290 // not user-content either - they're application state from another
291 // tool, safe to read/stat.
292 if let Ok(Home) = std::env::var("HOME") {
293 for Suffix in [".gitkraken", ".gk", ".copilot", ".config/git"] {
294 let ToolRoot = PathBuf::from(&Home).join(Suffix);
295 if Candidate.starts_with(&ToolRoot) || PathToCheck.starts_with(&ToolRoot) {
296 return true;
297 }
298 }
299 }
300
301 // Read-only POSIX OS-info files. Many extensions (csharp, ruby-lsp,
302 // rust-analyzer, debug adapters, telemetry SDKs) probe these to
303 // branch on distro / kernel for spawning the correct binary. They
304 // are world-readable system files - the workspace-folder check
305 // rejects them as "outside workspace" but there's no plausible
306 // abuse vector. Match by full equality to keep the carve-out tight.
307 for SystemFile in [
308 "/etc/os-release",
309 "/etc/lsb-release",
310 "/etc/system-release",
311 "/etc/redhat-release",
312 "/etc/SuSE-release",
313 "/etc/debian_version",
314 "/etc/alpine-release",
315 "/etc/machine-id",
316 "/etc/timezone",
317 "/etc/localtime",
318 "/proc/version",
319 "/proc/cpuinfo",
320 "/proc/meminfo",
321 "/proc/self/status",
322 "/proc/self/cgroup",
323 ] {
324 let SysPath = PathBuf::from(SystemFile);
325 if Candidate == SysPath || PathToCheck == SysPath {
326 return true;
327 }
328 }
329
330 false
331}
332
333/// True when `path` contains a directory segment whose name starts with
334/// `land.editor.`. Used to tighten the Application-Support / XDG checks so
335/// we only trust directories that Land itself provisioned, not every file
336/// under `$HOME/Library/Application Support`.
337fn ContainsLandEditorSegment(path:&Path) -> bool {
338 path.components().any(|Component| {
339 Component
340 .as_os_str()
341 .to_str()
342 .map(|Name| Name.starts_with("land.editor."))
343 .unwrap_or(false)
344 })
345}
346
347/// True when every element of `segments` appears in order as consecutive
348/// path components of `path`. Used to match Sky / Dependency extension
349/// roots regardless of which relative-path prefix the scanner used.
350fn ContainsPathSegments(path:&Path, segments:&[&str]) -> bool {
351 let Names:Vec<&str> = path.components().filter_map(|C| C.as_os_str().to_str()).collect();
352 if segments.is_empty() || Names.len() < segments.len() {
353 return false;
354 }
355 Names
356 .windows(segments.len())
357 .any(|Window| Window.iter().zip(segments.iter()).all(|(A, B)| A == B))
358}