gadk_platform/safe_subpath.rs
1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! [`safe_subpath`]: the containment check for a relative path read from an untrusted config,
17//! with its two error kinds ([`ERR_NOT_VALID_RELATIVE_PATH`],
18//! [`ERR_SYMLINK_IN_RELATIVE_PATH`]) and [`is_link_like`].
19//!
20// Unix path semantics only, as in the other path helpers (`go_path_clean`, `go_filepath_rel`,
21// `go_filepath_is_local`); the Windows rules (forbidden characters, trailing dot/space,
22// drives, UNC prefixes, reserved device names, junctions) are not implemented.
23
24use std::fmt;
25use std::io;
26use std::path::{Path, PathBuf};
27
28use crate::go_err::go_errno_text;
29use crate::go_fmt::go_quote;
30use crate::go_path::{
31 go_filepath_is_local, go_filepath_rel, go_path_clean, go_path_dir, go_path_join,
32};
33
34/// Text of the error for a reference that, read as a string, is not a relative path below the
35/// base directory.
36pub const ERR_NOT_VALID_RELATIVE_PATH: &str =
37 "path is not a relative path inside the base directory";
38
39/// Text of the error for a link on the way that leads outside the base directory. A link that
40/// stays inside is not an error.
41pub const ERR_SYMLINK_IN_RELATIVE_PATH: &str =
42 "path leads outside the base directory through a link";
43
44/// Which kind of failure a [`SafeSubpathError`] reports.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46#[non_exhaustive]
47pub enum SafeSubpathErrorKind {
48 /// The reference is not a relative path below the base ([`ERR_NOT_VALID_RELATIVE_PATH`]).
49 NotValidRelativePath,
50 /// A link on the way leads outside the base ([`ERR_SYMLINK_IN_RELATIVE_PATH`]).
51 SymlinkInRelativePath,
52 /// Neither sentinel: a base that is not absolute, or a filesystem error while following
53 /// links (`cannot resolve links: lstat …`, `too many links in …`).
54 Other,
55}
56
57/// An error of [`safe_subpath`]: its [`kind`](Self::kind) and full error text.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct SafeSubpathError {
60 kind: SafeSubpathErrorKind,
61 message: String,
62}
63
64impl SafeSubpathError {
65 fn not_valid(detail: &str) -> Self {
66 Self {
67 kind: SafeSubpathErrorKind::NotValidRelativePath,
68 message: format!("{ERR_NOT_VALID_RELATIVE_PATH}: {detail}"),
69 }
70 }
71
72 fn symlink(detail: &str) -> Self {
73 Self {
74 kind: SafeSubpathErrorKind::SymlinkInRelativePath,
75 message: format!("{ERR_SYMLINK_IN_RELATIVE_PATH}: {detail}"),
76 }
77 }
78
79 fn other(message: String) -> Self {
80 Self {
81 kind: SafeSubpathErrorKind::Other,
82 message,
83 }
84 }
85
86 /// Which kind of failure this error reports.
87 pub fn kind(&self) -> SafeSubpathErrorKind {
88 self.kind
89 }
90
91 /// True for [`SafeSubpathErrorKind::NotValidRelativePath`].
92 pub fn is_not_valid_relative_path(&self) -> bool {
93 self.kind == SafeSubpathErrorKind::NotValidRelativePath
94 }
95
96 /// True for [`SafeSubpathErrorKind::SymlinkInRelativePath`].
97 pub fn is_symlink_in_relative_path(&self) -> bool {
98 self.kind == SafeSubpathErrorKind::SymlinkInRelativePath
99 }
100}
101
102impl fmt::Display for SafeSubpathError {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 f.write_str(&self.message)
105 }
106}
107
108impl std::error::Error for SafeSubpathError {}
109
110/// Resolves `rel` below `base` and checks that the result stays inside it.
111/// stays inside it.
112///
113/// `base` must be absolute and is trusted; `rel` is not. On success the result is the
114/// absolute path the check followed `rel` to, every link on the way replaced by its target,
115/// and the base-relative spelling of `rel`. A caller that opens the returned path opens the
116/// file the check judged.
117///
118/// [`SafeSubpathErrorKind::NotValidRelativePath`] iff `rel` is not a local path below `base`
119/// (absolute, empty, escaping through `..`, effectively empty, or carrying a NUL byte).
120/// [`SafeSubpathErrorKind::SymlinkInRelativePath`] iff following the links on the way lands
121/// outside `base`, itself followed the same way. A link that lands inside is accepted (which
122/// keeps Kubernetes ConfigMap and Secret mounts working); a link whose target does not exist
123/// is judged by where it points. A component that does not exist, or that sits below a
124/// non-directory, is not an error: the path is returned and the caller's read reports it.
125pub fn safe_subpath(base: &Path, rel: &str) -> Result<(PathBuf, String), SafeSubpathError> {
126 // Validation order: base, empty, NUL, locality, containment, then links.
127 let base = base.to_string_lossy();
128 if !base.starts_with('/') {
129 return Err(SafeSubpathError::other(
130 "base path is not absolute".to_owned(),
131 ));
132 }
133 let abs_base = go_path_clean(&base);
134
135 if rel.is_empty() {
136 return Err(SafeSubpathError::not_valid("rel path is empty"));
137 }
138 // NUL char is not allowed both on linux and windows
139 if rel.contains('\0') {
140 return Err(SafeSubpathError::not_valid("rel path contains null byte"));
141 }
142 // IsLocal settles absolute paths and any ".." that escapes.
143 if !go_filepath_is_local(rel) {
144 return Err(SafeSubpathError::not_valid("rel path is not local"));
145 }
146
147 // check if rel stays below absBase. Rel + IsLocal, not a string prefix: the prefix
148 // absBase+separator is wrong for a filesystem root ("//").
149 let res = go_path_join(&[abs_base.as_str(), rel]);
150 let r = go_filepath_rel(&abs_base, &res)
151 .map_err(|e| SafeSubpathError::not_valid(&format!("filepath.Rel failed: {e}")))?;
152 if r == "." {
153 // rel is effectively empty
154 return Err(SafeSubpathError::not_valid("rel is effectively empty"));
155 }
156 if !go_filepath_is_local(&r) {
157 return Err(SafeSubpathError::not_valid("not a subpath"));
158 }
159
160 let real = resolve_inside(&abs_base, &res)?;
161 Ok((PathBuf::from(real), r))
162}
163
164/// Follows the links in `target` and reports where it really lands;
165/// [`ERR_SYMLINK_IN_RELATIVE_PATH`] when that is not below `base`, itself followed the same
166/// way so a base reached through a link is trusted.
167fn resolve_inside(base: &str, target: &str) -> Result<String, SafeSubpathError> {
168 // Resolve both paths through their links, then compare them.
169 let real_base = follow_links(base)
170 .map_err(|e| SafeSubpathError::other(format!("cannot resolve links in base: {e}")))?;
171 let real_target = follow_links(target)
172 .map_err(|e| SafeSubpathError::other(format!("cannot resolve links: {e}")))?;
173 match go_filepath_rel(&real_base, &real_target) {
174 Ok(rel) if rel == "." || go_filepath_is_local(&rel) => Ok(real_target),
175 _ => Err(SafeSubpathError::symlink(&format!(
176 "it resolves to {}",
177 go_quote(&real_target)
178 ))),
179 }
180}
181
182/// The number of links followed on one path before giving up, so a link loop is an error
183/// rather than a hang.
184const MAX_LINK_FOLLOWS: usize = 255;
185
186/// Walks the absolute path `p` one component at a time and replaces every
187/// link by its target, splicing the target in uncleaned so a `..` in it applies to whatever
188/// the walk has reached (in `s/../y.yaml`, what `s` points at). A link whose target does not
189/// exist is still followed by name; a component that does not exist, or sits below a
190/// non-directory, is walked past as a plain name (a later `..` can climb back into a
191/// directory that exists, and the components after it are still examined).
192fn follow_links(p: &str) -> Result<String, String> {
193 // Components are consumed left to right; a link target is spliced in front of the rest.
194 let mut cur = "/".to_owned();
195 let mut rest: Vec<String> = p.trim_matches('/').split('/').map(str::to_owned).collect();
196 let mut follows = 0usize;
197 let mut i = 0usize;
198 while i < rest.len() {
199 let c = rest[i].clone();
200 match c.as_str() {
201 "" | "." => {
202 i += 1;
203 continue;
204 }
205 ".." => {
206 cur = go_path_dir(&cur);
207 i += 1;
208 continue;
209 }
210 _ => {}
211 }
212 let next = go_path_join(&[cur.as_str(), c.as_str()]);
213 let meta = match std::fs::symlink_metadata(&next) {
214 Ok(meta) => meta,
215 Err(e)
216 if matches!(
217 e.kind(),
218 io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
219 ) =>
220 {
221 // Not a link, so nothing to follow; keep walking by name.
222 cur = next;
223 i += 1;
224 continue;
225 }
226 Err(e) => return Err(format!("lstat {next}: {}", go_errno_text(&e))),
227 };
228 if !is_link_like(&meta.file_type()) {
229 cur = next;
230 i += 1;
231 continue;
232 }
233 let dest = match std::fs::read_link(&next) {
234 Ok(dest) => dest.to_string_lossy().into_owned(),
235 Err(_) => {
236 // A reparse point that names no target redirects the read nowhere, so it is
237 // an ordinary entry here.
238 cur = next;
239 i += 1;
240 continue;
241 }
242 };
243 follows += 1;
244 if follows > MAX_LINK_FOLLOWS {
245 return Err(format!("too many links in {}", go_quote(p)));
246 }
247 // Continue the walk from the target's components, then whatever followed the link.
248 // The target is not cleaned: a ".." in it is applied by the walk, after the component
249 // before it has been followed. A relative target is read from the directory the link
250 // sits in, which is cur.
251 if dest.starts_with('/') {
252 cur = "/".to_owned();
253 }
254 let mut spliced: Vec<String> = dest
255 .trim_matches('/')
256 .split('/')
257 .map(str::to_owned)
258 .collect();
259 spliced.extend(rest.drain(i + 1..));
260 rest = spliced;
261 i = 0;
262 }
263 Ok(go_path_clean(&cur))
264}
265
266/// Whether a directory entry may redirect a read somewhere other than where its own name sits
267/// in the tree. On Unix that is a symbolic link.
268pub fn is_link_like(file_type: &std::fs::FileType) -> bool {
269 // Only symbolic links redirect a read on Unix.
270 file_type.is_symlink()
271}