Skip to content

fix(harness): prevent skill staging path traversal - #3314

Merged
juruoO-o merged 7 commits into
agentscope-ai:mainfrom
25344xiaoning:fix/3313-skill-staging-path-traversal
Nov 11, 2026
Merged

juruoO-o merged 7 commits into
agentscope-ai:mainfrom
25344xiaoning:fix/3313-skill-staging-path-traversal

Conversation

@25344xiaoning

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.0.4-SNAPSHOT (based on main at 857e3e6)

Description

Fixes #3313.

MarketplaceStager previously used unchecked skill names and source namespaces to construct staging directories. An absolute-path name could redirect resource writes and stale-file cleanup outside the cache. Relative traversal could also redirect cleanup even when resource writing was blocked.

This change validates both path components before any per-skill filesystem mutation.

Implementation

  • Normalize the workspace root before resolving cache paths.
  • Require skill names and source namespaces to resolve to direct child directories.
  • Reject path separators, drive/stream syntax, traversal aliases, and names ending in a dot or space.
  • Handle invalid paths through the existing per-skill failure handling, returning StageResult.NONE while continuing to stage valid entries.
  • Preserve supported names containing uppercase letters, internal spaces, underscores, and dots.
  • Update API Javadoc and the English and Chinese skill documentation.

Validation remains local to the staging boundary. This patch addresses path-name traversal; it does not introduce symlink-safe filesystem operations.

Tests

Added 31 regression cases covering:

  • Absolute-path writes, overwrites, and cleanup outside the cache.
  • Relative traversal and normalized path aliases.
  • Unsafe source namespaces, including repository-source fallback.
  • Unsafe names loaded from actual SKILL.md frontmatter.
  • Continued staging of valid skills after an invalid entry.
  • Normal resource staging, binary resources, stale-file cleanup, and default namespaces.

Verification

Executed on Windows with OpenJDK 21:

mvn -B -ntp -pl agentscope-harness -am verify "-Dtest=MarketplaceStagerPathTest,MarketplaceStagerExecBitTest,MarketplaceStagerOrphanGcTest,SharedWorkspaceSkillStagingE2ETest,SkillRuntimeTest,SandboxLifecycleMiddlewareCallbackTest" "-Djacoco.append=false"
  • Focused suite: 79 tests, zero failures or errors; one POSIX-permission test skipped on Windows.
  • All 31 new regression cases passed.
  • Changed executable lines: 16/16 covered.
  • New resolver branches: 11/12 covered locally; Windows rejects trailing spaces during path parsing before the explicit guard.
  • Spotless formatting and checks passed.
  • Javadoc generation passed.
  • Documentation validation passed: 411 pages and 479 redirects.
  • git diff --check passed.

The full repository test suite was not run locally.

Checklist

  • 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
  • Code is ready for review

Validate skill names and source namespaces before creating staging
paths so resource writes and stale-file cleanup cannot be redirected
by absolute paths or traversal components. Normalize the workspace
root and keep invalid entries isolated through StageResult.NONE.

Add regression coverage for filesystem effects, frontmatter loading,
namespace fallback, and valid staging behavior. Document the staging
name requirements in the API and both skill guides.

Fixes agentscope-ai#3313
@codecov

codecov Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@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

Hardens MarketplaceStager against path-traversal via unvalidated skill names / source namespaces: the staging root is normalized, and both path components must resolve to a single direct child directory before any materialisation or stale-file cleanup runs. The direction is right and the regression suite is unusually thorough (absolute-path writes, traversal aliases, frontmatter-sourced names, cleanup isolation) — thanks for covering the cleanup side and not just the write side, that is where the interesting damage was.

Two things I'd like answered before this is approved:

  1. Namespace validation rejects the default getSource() of two repositories shipped in this repo. GitSkillRepository.buildDefaultSource() returns e.g. git-test/repo (slash kept deliberately, asserted by its own test) and ClasspathSkillRepository.buildDefaultSource() returns classpath-agentscope/skills for a nested resource path. resolveSourceNamespaces() forwards those verbatim, so with this guard every skill from those repositories falls into the IllegalArgumentException branch → StageResult.NONE → no shell-mode <files-root>, plus a log.warn per skill per stage() call (staging runs on every agent call). Net effect: a traversal fix that silently disables marketplace staging for git/classpath sources.
  2. The pre-existing nested ns layout was itself a hazard (garbageCollectOrphans() walks exactly two levels, so for ns = "git-owner/repo" it inspects <scope>/git-owner as the skill dir and can deleteRecursively() a live subtree once it looks stale). So "single directory name" is the right invariant to enforce — the question is only how to get there without breaking those sources.

