Skip to content

Self-improving AI Employees for everyone

security: close error-severity code-scanning + dependabot alerts

trohitgaac82d1b52e9
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 2afe40a3..cef3577b 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -107,14 +107,15 @@ jobs:
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Setup Node.js
+ # ``cache:`` key intentionally omitted (release-job hardening).
+ # A poisoned cache from a previous CI run cannot taint the
+ # tarball when caching is disabled outright; zizmor's
+ # ``cache-poisoning`` audit requires the input absent, not just
+ # set to an empty string.
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: '22'
registry-url: 'https://registry.npmjs.org'
- # cache: false in release jobs (wrangler hardening). A
- # poisoned cache from previous CI runs cannot taint the
- # tarball; release-time installs always pull fresh.
- cache: ''
- name: Download built client
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
@@ -174,12 +175,13 @@ jobs:
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Setup Node.js
+ # ``cache:`` key intentionally omitted (release-job hardening
+ # -- matches the publish-npm job above; zizmor's
+ # ``cache-poisoning`` audit requires the input absent).
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: '22'
registry-url: 'https://npm.pkg.github.com'
- # cache: false in release jobs (wrangler hardening).
- cache: ''
- name: Download built client
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
diff --git a/package.json b/package.json
index 16b6f911..6689ab9b 100644
--- a/package.json
+++ b/package.json
@@ -103,6 +103,11 @@
"react-avatar-editor>react": "19",
"react-avatar-editor>react-dom": "19"
}
+ },
+ "overrides": {
+ "js-cookie@<3.0.7": "^3.0.7",
+ "qs@<6.14.0": "^6.14.0",
+ "ws@<8.17.1": "^8.17.1"
}
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7688acd5..94299964 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -4,6 +4,11 @@ settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
+overrides:
+ js-cookie@<3.0.7: ^3.0.7
+ qs@<6.14.0: ^6.14.0
+ ws@<8.17.1: ^8.17.1
+
importers:
.:
@@ -4146,9 +4151,9 @@ packages:
resolution: {integrity: sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==}
- resolution: {integrity: sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==}
- engines: {node: '>=14'}
+ resolution: {integrity: sha512-z/wZZgDrkNV1eA0ULjM/F9/50Ya8fbzgKneSpoPsXSGd0KnpdtHfOZWK+GcwLk+EZbS4F9RBhU+K2RgzuDaItw==}
+ engines: {node: '>=20'}
resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
@@ -9045,7 +9050,7 @@ snapshots:
'@types/js-cookie': 3.0.6
dayjs: 1.11.20
intersection-observer: 0.12.2
- js-cookie: 3.0.5
+ js-cookie: 3.0.7
lodash: 4.18.1
react: 19.2.6
react-dom: 19.2.6([email protected])
@@ -10666,7 +10671,7 @@ snapshots:
diff --git a/server/main.py b/server/main.py
index cf3e838b..5008fcfd 100644
--- a/server/main.py
+++ b/server/main.py
@@ -489,13 +489,16 @@ class CatchAllExceptionsMiddleware(BaseHTTPMiddleware):
try:
return await call_next(request)
except Exception as e:
- import traceback
-
- traceback.print_exc()
- logger.error(f"Unhandled exception: {type(e).__name__}: {str(e)}", exc_info=True)
+ # Full traceback goes to the structured log + file handler;
+ # the HTTP response body intentionally carries a generic
+ # message so an attacker hitting an unhandled-exception code
+ # path can't enumerate stack frames, file paths, or library
+ # versions. Matches the OWASP ``py/stack-trace-exposure``
+ # mitigation pattern.
+ logger.error("Unhandled exception", error_type=type(e).__name__, error=str(e), exc_info=True)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={"success": False, "error": f"{type(e).__name__}: {str(e)}", "detail": "Internal server error"},
+ content={"success": False, "error": "Internal server error", "detail": "Internal server error"},
)
diff --git a/server/nodes/_visuals.py b/server/nodes/_visuals.py
index 513a5ac9..db9c72a7 100644
--- a/server/nodes/_visuals.py
+++ b/server/nodes/_visuals.py
@@ -171,13 +171,14 @@ def get_plugin_icon_path(node_type: str, variant: str = "light") -> Optional[Pat
return None
# Candidate filenames in resolution order. Per-node-type first so
- # multi-node folders can override the shared icon for specific
- # node types. ``node_type`` is already constrained to
- # ``NODE_TYPE_PATTERN`` (``^[A-Za-z_][A-Za-z0-9_]*$``) by
- # ``is_valid_node_type`` above -- no path separators possible --
- # but resolving + ``is_relative_to(plugin_dir)`` gives CodeQL a
- # path-injection sanitizer it can statically prove (closes the
- # ``py/path-injection`` alert without weakening the contract).
+ # multi-node folders can override the shared icon for specific node
+ # types. ``node_type`` is already constrained to ``NODE_TYPE_PATTERN``
+ # (``^[A-Za-z_][A-Za-z0-9_]*$``) by ``is_valid_node_type`` above --
+ # no path separators possible -- but we resolve the candidate and
+ # call ``Path.relative_to(plugin_dir)`` (which raises ``ValueError``
+ # on traversal). CodeQL's taint tracker recognises
+ # ``Path.relative_to`` as a ``py/path-injection`` sanitizer; the
+ # ``is_relative_to`` predicate it does not.
candidates: list[str] = []
if variant == "dark":
candidates.append(f"icon_{node_type}.dark.svg")
@@ -188,7 +189,9 @@ def get_plugin_icon_path(node_type: str, variant: str = "light") -> Optional[Pat
for name in candidates:
candidate = (plugin_dir / name).resolve()
- if not candidate.is_relative_to(plugin_dir):
+ try:
+ candidate.relative_to(plugin_dir)
+ except ValueError:
continue
if candidate.exists():
return candidate
diff --git a/server/nodes/android/_router.py b/server/nodes/android/_router.py
index d498028d..97eed55a 100644
--- a/server/nodes/android/_router.py
+++ b/server/nodes/android/_router.py
@@ -1,8 +1,6 @@
"""Android System Services routes."""
-import re
-
-from fastapi import APIRouter, Depends, HTTPException
+from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from typing import Dict, Any
@@ -15,17 +13,13 @@ router = APIRouter(prefix="/api/android", tags=["android"])
# ADB device IDs: USB serials (alphanumeric), TCP "host:port" (digits + dots
# + colon), or "emulator-NNNN". All are safe characters but we lock the
-# accepted set explicitly so untrusted input can't slip a flag or path
-# separator into the argv list we pass to subprocess.run. Anything outside
-# `[A-Za-z0-9._:-]` (and longer than 64 chars) is rejected with 400.
-_DEVICE_ID_PATTERN = re.compile(r"^[A-Za-z0-9._:-]{1,64}$")
-
-
-def _validate_device_id(device_id: str) -> str:
- """Return device_id if it matches the ADB device-id shape, else 400."""
- if not _DEVICE_ID_PATTERN.fullmatch(device_id):
- raise HTTPException(status_code=400, detail="invalid device_id")
- return device_id
+# accepted set explicitly via FastAPI's ``Query(pattern=...)`` so untrusted
+# input can't slip a flag or path separator into the argv list we pass to
+# ``subprocess.run``. Anything outside ``[A-Za-z0-9._:-]`` (or longer than
+# 64 chars) is rejected with a 422 before the handler body runs --
+# CodeQL recognises the Pydantic-pattern constraint as a sanitizer so
+# ``py/command-line-injection`` doesn't fire on the resulting argv.
+_DEVICE_ID_PATTERN = r"^[A-Za-z0-9._:-]{1,64}$"
class AndroidServiceRequest(BaseModel):
@@ -146,20 +140,24 @@ async def list_android_devices():
logger.error("[Android] ADB not found in PATH")
return {"success": False, "error": "ADB not found. Please install Android SDK Platform Tools", "devices": []}
except Exception as e:
- logger.error(f"[Android] Failed to list devices: {e}")
- return {"success": False, "error": str(e), "devices": []}
+ logger.error("[Android] Failed to list devices", error=str(e), exc_info=True)
+ return {"success": False, "error": "Failed to list devices", "devices": []}
@router.post("/port-forward")
-async def setup_port_forwarding(device_id: str, local_port: int = 8888, device_port: int = 8888):
+async def setup_port_forwarding(
+ device_id: str = Query(..., pattern=_DEVICE_ID_PATTERN, max_length=64),
+ local_port: int = Query(8888, ge=1024, le=65535),
+ device_port: int = Query(8888, ge=1024, le=65535),
+):
"""Setup ADB port forwarding for Android device communication."""
- device_id = _validate_device_id(device_id)
import subprocess
try:
# Setup port forwarding: adb -s device_id forward tcp:local_port tcp:device_port
- # device_id passes _DEVICE_ID_PATTERN above; subprocess.run is called
- # with an argv list (no shell), so no further interpolation risk.
+ # device_id is constrained by ``Query(pattern=_DEVICE_ID_PATTERN, max_length=64)``
+ # at the boundary; ``local_port``/``device_port`` are bounded ints. Argv
+ # list is passed to ``subprocess.run`` with ``shell=False`` (the default).
cmd = ["adb", "-s", device_id, "forward", f"tcp:{local_port}", f"tcp:{device_port}"]
result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5)
@@ -181,8 +179,8 @@ async def setup_port_forwarding(device_id: str, local_port: int = 8888, device_p
logger.error("[Android] ADB not found in PATH")
return {"success": False, "error": "ADB not found. Please install Android SDK Platform Tools"}
except Exception as e:
- logger.error(f"[Android] Port forwarding error: {e}")
- return {"success": False, "error": str(e)}
+ logger.error("[Android] Port forwarding error", error=str(e), exc_info=True)
+ return {"success": False, "error": "Port forwarding failed"}
@router.get("/health")
@@ -226,5 +224,5 @@ async def get_relay_connection_status():
"status": "disconnected",
}
except Exception as e:
- logger.error(f"[Android] Failed to get relay status: {e}")
- return {"success": False, "connected": False, "error": str(e), "status": "error"}
+ logger.error("[Android] Failed to get relay status", error=str(e), exc_info=True)
+ return {"success": False, "connected": False, "error": "Failed to get relay status", "status": "error"}
diff --git a/server/routers/database.py b/server/routers/database.py
index ac202bc9..1709779a 100644
--- a/server/routers/database.py
+++ b/server/routers/database.py
@@ -31,8 +31,8 @@ async def save_node_parameters(request: NodeParameterRequest, database: Database
success = await database.save_node_parameters(request.node_id, request.parameters)
return {"success": success}
except Exception as e:
- logger.error("Failed to save node parameters", error=str(e))
- return {"success": False, "error": str(e)}
+ logger.error("Failed to save node parameters", error=str(e), exc_info=True)
+ return {"success": False, "error": "Failed to save node parameters"}
@router.get("/node-parameters/{node_id}")
@@ -42,8 +42,8 @@ async def get_node_parameters(node_id: str, database: Database = Depends(lambda:
parameters = await database.get_node_parameters(node_id)
return {"success": True, "parameters": parameters}
except Exception as e:
- logger.error("Failed to get node parameters", error=str(e))
- return {"success": False, "error": str(e)}
+ logger.error("Failed to get node parameters", error=str(e), exc_info=True)
+ return {"success": False, "error": "Failed to get node parameters"}
@router.delete("/node-parameters/{node_id}")
@@ -53,8 +53,8 @@ async def delete_node_parameters(node_id: str, database: Database = Depends(lamb
success = await database.delete_node_parameters(node_id)
return {"success": success}
except Exception as e:
- logger.error("Failed to delete node parameters", error=str(e))
- return {"success": False, "error": str(e)}
+ logger.error("Failed to delete node parameters", error=str(e), exc_info=True)
+ return {"success": False, "error": "Failed to delete node parameters"}
# ============================================================================
@@ -69,8 +69,8 @@ async def save_workflow(request: WorkflowSaveRequest, database: Database = Depen
success = await database.save_workflow(workflow_id=request.workflow_id, name=request.name, data=request.data)
return {"success": success, "workflow_id": request.workflow_id}
except Exception as e:
- logger.error("Failed to save workflow", error=str(e))
- return {"success": False, "error": str(e)}
+ logger.error("Failed to save workflow", error=str(e), exc_info=True)
+ return {"success": False, "error": "Failed to save workflow"}
@router.get("/workflows")
@@ -107,8 +107,8 @@ async def get_all_workflows(database: Database = Depends(lambda: container.datab
],
}
except Exception as e:
- logger.error("Failed to get workflows", error=str(e))
- return {"success": False, "error": str(e)}
+ logger.error("Failed to get workflows", error=str(e), exc_info=True)
+ return {"success": False, "error": "Failed to get workflows"}
@router.get("/workflows/{workflow_id}")
@@ -129,8 +129,8 @@ async def get_workflow(workflow_id: str, database: Database = Depends(lambda: co
}
return {"success": False, "error": "Workflow not found"}
except Exception as e:
- logger.error("Failed to get workflow", error=str(e))
- return {"success": False, "error": str(e)}
+ logger.error("Failed to get workflow", error=str(e), exc_info=True)
+ return {"success": False, "error": "Failed to get workflow"}
@router.delete("/workflows/{workflow_id}")
@@ -140,5 +140,5 @@ async def delete_workflow(workflow_id: str, database: Database = Depends(lambda:
success = await database.delete_workflow(workflow_id)
return {"success": success, "workflow_id": workflow_id}
except Exception as e:
- logger.error("Failed to delete workflow", error=str(e))
- return {"success": False, "error": str(e)}
+ logger.error("Failed to delete workflow", error=str(e), exc_info=True)
+ return {"success": False, "error": "Failed to delete workflow"}
diff --git a/server/routers/workflow.py b/server/routers/workflow.py
index 41e5a5b6..ee405519 100644
--- a/server/routers/workflow.py
+++ b/server/routers/workflow.py
@@ -88,8 +88,8 @@ async def clear_workflow_outputs(
await workflow_service.clear_all_outputs(session_id)
return {"success": True, "message": f"Cleared all outputs for session: {session_id}"}
except Exception as e:
- logger.error("Failed to clear outputs", session_id=session_id, error=str(e))
- return {"success": False, "error": str(e)}
+ logger.error("Failed to clear outputs", session_id=session_id, error=str(e), exc_info=True)
+ return {"success": False, "error": "Failed to clear outputs"}
@router.get("/health")
diff --git a/server/services/events/oauth_lifecycle.py b/server/services/events/oauth_lifecycle.py
index b49e0f0b..938aa21f 100644
--- a/server/services/events/oauth_lifecycle.py
+++ b/server/services/events/oauth_lifecycle.py
@@ -35,6 +35,8 @@ fail the callback CSRF check.
from __future__ import annotations
+import html
+import json
from typing import Any, Awaitable, Callable, Dict, Optional, Protocol
from fastapi import APIRouter, Query, Request, WebSocket
@@ -493,9 +495,9 @@ _HTML_TEMPLATE = """<!DOCTYPE html>
<script>
if (window.opener) {{
window.opener.postMessage({{
- type: '{provider}_oauth_callback',
+ type: {provider_js},
success: {success_js},
- message: '{message_js}',
+ message: {message_js},
}}, '*');
}}
setTimeout(function() {{ window.close(); }}, 2000);
@@ -525,19 +527,60 @@ def render_oauth_callback_html(
``{provider}_oauth_callback`` message to ``window.opener`` (the
popup's parent) and auto-closes after 2 seconds.
"""
+ # ``message`` reaches the page via the OAuth provider's ``?error_description=``
+ # query string -- attacker-controllable. Escape for both contexts the
+ # template interpolates it into:
+ # * ``<p>{message}</p>`` → ``html.escape`` neutralises
+ # ``<script>`` / attribute breakouts.
+ # * ``postMessage({ message: '{message_js}' })`` → ``json.dumps`` wraps the
+ # string in correctly-escaped
+ # JS source (matching quotes,
+ # ``</script>`` neutralised,
+ # unicode literals).
+ # CodeQL recognises both as ``py/reflective-xss`` sanitizers.
+ # ``message`` reaches the page via the OAuth provider's
+ # ``?error_description=`` query string -- attacker-controllable.
+ # Two sinks need separate escaping:
+ #
+ # * ``<p>{message}</p>`` → ``html.escape`` neutralises ``<script>``,
+ # attribute breakouts, ampersand-entities.
+ # * ``postMessage({message: X})`` → ``json.dumps`` + ``_js_safe`` post-escape.
+ # ``json.dumps`` alone does NOT escape ``<``
+ # or ``</``: an attacker-controlled message
+ # containing ``</script>`` would close the
+ # surrounding ``<script>`` tag because the
+ # browser tokenizer scans for that pattern
+ # before parsing the JS string. Per OWASP
+ # guidance we ``\u``-escape ``<`` ``>`` ``&``
+ # so the JSON literal is also safe inside
+ # a ``<script>`` block.
is_success = status == "success"
title = f"{provider.capitalize()} Connected" if is_success else "Connection Failed"
return _HTML_TEMPLATE.format(
- title=title,
- message=message,
+ title=html.escape(title),
+ message=html.escape(message),
color_hex=color_hex,
icon_path=_SUCCESS_ICON if is_success else _ERROR_ICON,
- provider=provider,
+ provider_js=_js_safe(json.dumps(f"{provider}_oauth_callback")),
success_js=str(is_success).lower(),
- message_js=message.replace("'", "\\'"),
+ message_js=_js_safe(json.dumps(message)),
)
+def _js_safe(json_literal: str) -> str:
+ """Post-escape a ``json.dumps`` output for safe inlining inside ``<script>``.
+
+ ``json.dumps`` follows the JSON spec, which doesn't require ``<`` / ``>`` /
+ ``&`` to be escaped -- but an attacker-controlled string containing
+ ``</script>`` inside a JSON literal would still close the surrounding
+ ``<script>`` block (the browser tokenizer hunts for ``</script>`` regardless
+ of JS string-literal state). The OWASP Cheat Sheet recommends ``\\u``-encoding
+ those three characters before emission. CodeQL recognises this pattern as a
+ ``py/reflective-xss`` sanitizer.
+ """
+ return json_literal.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
+
+
__all__ = [
"OAuthLike",
"OAuthFactory",