Skip to content

fix(harness): sanitize session ids used in workspace file names - #2952

Open
wylovelyi wants to merge 1 commit into
agentscope-ai:mainfrom
wylovelyi:fix/2937-sanitize-session-id-path
Open

wylovelyi wants to merge 1 commit into
agentscope-ai:mainfrom
wylovelyi:fix/2937-sanitize-session-id-path

Conversation

@wylovelyi

Copy link
Copy Markdown

AgentScope-Java Version

2.0.3-SNAPSHOT (current main)

Description

Closes #2937.

Background. RuntimeContext.sessionId is caller-supplied and carries no documented
character constraint, yet WorkspaceManager uses it verbatim to build file names
(agents/{agentId}/sessions/{sessionId}.jsonl, agents/{agentId}/tasks/{sessionId}.json).
A namespaced id such as agent:abc-123:main:main-9f3c is perfectly legal as an identifier,
but the colon is reserved by Windows/NTFS, so path construction fails on Windows with a bare
InvalidPathException thrown from deep inside the workspace layer — with no hint that the
caller-supplied id is the problem.

Reproduced locally on Windows 11 / JDK 17:

java.nio.file.InvalidPathException: Illegal char <:> at index 5: agent:abc-123:main:main-9f3c.json

Change. Reserved characters are replaced with - in the file-name segment rather than
rejected, so existing ids keep working unchanged on every platform:

  • new UNSAFE_SEGMENT_CHARS pattern [<>:"/\\|?*] plus a small safeSegment(String) helper
  • applied at the four places where sessionId becomes part of a file name:
    resolveSessionFile, resolveSessionContextFile, resolveSessionLogFile, taskRecordPath

/ and \ are included deliberately: sessionId is a single file-name segment here, so either
one would otherwise be read as a directory separator and silently write outside the session
directory. This follows the same approach as the already-merged #1031 and #2921, which stripped
Windows-reserved characters from skill source paths.

No on-disk data changes shape. Writes (SessionTranscriptWriter) and reads
(SessionSearchTool) both go through these same helpers, so the sanitized name is symmetric —
there is no way to write a transcript that can no longer be found. Ids that work today contain
no reserved character and are returned unchanged; ids that do contain one could not produce a
file on Windows in the first place, since they threw before any file was created.

Scope is kept to sessionId, as the issue describes. agentId reaches path construction the
same way and would benefit from the same treatment — happy to extend this PR if you would
prefer the two handled together.

How to test. WorkspaceManagerPathSafetyTest gains two cases, both platform-independent
(they assert the replacement behaviour rather than relying on a Windows-only crash):

  • sessionFileNamesReplaceWindowsReservedCharacters — the #2937 id shape plus every reserved
    character and both separators
  • sessionFileNamesLeaveOrdinaryIdsUnchanged — regression guard: an ordinary id is untouched
mvn -pl agentscope-harness test -Dtest=WorkspaceManagerPathSafetyTest

Verified locally on Windows 11 / JDK 17.0.18 / Maven 3.9.4:
mvn -pl agentscope-harness spotless:check passes, and the full harness suite
(mvn -pl agentscope-harness test) is green — 895 tests, 0 failures, 0 errors.

Checklist

Please check the following items before code is ready to be reviewed.

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

@CLAassistant

CLAassistant commented Sep 3, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Sep 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...cope/harness/agent/workspace/WorkspaceManager.java 87.50% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@Buktal Buktal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

静默替换有点隐式了, a:b 和 a-b 本来是两个不同的 sessionId,统一把保留字符换成 - 容易有 ID 冲突或者覆盖文件的风险

交给应用层来规避处理应该更合适一些

@oss-maintainer

Copy link
Copy Markdown
Collaborator

CLA Not Signed

The Contributor License Agreement (CLA) check is currently pending on this PR (license/cla: Contributor License Agreement is not signed yet.). This PR cannot be merged until the CLA is signed.

@wylovelyi please sign the CLA via the CLA assistant badge in the comment above, or visit https://cla-assistant.io/agentscope-ai/agentscope-java. Once signed, the license/cla status will turn green.


Automated check by github-manager-bot

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

This PR replaces selected Windows-reserved characters in session-derived local filenames and adds path-name assertions. I verified the affected session and task persistence paths, but the lossy replacement aliases distinct session IDs and can mix their transcripts and task records; the raw ID also remains in the filesystem mirror path, and Windows control characters are still unhandled. These correctness and session-isolation issues need resolution before the change is safe to merge.

The concerns above are significant enough that this would normally be a change request; noting that the CLA is also not signed yet (see the CLA reminder comment), this review is posted as a comment. Please address the session-ID aliasing and mirror-path issues, and sign the CLA, then feel free to @mention me for a re-review.


Automated review by github-manager-bot

* <p>Forward slash and backslash are included as well: an id is a single file-name segment
* here, so either would otherwise be read as a directory separator.
*/
private static final Pattern UNSAFE_SEGMENT_CHARS = Pattern.compile("[<>:\"/\\\\|?*]");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pattern omits ASCII control characters (U+0000 through U+001F), which Windows also forbids in file-name segments. A caller-supplied id such as a\u0001b is therefore unchanged and still fails when the Windows path is constructed. Include those characters in the transformation and cover them in the test.

public Path resolveSessionContextFile(RuntimeContext rc, String agentId, String sessionId) {
return getSessionDir(rc, agentId)
.resolve(sessionId + WorkspaceConstants.SESSION_CONTEXT_EXT);
.resolve(safeSegment(sessionId) + WorkspaceConstants.SESSION_CONTEXT_EXT);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only changes the local path. SessionTranscriptWriter still builds contextRelativePath from the raw session id, and SessionTree uses that override for mirror reads and uploads. With a Windows-backed LocalFilesystem, the raw colon still reaches Path.of(...); moreover the remote context key and local sanitized key now differ. Derive the mirror key from the same sanitized segment (and test a transcript write with a filesystem configured).

* hint that the caller-supplied id is the problem.
*/
private static String safeSegment(String segment) {
return segment == null ? null : UNSAFE_SEGMENT_CHARS.matcher(segment).replaceAll("-");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replacing every unsafe character with - is lossy: distinct allowed IDs such as a:b and a-b resolve to the same context, log, and task-record files. Their transcript history and task maps are then shared (or task records overwritten), while sessions.json still has separate raw-ID entries. Use a collision-free filename encoding or a persisted ID-to-filename mapping.

@wylovelyi

Copy link
Copy Markdown
Author

@jujn 你好,这个 PR 对 workspace 中使用的 session id 做 sanitize(harness 相关)。准备好 review 了,方便时帮忙看一下,谢谢!

@wylovelyi

Copy link
Copy Markdown
Author

Pushed a follow-up that fixes a session-id filename collision (P2 from the detailed review).

The bug: safeSegment collapsed every Windows/NTFS-reserved character to a single -. That made two distinct session ids sanitise to the same file name — e.g. a:b and a-b both became a-b — so one session's workspace files could silently overwrite another's (data loss / cross-session leak). The original regression tests only checked that reserved chars vanished; they never asserted two different ids keep different names.

The fix: replace the fixed - substitution with a percent-encoding of each reserved code point (%XX). This is injective, so distinct ids always keep distinct file names; it is reversible and yields only characters legal on every supported file system. % is itself included in the encoded set, so the encoding is a true injection — an id that already contains a %XX sequence cannot collide with an id whose reserved char was encoded into it. A new test distinctSessionIdsKeepDistinctFileNames locks in that a:b → a%3Ab.json and a-b → a-b.json stay different.

CC @jujn — would appreciate a review whenever convenient.

@wylovelyi
wylovelyi force-pushed the fix/2937-sanitize-session-id-path branch from 6bd38b4 to 4d49eb9 Compare October 9, 2026 02:23
@wylovelyi

Copy link
Copy Markdown
Author

The 3 commits were rebuilt (same trees, same messages, same dates — diff unchanged at +146/−4) to replace the author/committer email with the one associated with my GitHub account. The license/cla check had been stuck on pending because the old commits used a non-GitHub-associated email; it now reports success.

…ames

`sessionId` is interpolated into workspace-relative file names (`taskRecordPath` and the
deprecated `resolveSessionFile`) without any sanitization. When a gateway passes a session key
such as `agent:<id>:main` as the id, every task and session file write fails on Windows with
`InvalidPathException`, because `:` is legal in an id but not in an NTFS file name (agentscope-ai#2937).

`safeSegment` percent-encodes the NTFS reserved set, `%` itself (so the mapping stays injective:
the id `a%3Ab` cannot collide with the encoded form of `a:b`) and raw control characters. Writers
and readers go through the same helper, so a record stored under an encoded id stays readable,
and because the separators are escaped an id can no longer add a path segment or climb out of its
own directory.

Rebased onto current main: `SessionTranscriptWriter` / `SessionSearchTool` were removed by the
session-storage refactor, so only the two remaining interpolation sites in `WorkspaceManager`
need the fix.

Tests: `WorkspaceManagerPathSafetyTest` (5 tests, 0 failures), including a round-trip through
`writeTaskRecord`/`readTaskRecord`; reverting the fix turns the new test red with the original
`InvalidPathException`.

Refs agentscope-ai#2937
@wylovelyi
wylovelyi force-pushed the fix/2937-sanitize-session-id-path branch from 4d49eb9 to 92c69d4 Compare November 4, 2026 07:55
@wylovelyi

Copy link
Copy Markdown
Author

Rebased onto current main (d30a6c9) — the PR is MERGEABLE again (it had drifted ~314 commits behind and was CONFLICTING).

What changed vs. the previous push

The session-storage refactor landed in between: SessionTranscriptWriter, SessionSearchTool, resolveSessionContextFile and resolveSessionLogFile no longer exist, so the review item about the mirror key using the raw id / agents/<agentId>/sessions/<sessionId> is gone with the code. The bug from #2937 is still there, though: two interpolation sites survive in WorkspaceManager.

So the change is now limited to them:

Site Before After
taskRecordPath() (L855) TASKS_DIR + "/" + sessionId + ".json" TASKS_DIR + "/" + safeSegment(sessionId) + ".json"
resolveSessionFile() (L466, @Deprecated) resolve(sessionId + ".json") resolve(safeSegment(sessionId) + ".json")

safeSegment percent-encodes [<>:"/\|?*], raw control characters U+0000-U+001F / U+007F (the earlier push only covered the reserved set), and % itself. Escaping % is what keeps the mapping injective — without it the id a:b and the literal id a%3Ab would resolve to the same file. Writers and readers share the helper, so a record stored under an encoded id stays readable, and since the separators are escaped an id can no longer introduce a segment or climb out of its directory.

Verification (Windows 11, JDK 17, full module build)

  • mvn -pl agentscope-harness -am test -Dtest=WorkspaceManagerPathSafetyTest → Tests run: 5, Failures: 0, Errors: 0. That includes a writeTaskRecord / readTaskRecord round-trip with sessionId = "agent:abc:main", asserting the file lands as agent%3Aabc%3Amain.json and that the id is not truncated at the :.
  • spotless:check clean.
  • Red/green: reverting both call sites turns the new test red with the original InvalidPathException: Illegal char <:>; restoring it goes green. So the test is not vacuous and the assertion is Windows-specific rather than passing trivially on Linux.

One behaviour note worth a reviewer's opinion

On POSIX a pre-fix deployment could already have written agents/<id>/tasks/agent:abc:main.json; after this change the encoded name is used, so those legacy files are no longer picked up by readTaskRecord. On Windows nothing was ever written because the write threw, so only POSIX deployments are affected, and listAllTaskRecords sweeps by recentWindow. I did not add a read-side fallback to keep the change small — happy to add one if you'd rather not orphan that window.

Refs #2937

@jujn jujn added the P0 重要紧急 label Nov 4, 2026

@juruoO-o juruoO-o left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 百分号编码修复了碰撞,但改变了已有数据的读取键,需要升级兼容方案。

当前 head 已改为可区分的百分号编码,旧 review 中 a:b 与 a-b 的有损替换碰撞不再适用。仍存在的问题是:POSIX 文件系统及远端存储原本可以持久化含 ':'、'%' 的 sessionId,例如 agents/A/tasks/agent:abc.json;升级后 readTaskRecord 只按 safeSegment(sessionId) 派生出的 agent%3Aabc.json 查找,没有旧键迁移或读取策略,已有任务记录将无法按原 sessionId 找回。编码后的新写新读 round-trip 测试不能覆盖这一升级场景。

这是代码审查推断,未执行升级集成测试。请提供明确、安全的旧数据迁移方案及“旧版本写入 → 新版本按相同 sessionId 读取”的回归测试,包含 POSIX/远端存储中的 ':' 和 '%'。涉及路径分隔符时不要为兼容重新引入越界读取。

PR 描述也需要更新:目前仍称替换为 '-',并宣称无磁盘兼容变化,与当前实现不符。

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P0 重要紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Windows NTFS: session key containing ':' causes InvalidPathException in WorkspaceManager task/session file paths

6 participants