Suggested resolution for both: treat the namespace the way scopeSegment(scope) already treats the scope — sanitize to [A-Za-z0-9._-] and, when the sanitisation is lossy, append a short digest of the original so the mapping stays injective. That keeps git/classpath marketplace skills staging, guarantees the two-level layout the GC depends on, and leaves the strict rejection in place for skill names (which are attacker-influenced through SKILL.md frontmatter and should not be silently rewritten). If rejecting instead of mapping is the intended product decision, then the git/classpath default sources need to change in the same PR, with a test driving stage() with getSource() = "git-owner/repo".

Findings

  • [Warning] MarketplaceStager.java:247 — namespace rejection breaks GitSkillRepository / ClasspathSkillRepository default sources (git-owner/repo), degrades them to StageResult.NONE, and produces per-call WARN noise.
  • [Warning] MarketplaceStagerPathTest.java:152 — nested/source is asserted invalid, but that is the shape of a shipped default source; needs a stage()-level decision test.
  • [Info] MarketplaceStager.java:268 — Win32 reserved device names (CON, NUL, COM1…) still pass the component check and only fail later inside Files.createDirectories; symlinked staging dirs remain out of scope (as the PR body states) — worth a follow-up issue for a NOFOLLOW_LINKS probe.

CI (build ubuntu/windows, validate, Check License, Check Module Sync) is green and the CLA is signed. Not requesting changes on the security intent itself — just on the namespace blast radius.


Automated review by github-manager-bot

