Skip to content

The agent that grows with you

fix(files): a doubly encoded file URL names the file in the folder its label shows

emozilla797999de0197
diff --git a/apps/shared/src/file-url.test.ts b/apps/shared/src/file-url.test.ts
index 0869a08c06e..e36be3c4236 100644
--- a/apps/shared/src/file-url.test.ts
+++ b/apps/shared/src/file-url.test.ts
@@ -50,6 +50,30 @@ describe('fileUrlToNativePath', () => {
expect(fileUrlToNativePath(url)).toBeNull()
})
+ // A reader that decodes the path once more (the gateway does, for a path missing as written)
+ // must not find another folder in it: a separator or a dot-segment still encoded after decoding
+ // is refused like an encoded one.
+ it.each([
+ 'file:///srv/project/..%252f..%252fetc/passwd',
+ 'file:///srv/project/..%252F..%252Fetc/passwd',
+ 'file:///srv/project/%252e%252e/etc/passwd',
+ 'file:///srv/project/%252E%252E%252Fetc/passwd',
+ 'file:///srv/project/%252e/report.html',
+ 'file:///C:/work/..%255c..%255cWindows/win.ini',
+ 'file:///C:/work/%252e%252e/Windows/win.ini',
+ 'file://server/share/%252e%252e/secret.txt'
+ ])('refuses %s, whose decoded path still encodes a separator or a dot-segment', url => {
+ expect(fileUrlToNativePath(url)).toBeNull()
+ })
+
+ it.each([
+ ['file:///srv/100%2525.txt', '/srv/100%25.txt'],
+ ['file:///srv/a%252eb.txt', '/srv/a%2eb.txt'],
+ ['file:///srv/name%255Cdraft.html', '/srv/name%5Cdraft.html']
+ ])('keeps a POSIX name that only spells a percent sequence: %s', (url, path) => {
+ expect(fileUrlToNativePath(url)).toBe(path)
+ })
+
it.each(['file:///tmp/100%.txt', 'file:///tmp/%E0%A4%A.txt', 'file://%invalid/clip.mp4', 'not a url', '', 'file'])(
'refuses malformed input %j',
value => {
diff --git a/apps/shared/src/file-url.ts b/apps/shared/src/file-url.ts
index 8f04d850849..449ce5395df 100644
--- a/apps/shared/src/file-url.ts
+++ b/apps/shared/src/file-url.ts
@@ -9,6 +9,23 @@
// tests the decoded path too, so `/C%3A/...` is a drive path.
const DRIVE_PATH_RE = /^\/[a-z]:/i
+// A decoded segment that one more decode turns into `.` or `..`.
+const ENCODED_DOT_SEGMENT_RE = /^(?:\.|%2e){1,2}$/i
+
+/**
+ * Whether the decoded path still encodes a separator (`%2f`; `%5c` too in a
+ * Windows path) or a dot-segment. A reader that decodes it again, as the
+ * gateway does for a path that is missing as written, would find another
+ * folder in it than the one the URL names.
+ */
+function encodesAnotherPath(path: string, windows: boolean): boolean {
+ if (/%2f/i.test(path) || (windows && /%5c/i.test(path))) {
+ return true
+ }
+
+ return path.split(windows ? /[\\/]/ : '/').some(segment => ENCODED_DOT_SEGMENT_RE.test(segment))
+}
+
/**
* The native path a `file:` URL names, read the way Node's `fileURLToPath`
* reads it on the OS the URL itself implies: a UNC host or a drive letter can
@@ -21,7 +38,8 @@ const DRIVE_PATH_RE = /^\/[a-z]:/i
*
* Null when the value is not a parseable `file:` URL, does not percent-decode,
* or encodes a separator: `%2f` anywhere, `%5c` in a Windows path (a POSIX
- * name may hold a literal backslash).
+ * name may hold a literal backslash). The same goes for a separator or a
+ * dot-segment that is still encoded after decoding (`..%252f`).
*/
export function fileUrlToNativePath(value: string): null | string {
try {
@@ -33,8 +51,13 @@ export function fileUrlToNativePath(value: string): null | string {
}
const path = decodeURIComponent(pathname)
+ const windows = Boolean(hostname) || DRIVE_PATH_RE.test(path)
+
+ if (encodesAnotherPath(path, windows)) {
+ return null
+ }
- if (!hostname && !DRIVE_PATH_RE.test(path)) {
+ if (!windows) {
return path
}
diff --git a/hermes_cli/web_server_files.py b/hermes_cli/web_server_files.py
index 52e45d1a53c..ac8e3010060 100644
--- a/hermes_cli/web_server_files.py
+++ b/hermes_cli/web_server_files.py
@@ -4,6 +4,7 @@
import logging
import mimetypes
import os
+import re
import stat
import urllib.request
from contextlib import contextmanager
@@ -35,6 +36,22 @@ def _resolve_fs_candidate(raw: str, *, cwd: str | None = None) -> Path:
return candidate.resolve(strict=False)
+def _decoded_candidate(raw: str, *, cwd: str | None = None) -> Path | None:
+ """``raw`` percent-decoded once and resolved, or None when decoding adds a dot-segment.
+
+ The decode rescues a name that arrived encoded twice (issue #103425). A ``.`` or ``..`` it
+ produces (``..%2f``, ``%2e%2e/``) would move the lookup out of the folder the caller named."""
+ decoded = urllib.parse.unquote(raw)
+ separators = r"[\\/]" if os.name == "nt" else "/"
+
+ def dot_segments(path: str) -> int:
+ return sum(segment in (".", "..") for segment in re.split(separators, path))
+
+ if dot_segments(decoded) > dot_segments(raw):
+ return None
+ return _resolve_fs_candidate(decoded, cwd=cwd)
+
+
def _fs_path(raw_path: str, *, cwd: str | None = None, decode_fallback: bool = True) -> Path:
raw = str(raw_path or "").strip()
if not raw:
@@ -42,7 +59,8 @@ def _fs_path(raw_path: str, *, cwd: str | None = None, decode_fallback: bool = T
if "\0" in raw:
raise HTTPException(status_code=400, detail="Invalid path")
try:
- if raw.lower().startswith("file:"):
+ from_url = raw.lower().startswith("file:")
+ if from_url:
parsed = urllib.parse.urlparse(raw)
uri_path = parsed.path
if parsed.netloc and parsed.netloc.lower() != "localhost":
@@ -60,10 +78,11 @@ def _fs_path(raw_path: str, *, cwd: str | None = None, decode_fallback: bool = T
# decoding, so a non-ASCII name can arrive as a literal "%E5%8D%8A..."
# string that stats as missing (issue #103425). The verbatim path wins
# whenever it exists, so filenames that genuinely contain "%XX" keep
- # resolving as-is; the unquoted form only rescues the lookup.
- if decode_fallback and "%" in raw and not candidate.exists():
- decoded = _resolve_fs_candidate(urllib.parse.unquote(raw), cwd=cwd)
- if decoded.exists():
+ # resolving as-is; the unquoted form only rescues the lookup. A file: URL
+ # was decoded once above, and a second decode would read ..%252f as ../.
+ if decode_fallback and not from_url and "%" in raw and not candidate.exists():
+ decoded = _decoded_candidate(raw, cwd=cwd)
+ if decoded is not None and decoded.exists():
candidate = decoded
return candidate
except (OSError, RuntimeError, ValueError):
diff --git a/tests/hermes_cli/test_web_server_fs.py b/tests/hermes_cli/test_web_server_fs.py
index 5aa60f8493c..dc5028e241b 100644
--- a/tests/hermes_cli/test_web_server_fs.py
+++ b/tests/hermes_cli/test_web_server_fs.py
@@ -411,6 +411,35 @@ def test_fs_read_text_keeps_literal_percent_filename_verbatim(client, tmp_path):
assert response.json()["text"] == "literal percent name"
[email protected]("name", ["..%252fsecret.md", "%252e%252e%252fsecret.md", "..%255csecret.md"])
+def test_fs_read_text_decodes_a_file_url_once(client, tmp_path, name):
+ """A ``file:`` URL is percent-decoded once. ``..%252f`` is then the name ``..%2f`` inside the
+ folder the URL names, which does not exist; a second decode would turn it into ``../`` and read
+ a file outside that folder."""
+ folder = tmp_path / "docs"
+ folder.mkdir()
+ (tmp_path / "secret.md").write_text("outside the named folder")
+
+ response = client.get("/api/fs/read-text", params={"path": f"{folder.as_uri()}/{name}"})
+
+ assert response.status_code == 404
+ assert "outside the named folder" not in response.text
+
+
[email protected]("name", ["..%2fsecret.md", "%2e%2e/secret.md", "%2E%2E%2Fsecret.md"])
+def test_fs_read_text_decode_fallback_stays_in_the_named_folder(client, tmp_path, name):
+ """The one-decode rescue for a doubly encoded path (issue #103425) never leaves the folder the
+ path names: when decoding would add a ``..`` segment, the path is read as written."""
+ folder = tmp_path / "docs"
+ folder.mkdir()
+ (tmp_path / "secret.md").write_text("outside the named folder")
+
+ response = client.get("/api/fs/read-text", params={"path": f"{folder}/{name}"})
+
+ assert response.status_code == 404
+ assert "outside the named folder" not in response.text
+
+
def test_fs_write_text_never_decodes_percent_path(client, tmp_path):
sibling = tmp_path / "report v2.md"
sibling.write_text("existing")