Fix: reject zip-slip entries and non-bare skill names when loading zipped skills (adk-python parity) - #312
Open
AmaadMartin wants to merge 9 commits into
Open
Fix: reject zip-slip entries and non-bare skill names when loading zipped skills (adk-python parity)#312AmaadMartin wants to merge 9 commits into
AmaadMartin wants to merge 9 commits into
Conversation
* docs: document minimum supported Node.js version in README Add a short prerequisite note under the Installation section stating that ADK for TypeScript requires Node.js 18 or newer, so new users know which Node.js runtime they need before running npm install @google/adk. The version reflects the mandated fallback: no engines.node field is declared in any package.json in the repo. * docs: reference current Node.js LTS instead of a fixed version Node.js 18 is EOL and any hard-coded minimum version goes stale over time. Reword the installation prerequisite to point readers at the current Node.js LTS releases, which stays accurate without future edits. Addresses PR review feedback on #526. --------- Co-authored-by: Amaad Martin <amaadmartin@google.com>
…#536) `ToolAuthHandler` accepted an `authCredential` and then never read it. When no auth response was present it went straight to `requestCredential()`, so a credential handed to `OpenAPIToolset`/`RestApiTool` at construction time was ignored and the tool returned `{pending: true}` on every call. For `apiKey`, `http` and `serviceAccount` schemes nothing ever resolves that request — no user interaction is involved — so the tool could never complete. Fall back to the configured credential when there is no auth response, which mirrors `_get_auth_response() or self.auth_credential` in adk-python. Also narrow what gets written to session state. The credential store exists to avoid repeating work that either cannot be repeated (an auth response is readable once) or is expensive (an exchange costs a round trip). A static credential that needed no exchange is neither, so it is no longer persisted — that would only copy the developer's secret into the session store.
…hon parity (#542) * Feat: add LoadMcpResourceTool and MCPToolset resource access Port adk-python's LoadMcpResourceTool to adk-js for cross-language parity. - Add listResources/getResourceInfo/readResource to MCPToolset, following the existing create -> try -> closeSession-in-finally session idiom. - Add LoadMcpResourceTool (mirrors the in-repo LoadArtifactsTool idiom): declares load_mcp_resource({resource_names}), and processLlmRequest injects resolved resource contents (text + base64 binary, no decode step) into the LlmRequest. - Export the tool from core/src/index.ts (@google/adk public API). * test: cover LoadMcpResourceTool and MCPToolset resource access Add full unit coverage (100% line + branch of the new code): - load_mcp_resource_tool_test.ts: init, declaration, runAsync (incl. default), list injection (incl. empty + swallowed list errors), text/binary/unknown content, base64 blob passthrough + default mime type, swallowed read errors, and all no-op guard paths (non-matching/absent function response, missing parts). - mcp_toolset_test.ts: listResources/getResourceInfo/readResource happy paths and error paths (unknown name, missing URI), plus session-cleanup assertions for success and failure (closeSession in finally, no leaked sessions). * test(e2e): exercise LoadMcpResourceTool against a real MCP server Add a no-mock end-to-end test that spawns a real MCP server over stdio (mcp_resource_server.mjs, exposing a text and a binary resource) and drives the real MCPToolset + LoadMcpResourceTool: listing/resolving/reading resources and injecting their contents (text + base64 binary) into an LlmRequest. --------- Co-authored-by: Amaad Martin <amaadmartin@google.com>
* feat(tools): add ExampleTool for few-shot examples Port adk-python's ExampleTool to adk-js. The tool accepts a static Example[] or a BaseExampleProvider and, on each outgoing LLM request, appends a few-shot <EXAMPLES> block (built via buildExampleSi from the latest user query) to the system instruction. It is never declared to the model (mirrors PreloadMemoryTool) and is a no-op when no user text is present. Exported from the public @google/adk API. * test(tools): cover ExampleTool unit and end-to-end paths Add Vitest coverage for ExampleTool: static list and provider paths, model-style passthrough, no-op branches (missing user content, empty parts, text-less first part), runAsync throwing, and the public export. Includes an end-to-end block that drives processLlmRequest through a real Context/InvocationContext (no mocks). 100% line/branch coverage of the new tool. * refactor(tools): apply simplicity audit feedback Use a constructor parameter property for `examples` (repo convention), and drop the redundant provider end-to-end test whose only unique aspect was a spy — keeping the no-mock e2e block strictly mock-free. The provider selection path stays fully covered by the unit tests; the tool retains 100% line/branch coverage. --------- Co-authored-by: Amaad Martin <amaadmartin@google.com>
* feat(agents): support clone() for RoutedAgent RoutedAgent derives its routing targets from config.agents rather than subAgents, so the inherited BaseAgent.clone() rebuilt the agent from the already-parented originals and threw "already has a parent agent". Add a RoutedAgent.clone() override that deep-clones the routing targets (via a private cloneRoutingTargets helper) and passes them through the agents override, so super.clone() rebuilds the constructor with fresh, detached copies that are re-parented onto the clone. The array-vs-record shape and record keys are preserved so the clone routes identically, and parent-override rejection plus the detached-root guarantee are still enforced by the base implementation. Remove the now-obsolete "documented limitation" test (and its unused RoutedAgent import) from base_agent_test; positive coverage lives in routed_agent_test. * test(agents): cover RoutedAgent.clone() Add a clone describe suite exercising the new override and the cloneRoutingTargets helper: array and record forms, deep-clone and re-parenting of targets, originals left untouched, functional routing on the clone (record form), verbatim agents override, non-agents overrides, and parentAgent-override rejection. Includes a no-mock end-to-end case that clones a RoutedAgent whose targets are real LlmAgents. --------- Co-authored-by: Amaad Martin <amaadmartin@google.com>
* Feat(tools): add SSRF-safe load_web_page tool for adk-python parity Ports the adk-python load_web_page tool to adk-js. Fetches a URL and returns its extracted, readable text, hardened against SSRF: - only http/https schemes are fetched - localhost-style hostnames and hosts resolving to non-global IPs (private, loopback, link-local, shared/CGNAT, reserved, multicast, IPv4-mapped IPv6) are rejected before any connection - redirects are never followed (redirect: 'manual') - a configurable timeout (default 30s) bounds every request - expected failures return the parity string "Failed to fetch url: <url>" instead of throwing Exposes loadWebPage(), the LOAD_WEB_PAGE FunctionTool, and the LoadWebPageOptions type via the @google/adk public API. * Refactor(tools): inline single-use failure prefix in load_web_page Addresses simplicity-audit feedback: the FAILURE_PREFIX constant had a single caller, so its literal is inlined into failedToFetchMessage, which remains the sole formatter of the parity failure string. --------- Co-authored-by: Amaad Martin <amaadmartin@google.com>
…n parity) (#525) * feat(tools): add EnterpriseWebSearchTool for Gemini web grounding Ports adk-python's EnterpriseWebSearchTool to adk-js, closing a cross-language parity gap. The tool is a Gemini 2+ built-in grounding source that appends {enterpriseWebSearch: {}} to the outgoing LlmRequest config; it performs no client-side execution. Mirrors the google_maps_grounding_tool idiom (extracted applyEnterpriseWebSearch function + ADK_DISABLE_GEMINI_MODEL_ID_CHECK escape hatch). Exported from the public API via common.ts. * test(tools): add unit tests for EnterpriseWebSearchTool Covers every branch of applyEnterpriseWebSearch (100% line/branch): model-unset guard, Gemini 2+ (plain + path form), config initialization, Gemini 1.x with/without other tools, non-Gemini rejection, and the ADK_DISABLE_GEMINI_MODEL_ID_CHECK escape hatch, plus the runAsync no-op and the exported singleton. Mock-free; imports via the @google/adk public entry point. --------- Co-authored-by: Amaad Martin <amaadmartin@google.com>
…loading zipped skills loadSkillFromZipBuffer read SKILL.md and the references/assets/scripts trees straight out of an attacker-authored archive with no validation of member names, and never checked that the skill name was a bare path segment. adk-python's _load_skill_from_zip_bytes has both guards, so the same archive was rejected there and accepted here. Port both guards with the error strings copied verbatim from src/google/adk/skills/_utils.py. The name guard has to run on the raw YAML mapping before schema validation, so parseSkillMdContent is split into parseFrontmatterYaml + validateFrontmatter; its own signature and error strings are unchanged.
AmaadMartin
force-pushed
the
fix/skills-zip-slip-and-name-guards
branch
from
July 30, 2026 18:11
e00bab2 to
7ef4afa
Compare
This was referenced Jul 31, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Please ensure you have read the contribution guide before creating a pull request.
Link to Issue or Description of Change
No existing issue.
Problem:
loadSkillFromZipBuffer()(core/src/skills/loader.ts) is the trust boundary for Agent Skills downloaded from a remote registry —GCPSkillRegistry.getSkill()base64-decodes an API response and hands the raw bytes straight in, so the archive is authored by whoever published the skill, not by the user running the agent. It readSKILL.mdand thereferences//assets//scripts/trees out of the archive with no validation of member names, and never checked that the skillnamewas a bare path segment. The adk-python counterpart,_load_skill_from_zip_bytesinsrc/google/adk/skills/_utils.py, has both guards, so the identical archive was rejected by adk-python and accepted by adk-js.entryNameis not sanitised on read — verified empirically against the pinnedadm-zip@0.5.17(core/package.json): a zip written with the members../evil.txt,/abs.txt,references/../../esc.txtround-trips throughnew AdmZip(buffer).getEntries()with those exact strings intact. The resource maps are keyed by relative path, soloadZipDir('references')turns a member namedreferences/../../esc.txtinto the map key../../esc.txt, which escapes for any caller that writesSkill.resourcesto disk.Solution: Port both adk-python guards into
loadSkillFromZipBuffer, with the error strings copied character-for-character.../-prefixed / containing/../Dangerous zip entry ignored: <entryName>SKILL.md(unchanged)SKILL.md not found in zipped filesystem.namemissing or falsySKILL.md frontmatter must contain 'name'namenot a string, or not a bare path segmentInvalid skill name in SKILL.md: <name>Three things worth calling out explicitly:
(a) Which strings were copied verbatim, and why one of them reads oddly. All four messages above are taken verbatim from
src/google/adk/skills/_utils.py, includingDangerous zip entry ignored:— the word "ignored" is misleading (both implementations reject the entire archive rather than skipping the entry; adk-pythonraises at_utils.py, it does not skip-and-warn), but parity on the observable string wins over nicer prose, so it is not reworded.(b) The name guard has to run before schema validation, which is why
parseSkillMdContentwas split.parseSkillMdContent()validated with zod internally and wrapped every failure asInvalid YAML in frontmatter: …, so a name of../evilnever reached a check placed after it — a guard added downstream would be unreachable dead code. It is now split into two module-private helpers mirroring the Python structure (_parse_skill_md_contentreturns an unvalidated dict;Frontmatter.model_validateruns after the name checks):parseFrontmatterYaml()returns the raw mapping,validateFrontmatter()appliesFrontmatterSchema.parseSkillMdContent's exported signature, return value and every one of its error strings are unchanged — the five existing tests asserting them are untouched and still pass. The only behavioural addition inside it isArray.isArray(parsed)in the mapping check, needed soraw['name']really is read off a mapping (it also matches Python'sisinstance(parsed, dict)); it is thrown from inside the sametry, so it still surfaces composed asInvalid YAML in frontmatter: SKILL.md frontmatter must be a YAML mapping.(c)
path.basenameneeds an explicit./..case to matchpathlib.path.basename('..') === '..'whereaspathlib.Path('..').name === '', so a naivepath.basename(name) === namecheck accepts..where adk-python rejects it.isBareSkillNamerejects.and..explicitly. There is a test pinning exactly this (casename: ..), and it fails against the naive version — see the mutation log below.Honest scope note on guard #2. I verified against the built schema that
FrontmatterSchemaalready rejects every name this guard rejects (../evil,a/b,..,.,/etc/passwd,123, missing) becauseSNAKE_OR_KEBAB_NAME_PATTERNadmits only[a-z0-9]with single-or_. So guard #2 does not change which archives are accepted today; it changes the observable error message from a 150-character zod dump prefixedInvalid YAML in frontmatter:(which blames YAML for something that is not a YAML problem) to adk-python's string. It is kept as an independent check because that regex is a naming-style rule, not a traversal defence: if it is ever relaxed (dots for versioned names, uppercase, …) the traversal property would disappear silently. Guard #1 (zip slip) is not redundant — nothing else in the file rejects a traversal member name.Breaking change: intentional and the point of the change. An archive whose
SKILL.mdnamecontains a path separator or is./..previously threwInvalid YAML in frontmatter: <zod dump>and now throwsInvalid skill name in SKILL.md: <name>. No test asserted the old string. Archives with traversal member names previously loaded and now throw. Exported API surface,loadSkillFromDir,validateSkillDir,loadAllSkillsInDirandGCPSkillRegistry's signature are all unchanged; no new exports, no dependency or lockfile changes.Collision check (run before writing any code, per pipeline policy):
gh pr list --repo AmaadMartin/adk-js --state open --limit 100returned 13 open skill-related PRs; I diffed the six that touchcore/src/skills/loader.ts(#282, #262, #239, #284, #263, #242). None implements either guard, so this is not a duplicate. Three of them overlap textually: #239 and #262 remove the redundant secondFrontmatterSchema.parse(...)inloadSkillFromZipBuffer(which disappears here too, as a consequence of callingvalidateFrontmatter(raw)directly), and #282 restructures the sametryblock inparseSkillMdContent. I branched frommainrather than stacking because those three are mutually conflicting siblings — stacking on any one of them would be arbitrary and would pull an unrelated, unreviewed change into this security fix's base. Whichever lands first, the other diffs are a small textual rebase. I deliberately leftloadSkillFile's identical double-parse alone for the same reason (it is claimed by #239/#262), and did not touchALLOWED_FRONTMATTER_KEYSorvalidateSkillDir, which other siblings are editing.Testing Plan
Please describe the tests that you ran to verify your changes. This is required for all PRs that are not small documentation or typo fixes.
Unit Tests:
[x] I have added or updated unit tests for my change.
[x] All unit tests pass locally.
12 new cases in a
describe('loadSkillFromZipBuffer', …)block incore/test/skills/loader_test.ts: benign archive loads all three resource maps; the three dangerous member names (/etc/passwd,../evil.txt,references/../../esc.txt); a dangerous member in an archive with noSKILL.md(pins that the zip-slip loop runs before theSKILL.mdlookup, matching_utils.py); the three non-bare names (../evil,a/b,..); a non-string name (123); a missing name; a YAML-sequence frontmatter; and a regression guard that a benign archive withoutSKILL.mdstill reportsSKILL.md not found in zipped filesystem..Fixture note:
AdmZip.addFile()canonicalises the name it is given ('../evil.txt'is stored as'evil.txt'), so a test written the obvious way builds a benign archive and passes for the wrong reason. The helper adds a placeholder member and reassignsentryNameafterwards, which round-trips throughtoBuffer()intact.Commands run (targeted only, no full-suite run):
Coverage: 100% line and branch coverage of the new code, measured with
--coverage.include='core/src/skills/loader.ts'and checked per-line against the coverage JSON — every uncovered line in the file is pre-existing code the change does not touch (theloadDirwalk,validateSkillDir's catch, and the deadcatcharounddata.toString('utf-8')inloadZipDir). No coverage thresholds were changed and no coverage-tool suppressions were added.Proof the tests can fail. Each new guard was mutated in
core/src/skills/loader.tsand the suite re-run; every mutation was killed:rejects the whole archive for the dangerous entry ../evil.txt: expected [Function] to throw an error; andreports the dangerous entry even when SKILL.md is absent: expected … 'Dangerous zip entry ignored: ../evil.…' but got 'SKILL.md not found in zipped filesyst…' (this one also pins the guard ordering)isBareSkillName→ naivepath.basename(name) === namerejects the non-bare skill name ..: expected … 'Invalid skill name in SKILL.md: ..' but got 'Invalid YAML in frontmatter: [\n {\n…'rejects frontmatter with no name: expected … 'SKILL.md frontmatter must contain 'n…' but got 'Invalid YAML in frontmatter: [\n {\n…'typeof skillName !== 'string'disjunctrejects a skill name that is not a string: expected … 'Invalid skill name in SKILL.md: 123' but got 'Invalid YAML in frontmatter: [\n {\n…'Array.isArray(parsed)from the mapping checkreports a YAML sequence as a non-mapping, not as a missing name: expected … 'Invalid YAML in frontmatter: SKILL.md…' but got 'SKILL.md frontmatter must contain 'n…'Manual End-to-End (E2E) Tests:
Please provide instructions on how to manually test your changes, including any necessary setup or configuration.
No credentials or network needed. From the repo root, after
npm ci && npm run build, run a scratch ESM script that imports from the public entry point:Observed output against the built package, matching adk-python's strings exactly:
Checklist
[x] I have read the CONTRIBUTING.md document.
[x] I have performed a self-review of my own code.
[x] I have commented my code, particularly in hard-to-understand areas.
[x] I have added tests that prove my fix is effective or that my feature works.
[x] New and existing unit tests pass locally with my changes.
CI note: the first
validationrun failed onrun-tests (macos-latest)withError: Test timed out in 40000msintests/integration/app_loader/app_loader_test.ts > should discover apps vs agents across directories and standalone files(2521 passed, 1 failed), which cancelled the other two matrix legs. That is the known cold-startAgentLoaderdiscovery flake already being addressed by open PRs on this fork (#260, #256, #247, #235) and is unrelated to this change — no skills test was involved. A re-run of the failed jobs passed on all three platforms:run-tests (ubuntu-latest)pass 5m27s,run-tests (macos-latest)pass 5m50s,run-tests (windows-latest)pass 8m1s.