Path stagedDir = scopeRoot.resolve(ns).resolve(name);
try {
// Validate both components before materialisation: cleanup also trusts this root.
Path namespaceDir = resolveStagingDirectory(scopeRoot, ns);

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.

[Warning] Rejecting any namespace containing / silently disables staging for two repositories that ship in this repo and legitimately produce slash-containing sources:

  • GitSkillRepository.buildDefaultSource() keeps the slash on purpose (// forward slash (/) is kept as it's valid in source identifiers (owner/repo format)) and its own test asserts getSource() == git-test/repo.
  • ClasspathSkillRepository.buildDefaultSource() returns classpath-<parent>/<child> for a nested resource path (e.g. resource path io/agentscope/skills → classpath-agentscope/skills).

resolveSourceNamespaces() passes those strings through unchanged, so after this change every skill from such a repository hits the IllegalArgumentException path, returns StageResult.NONE, and loses its shell-mode <files-root> — with a fresh log.warn per skill on every stage() call (staging runs per agent call, so that is sustained WARN noise).

Suggested direction: keep the strict rejection for name (attacker-influenced via SKILL.md frontmatter), but map the namespace into one safe segment the same way scopeSegment(scope) already does (sanitize + length/format check + digest suffix for injectivity). That preserves staging for git/classpath sources and still guarantees the two-level <scope>/<ns>/<skill> layout the orphan GC assumes — which is the invariant actually worth protecting here (a nested ns makes garbageCollectOrphans() see <parent-of-ns> as the skill dir and deleteRecursively() a live staging dir). Happy to see it handled either way; just need the git/classpath impact answered before this merges.

}

@ParameterizedTest
@ValueSource(strings = {".", "..", "../other", "..\\other", "nested/source", "C:relative"})

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.

[Warning] nested/source is encoded here as invalid, but it is exactly what GitSkillRepository.getSource() returns by default (git-owner/repo). If the namespace contract is really "single directory name", the default sources of the shipped git/classpath repositories need to be sanitised at their side (or by resolveSourceNamespaces) and this case needs a positive test; otherwise this PR turns a path-shape hardening into a functional regression for marketplace skills. Could you add a test that drives stage() with a getSource() of git-owner/repo and assert the outcome you intend?

Path resolved = parent.resolve(name).normalize();
// Check both separator styles and drive syntax even on Unix, since the cache may be
// projected onto another filesystem. Windows also aliases trailing dots and spaces.
if (!parent.equals(resolved.getParent())

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.

[Info] Two non-blocking gaps in the component check, both already close to the Windows intent of this guard:

  1. Win32 reserved device names (CON, PRN, NUL, COM1..COM9, LPT1..LPT9, and their dotted/:-suffixed forms) pass this check and only fail later inside Files.createDirectories — the outcome is still StageResult.NONE, but on windows-latest that means one exception per call rather than one clean rejection here. An explicit reserved-name test would make the intent readable.
  2. The containment check is lexical, so a pre-existing symlink at <scopeRoot>/<ns>/<name> (anything that can write the workspace) still redirects writes. The PR body already scopes this out — suggesting a follow-up issue (NOFOLLOW_LINKS probe on the resolved dir before materialising) instead of expanding this diff.

The scopeRoot normalisation itself looks right: making retained and Files.list(scopeRoot) agree on the same absolute-normalized shape is what the GC white-list needs, and safeNamesPreserveResourcesAndCleanup pins it.

@25344xiaoning

Copy link
Copy Markdown
Contributor Author

Good. Your reply explains the namespace mapping fix, links the commit and PR, and notes the validation results. The PR should now await the administrator’s re-review and CI checks.

@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

The follow-up on 60d78edf resolves everything from the last round: source namespaces are now mapped to a single safe, injective segment via sourceNamespaceSegment() (so git-owner/repo and classpath-agentscope/skills keep staging instead of degrading to StageResult.NONE), the two-level layout garbageCollectOrphans() depends on is guaranteed, and there is now a stage()-level test driving a shipped slash source plus an injectivity test for lossy mappings. Skill names keep the strict reject-don't-rewrite behaviour, which is the right asymmetry given they come from SKILL.md frontmatter. Good fix.

Remaining notes are non-blocking: the duplicated segment-mapping policy (drift risk), the undocumented on-disk cache layout shift for existing installs, and the carried-over Win32 reserved-name gap.

Findings

  • [Warning] MarketplaceStager.java:225 — sourceNamespaceSegment duplicates scopeSegment with subtly different alias/trailing-space rules; extract one shared helper.
  • [Warning] MarketplaceStager.java:606 — namespace mapping moves the cache subtree (git-test/repo/… → git-test_repo-<digest>/…); the legacy subtree is now unreachable by the two-level orphan GC and persisted filesRoot paths break across the upgrade. Document or clean up once.
  • [Info] MarketplaceStager.java:301 — bare Win32 device names (CON, NUL, COM1…) still pass the component check; an explicit guard + test row would be cheaper than the late createDirectories failure.

CI at this commit: validate, Check License, Check Module Sync and build (ubuntu-latest) pass. build (windows-latest) fails in service-dataplane (ToolConfirmationCoordinatorTest.nonOwnerPersistsDecisionButOwnerPollerAloneReleasesContinuation) — a module this PR does not touch, so it looks like pre-existing Windows flakiness rather than a regression from these changes; worth a re-run to confirm. CLA is signed, no changes requested.


Automated review by github-manager-bot

* as {@code owner/repository}; rejecting those values would silently disable staging. A digest
* suffix preserves injectivity whenever sanitisation changes the identifier.
*/
private static String sourceNamespaceSegment(String namespace) {

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.

[Warning] sourceNamespaceSegment is a near-copy of scopeSegment (same sanitise → lossless-check → prefix-<digest> shape) with two subtle divergences: this one excludes ./.. and adds a endsWith(" ") guard, while scopeSegment excludes SHARED_SCOPE and only guards endsWith("."). Two overlapping segment policies in one file drift easily — the next caller will pick whichever one it found first. Consider one shared helper, e.g. safeSegment(String raw, int maxLen, Set<String> reservedAliases, boolean rejectTrailingSpace), used by scope, namespace and (as a pure validator) the skill-name path.

int total = count.getOrDefault(src, 1);
if (total == 1) {
ns.put(repo, src);
ns.put(repo, sourceNamespaceSegment(src));

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.

[Warning] Mapping namespaces at resolveSourceNamespaces changes the on-disk layout for existing installations: git-test/repo used to stage to .skills-cache/<scope>/git-test/repo/<name>/, now it is .skills-cache/<scope>/git-test_repo-<digest>/<name>/. Two consequences worth a line in the PR description: (1) the old git-test/ subtree is invisible to garbageCollectOrphans(), which walks exactly two levels, so those directories are never reclaimed (bounded, but permanent cache litter after upgrade); (2) any filesRoot path persisted across the upgrade — previously rendered skill prompts, session transcripts the model quotes back — points at a directory that no longer exists. A one-time removal of the legacy nested subtree (or a documented note that cache is advisory and self-heals on next stage) would close this out.

Path resolved = parent.resolve(name).normalize();
// Check both separator styles and drive syntax even on Unix, since the cache may be
// projected onto another filesystem. Windows also aliases trailing dots and spaces.
if (!parent.equals(resolved.getParent())

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.

[Info] Non-blocking, carried over from the previous round: bare Win32 device names (CON, PRN, NUL, COM1..COM9, LPT1..LPT9) still pass this guard — the : check only catches the CON:1 form — so they fail later inside Files.createDirectories, which on windows-latest means one exception per skill per call instead of a clean rejection here. An explicit reserved-name check plus one @ParameterizedTest row would make the intent self-documenting. Symlinked staging dirs remain explicitly out of scope per the PR body — a LinkOption.NOFOLLOW_LINKS probe would be a good follow-up issue.

@25344xiaoning

Copy link
Copy Markdown
Contributor Author

Thank you for your correction. I have optimized it

@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

Security fix for skill staging path traversal in MarketplaceStager. Re-review at 7c1a7fb: all three findings from the previous round are resolved — the duplicated segment policy is now one shared helper, the Win32 reserved-name gap is closed, and the legacy nested cache subtree is both documented and reachable by orphan GC. The staging path check is fail-closed for absolute paths, traversal aliases, separators and drive/stream syntax, and the regression tests drive the shipped stage() entry point. Approved; CLA signed.

Findings

  • [Info] one non-blocking hardening note, inline — symlink / real-path escape is not covered by normalize() + parent equality. It is explicitly out of this PR's scope; please track it as a follow-up.

CI

build (windows-latest) fails in service-dataplane (ToolConfirmationCoordinatorTest), a module this PR does not touch — it looks like pre-existing Windows flakiness rather than a regression from these changes; a re-run would confirm.


Automated review by github-manager-bot

}

/** Resolves one directory component without allowing aliases of its parent or siblings. */
private static Path resolveStagingDirectory(Path parent, String name) {

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 new resolveStagingDirectory check is logical (Path.normalize() + parent equality) and does not resolve symlinks or real paths. A pre-existing symlink under .skills-cache (or a symlinked workspace root) could still redirect staging writes or orphan cleanup outside the intended tree. The PR description already excludes symlink-safe filesystem operations from scope, so this is acceptable for now, but it should be tracked as a follow-up hardening item.

Add staging tests for duplicate sources and blank explicit namespaces. Reuse the namespace mapper fallback instead of repeating it in stageAll.

Refs agentscope-ai#3313

@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

Re-review at 65f6b32b. The only product-code delta since the approved 7c1a7fb5 is the removal of the now-redundant blank-namespace fallback in stageAll() — correct, because sourceNamespaceSegment() already maps null/blank to GLOBAL_NAMESPACE, and keeping both would have made the default namespace reachable through two different code paths. The rest of the commit adds the stage()-level coverage for namespace fallbacks and collisions that the earlier rounds asked for. No new issues; all findings from the previous two rounds stay resolved.

CI

Full green at 65f6b32b — validate, Check License, Check Module Sync, build (ubuntu-latest) and build (windows-latest) (the Windows flake that blocked the previous round now passes), CLA signed.

Carried-over non-blocking follow-up, still worth an issue: symlink/real-path escape at the staging boundary is outside what normalize() + parent equality can cover.


Automated review by github-manager-bot

@jujn jujn added the P0 重要紧急 label Nov 4, 2026
Resolve docs conflicts by keeping main's per-call (PreCall) staging wording
and NONE-for-inline-only paragraph alongside this PR's <scope> cache layout
and grace-period orphan GC notes.

Adapt MarketplaceStagerPathTest to main's construction-time skill name
validation (agentscope-ai#3787): unsafe names now reach the stager only through custom
repositories, so tests supply them via mocks; the frontmatter test asserts
load-time rejection plus the stager's independent rejection.
@mintlify

mintlify Bot commented Nov 11, 2026

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 48a2108.

Approve preview

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ 25344xiaoning
❌ ”zhuzhiyu.zzy“


”zhuzhiyu.zzy“ seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@juruoO-o

Copy link
Copy Markdown
Collaborator

recheck

@juruoO-o
juruoO-o merged commit 9cdaa81 into agentscope-ai:main Nov 11, 2026
8 of 9 checks passed
chickenlj pushed a commit that referenced this pull request Nov 13, 2026
Backport the verified fix to the 2.0.x implementation and retain its existing public contracts where the upstream kernel differs.

(cherry picked from commit 9cdaa81)
Backport-review-patch: e0e0245f993b1e4394a1587cfa9cd39d78a12333
Constraint: No AgentScope Service or SDK migration
Confidence: high
Not-tested: Whole-repository verification pending after lane integration
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]: MarketplaceStager allows skill names to escape the staging cache

5 participants