Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(security): close two open CodeQL py/path-injection alerts on plugin-icon resolution
trohitg7700f87eaeed
diff --git a/server/nodes/_visuals.py b/server/nodes/_visuals.pyindex f3668d2e..6327e13c 100644--- a/server/nodes/_visuals.py+++ b/server/nodes/_visuals.py@@ -30,6 +30,8 @@ import jsonfrom pathlib import Pathfrom typing import Dict, Optional+from services.plugin.identifiers import is_valid_node_type+_VISUALS_PATH = Path(__file__).resolve().parent / "visuals.json"@@ -99,6 +101,8 @@ def get_plugin_meta(node_type: str, key: Optional[str] = None) -> Optional[dict"""from services.node_registry import get_node_class+ if not is_valid_node_type(node_type):+ return Nonecls = get_node_class(node_type)if cls is None:return None@@ -156,6 +160,8 @@ def get_plugin_icon_path(node_type: str, variant: str = "light") -> Optional[Pat# itself doesn't import _visuals, but plugin modules import both).from services.node_registry import get_node_class+ if not is_valid_node_type(node_type):+ return Nonecls = get_node_class(node_type)if cls is None:return Nonediff --git a/server/routers/schemas.py b/server/routers/schemas.pyindex 60dcae84..36992a95 100644--- a/server/routers/schemas.py+++ b/server/routers/schemas.py@@ -7,7 +7,7 @@ the design rationale and docs-internal/schema_source_of_truth_rfc.mdfor the frontend consumer (useNodeOutputSchemaQuery)."""-from fastapi import APIRouter, HTTPException, Query, Response+from fastapi import APIRouter, HTTPException, Path, Query, Responsefrom fastapi.responses import FileResponsefrom nodes._visuals import get_plugin_icon_path@@ -19,6 +19,7 @@ from services.node_output_schemas import (list_node_types_with_schema,)from services.node_spec import get_node_spec, list_node_groups, list_node_types_with_spec+from services.plugin.identifiers import NODE_TYPE_PATTERNrouter = APIRouter(prefix="/api/schemas", tags=["schemas"])@@ -118,7 +119,7 @@ async def get_credential_icon(provider: str):@router.get("/nodes/{node_type}/icon")async def get_node_icon(- node_type: str,+ node_type: str = Path(..., pattern=NODE_TYPE_PATTERN),variant: str = Query("light", pattern="^(light|dark)$"),):"""Return the plugin folder's co-located ``icon.svg``.diff --git a/server/services/plugin/identifiers.py b/server/services/plugin/identifiers.pynew file mode 100644index 00000000..13e8fc0e--- /dev/null+++ b/server/services/plugin/identifiers.py@@ -0,0 +1,48 @@+"""Shape validation for plugin identifiers used in URL routes + lookups.++Plugin node types (and credential provider ids) follow Python-identifier+rules: a letter or underscore followed by word characters. URL-facing+routes (``GET /api/schemas/nodes/{node_type}/icon`` etc.) and internal+helpers (``nodes._visuals.get_plugin_icon_path`` etc.) both validate+against this constraint to reject path-traversal injections at the+boundary.++Why this lives here (not inline at each callsite):++- One source of truth for the regex pattern. FastAPI consumes the raw+ pattern string via ``Path(pattern=...)``; Python code consumes the+ pre-compiled validator via :func:`is_valid_node_type`. Keeping the+ pattern in one module guarantees the route-level and function-level+ checks stay in lockstep.+- Recognised by CodeQL's ``py/path-injection`` taint analysis as a+ sanitizer — the canonical "regex fullmatch on user input" pattern+ (see https://codeql.github.com/codeql-query-help/python/py-path-injection/).+"""++from __future__ import annotations++import re+from typing import Final+++# Letter/underscore then word chars — the shape every registered+# ``BaseNode.type`` and ``Credential.id`` follows. Exposed as a raw+# string so FastAPI's ``Path(pattern=...)`` / ``Query(pattern=...)``+# can consume it directly.+NODE_TYPE_PATTERN: Final[str] = r"^[A-Za-z_][A-Za-z0-9_]*$"++_NODE_TYPE_RE: Final[re.Pattern[str]] = re.compile(NODE_TYPE_PATTERN)+++def is_valid_node_type(value: str) -> bool:+ """True if ``value`` matches :data:`NODE_TYPE_PATTERN`.++ Treats ``None`` / non-string input as invalid (defensive — the+ type hint is ``str`` but callers may forward URL params verbatim).+ """+ if not isinstance(value, str):+ return False+ return bool(_NODE_TYPE_RE.fullmatch(value))+++__all__ = ["NODE_TYPE_PATTERN", "is_valid_node_type"]diff --git a/server/tests/services/test_identifiers.py b/server/tests/services/test_identifiers.pynew file mode 100644index 00000000..ae88e21d--- /dev/null+++ b/server/tests/services/test_identifiers.py@@ -0,0 +1,122 @@+"""Unit tests for ``services.plugin.identifiers``.++Locks the contract for ``NODE_TYPE_PATTERN`` / ``is_valid_node_type``+— the input sanitizer that gates URL-facing plugin lookups+(``GET /api/schemas/nodes/{node_type}/icon`` etc.). A regression here+would re-open the ``py/path-injection`` CodeQL alerts that fixed+``server/nodes/_visuals.py:get_plugin_icon_path`` cleared.+"""++from __future__ import annotations++import re++import pytest++from services.plugin.identifiers import NODE_TYPE_PATTERN, is_valid_node_type+++# ---------------------------------------------------------------------------+# Positive cases — every shape registered ``BaseNode.type`` values take+# ---------------------------------------------------------------------------+++ "value",+ [+ # Real-world examples from the registry.+ "aiAgent",+ "openaiChatModel",+ "anthropicChatModel",+ "geminiChatModel",+ "claude_code_agent",+ "browser",+ "gmaps_create",+ "gmaps_nearby_places",+ "whatsappSend",+ "twitterReceive",+ "fileRead",+ # Edge shapes still inside the contract.+ "A",+ "_leading_underscore",+ "x1",+ "snake_case_lots_of_underscores",+ "camelCaseMixed123",+ ],+)+def test_accepts_valid_identifiers(value: str) -> None:+ assert is_valid_node_type(value) is True+++# ---------------------------------------------------------------------------+# Negative cases — every shape an attacker might try via URL injection+# ---------------------------------------------------------------------------+++ "value",+ [+ "", # empty+ "1leading_digit", # digit prefix+ "with space", # whitespace+ "with-hyphen", # hyphen (not a Python identifier char)+ "with.dot", # dot (path separator on URLs)+ "with/slash", # path separator+ "with\\backslash", # Windows separator+ "..", # parent-dir token+ "../etc/passwd", # classic traversal+ "..\\windows\\system32", # Windows traversal+ "foo\x00bar", # null byte truncation+ "foo\nbar", # newline / CRLF injection+ "foo\rbar",+ "%2e%2e%2fetc", # URL-encoded traversal+ " leading_space",+ "trailing_space ",+ "tab\there",+ "foo;bar", # command separator+ "foo|bar", # pipe+ "$VAR", # shell expansion+ "${HOME}",+ "foo'bar", # quote+ "foo\"bar",+ "foo`bar", # backtick (command substitution)+ ],+)+def test_rejects_traversal_and_injection_vectors(value: str) -> None:+ assert is_valid_node_type(value) is False+++# ---------------------------------------------------------------------------+# Defensive type-check — URL params can be ``None`` if a typed dict+# decoder hands forward a missing key.+# ---------------------------------------------------------------------------++[email protected]("value", [None, 123, b"aiAgent", ["aiAgent"], object()])+def test_rejects_non_string(value) -> None:+ assert is_valid_node_type(value) is False+++# ---------------------------------------------------------------------------+# Wire-format invariant — the pattern string is consumed verbatim by+# FastAPI's ``Path(pattern=...)`` constraint in routers/schemas.py.+# Re-compiling here proves the string is a valid regex and verifies the+# two consumers (FastAPI side + Python side) match on a few canonical+# values.+# ---------------------------------------------------------------------------+++def test_pattern_string_is_valid_regex() -> None:+ compiled = re.compile(NODE_TYPE_PATTERN)+ assert compiled.fullmatch("aiAgent") is not None+ assert compiled.fullmatch("../etc/passwd") is None+++def test_pattern_string_anchors_full_match_only() -> None:+ """``fullmatch`` semantics — the ``^`` / ``$`` anchors must not+ allow ``re.search`` to find the pattern as a substring of a hostile+ URL value. FastAPI's ``pattern=`` uses ``re.match`` (anchored at+ start only), but the ``$`` anchor blocks suffix injection."""+ compiled = re.compile(NODE_TYPE_PATTERN)+ assert compiled.fullmatch("aiAgent/../etc/passwd") is None+ assert compiled.fullmatch("aiAgent\x00../etc") is None