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).map_err(|e| {
151 SafeSubpathError::not_valid(&format!("failed to compute relative path: {e}"))
152 })?;
153 if r == "." {
154 // rel is effectively empty
155 return Err(SafeSubpathError::not_valid("rel is effectively empty"));
156 }
157 if !go_filepath_is_local(&r) {
158 return Err(SafeSubpathError::not_valid("not a subpath"));
159 }
160
161 let real = resolve_inside(&abs_base, &res)?;
162 Ok((PathBuf::from(real), r))
163}
164
165/// Follows the links in `target` and reports where it really lands;
166/// [`ERR_SYMLINK_IN_RELATIVE_PATH`] when that is not below `base`, itself followed the same
167/// way so a base reached through a link is trusted.
168fn resolve_inside(base: &str, target: &str) -> Result<String, SafeSubpathError> {
169 // Resolve both paths through their links, then compare them.
170 let real_base = follow_links(base)
171 .map_err(|e| SafeSubpathError::other(format!("cannot resolve links in base: {e}")))?;
172 let real_target = follow_links(target)
173 .map_err(|e| SafeSubpathError::other(format!("cannot resolve links: {e}")))?;
174 match go_filepath_rel(&real_base, &real_target) {
175 Ok(rel) if rel == "." || go_filepath_is_local(&rel) => Ok(real_target),
176 _ => Err(SafeSubpathError::symlink(&format!(
177 "it resolves to {}",
178 go_quote(&real_target)
179 ))),
180 }
181}
182
183/// The number of links followed on one path before giving up, so a link loop is an error
184/// rather than a hang.
185const MAX_LINK_FOLLOWS: usize = 255;
186
187/// Walks the absolute path `p` one component at a time and replaces every
188/// link by its target, splicing the target in uncleaned so a `..` in it applies to whatever
189/// the walk has reached (in `s/../y.yaml`, what `s` points at). A link whose target does not
190/// exist is still followed by name; a component that does not exist, or sits below a
191/// non-directory, is walked past as a plain name (a later `..` can climb back into a
192/// directory that exists, and the components after it are still examined).
193fn follow_links(p: &str) -> Result<String, String> {
194 // Components are consumed left to right; a link target is spliced in front of the rest.
195 let mut cur = "/".to_owned();
196 let mut rest: Vec<String> = p.trim_matches('/').split('/').map(str::to_owned).collect();
197 let mut follows = 0usize;
198 let mut i = 0usize;
199 while i < rest.len() {
200 let c = rest[i].clone();
201 match c.as_str() {
202 "" | "." => {
203 i += 1;
204 continue;
205 }
206 ".." => {
207 cur = go_path_dir(&cur);
208 i += 1;
209 continue;
210 }
211 _ => {}
212 }
213 let next = go_path_join(&[cur.as_str(), c.as_str()]);
214 let meta = match std::fs::symlink_metadata(&next) {
215 Ok(meta) => meta,
216 Err(e)
217 if matches!(
218 e.kind(),
219 io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
220 ) =>
221 {
222 // Not a link, so nothing to follow; keep walking by name.
223 cur = next;
224 i += 1;
225 continue;
226 }
227 Err(e) => return Err(format!("lstat {next}: {}", go_errno_text(&e))),
228 };
229 if !is_link_like(&meta.file_type()) {
230 cur = next;
231 i += 1;
232 continue;
233 }
234 let dest = match std::fs::read_link(&next) {
235 Ok(dest) => dest.to_string_lossy().into_owned(),
236 Err(_) => {
237 // A reparse point that names no target redirects the read nowhere, so it is
238 // an ordinary entry here.
239 cur = next;
240 i += 1;
241 continue;
242 }
243 };
244 follows += 1;
245 if follows > MAX_LINK_FOLLOWS {
246 return Err(format!("too many links in {}", go_quote(p)));
247 }
248 // Continue the walk from the target's components, then whatever followed the link.
249 // The target is not cleaned: a ".." in it is applied by the walk, after the component
250 // before it has been followed. A relative target is read from the directory the link
251 // sits in, which is cur.
252 if dest.starts_with('/') {
253 cur = "/".to_owned();
254 }
255 let mut spliced: Vec<String> = dest
256 .trim_matches('/')
257 .split('/')
258 .map(str::to_owned)
259 .collect();
260 spliced.extend(rest.drain(i + 1..));
261 rest = spliced;
262 i = 0;
263 }
264 Ok(go_path_clean(&cur))
265}
266
267/// Whether a directory entry may redirect a read somewhere other than where its own name sits
268/// in the tree. On Unix that is a symbolic link.
269pub fn is_link_like(file_type: &std::fs::FileType) -> bool {
270 // Only symbolic links redirect a read on Unix.
271 file_type.is_symlink()
272}