Skip to content

Self-improving AI Employees for everyone

fix(security): close the open CodeQL findings

trohitg2d238ee6d213
diff --git a/bun.lock b/bun.lock
index 0eae49b7..56762183 100644
--- a/bun.lock
+++ b/bun.lock
@@ -13,7 +13,7 @@
},
"client": {
"name": "react-flow-client",
- "version": "0.1.1",
+ "version": "0.2.1",
"dependencies": {
"@eslint/js": "^10.0.1",
"@fontsource-variable/geist": "^5.2.8",
@@ -83,6 +83,7 @@
"version": "1.0.0",
"dependencies": {
"express": "^5.2.1",
+ "express-rate-limit": "^8.7.0",
},
"devDependencies": {
"@types/express": "^5.0.6",
@@ -1327,7 +1328,7 @@
"express": ["[email protected]", "", { "dependencies": { "accepts": "2.0.0", "body-parser": "2.3.0", "content-disposition": "1.1.0", "content-type": "1.0.5", "cookie": "0.7.2", "cookie-signature": "1.2.2", "debug": "4.4.3", "depd": "2.0.0", "encodeurl": "2.0.0", "escape-html": "1.0.3", "etag": "1.8.1", "finalhandler": "2.1.1", "fresh": "2.0.0", "http-errors": "2.0.1", "merge-descriptors": "2.0.0", "mime-types": "3.0.2", "on-finished": "2.4.1", "once": "1.4.0", "parseurl": "1.3.3", "proxy-addr": "2.0.7", "qs": "6.15.2", "range-parser": "1.2.1", "router": "2.2.0", "send": "1.2.1", "serve-static": "2.2.1", "statuses": "2.0.2", "type-is": "2.0.1", "vary": "1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
- "express-rate-limit": ["[email protected]", "", { "dependencies": { "debug": "4.4.3", "ip-address": "10.5.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A=="],
+ "express-rate-limit": ["[email protected]", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-hOwV7WOxXfjRpAM1DSJWZDXx3GhplwD8IfwuwvogD8i1Qnkgosw/H45s4ZnFAUHDAhPjlY9hLBvJhKmGMyY26g=="],
"extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
@@ -2525,6 +2526,8 @@
"@modelcontextprotocol/sdk/ajv-formats": ["[email protected]", "", { "peerDependencies": { "ajv": "^8.0.0" }, "optionalPeers": ["ajv"] }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
+ "@modelcontextprotocol/sdk/express-rate-limit": ["[email protected]", "", { "dependencies": { "debug": "4.4.3", "ip-address": "10.5.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A=="],
+
"@radix-ui/react-accordion/@radix-ui/react-compose-refs": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
"@radix-ui/react-accordion/@radix-ui/react-id": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="],
diff --git a/cli/tests/test_release_pipeline_config.py b/cli/tests/test_release_pipeline_config.py
index 74a22d46..0027ffe6 100644
--- a/cli/tests/test_release_pipeline_config.py
+++ b/cli/tests/test_release_pipeline_config.py
@@ -453,7 +453,7 @@ def test_npm_release_authenticates_before_publish(
publish_index = next(i for i, step in enumerate(steps) if "bun publish" in step["run"])
assert steps[auth_index]["env"]["NPM_TOKEN"] == "${{ secrets.NPM_TOKEN }}"
- assert "registry.npmjs.org" in steps[auth_index]["run"]
+ assert steps[auth_index]["run"] == "printf '//registry.npmjs.org/:_authToken=%s\\n' \"$NPM_TOKEN\" > ~/.npmrc"
assert steps[preflight_index]["run"] == "bun pm whoami"
assert auth_index < preflight_index < publish_index
diff --git a/server/core/approot.py b/server/core/approot.py
index f40e05fd..77c075dd 100644
--- a/server/core/approot.py
+++ b/server/core/approot.py
@@ -74,6 +74,29 @@ def client_dist() -> Path:
return _env_path("OPENCOMPANY_CLIENT_DIST") or (app_root() / "client" / "dist")
+def resolve_static_asset(base_dir: Path, relative: str) -> str | None:
+ """Return the absolute path of ``relative`` inside ``base_dir``, or ``None``.
+
+ Built for the SPA fallback route, which maps a request path onto the
+ built client directory. The request path is attacker-controlled, so the
+ joined path is normalised with :func:`os.path.normpath` and then
+ required to start with the (real) base directory plus a separator; a
+ ``..`` escape, an absolute path, or a prefix-sibling such as
+ ``client/dist2`` all fail that test. ``None`` also covers a path that
+ resolves inside the directory but is not a regular file, so callers
+ fall through to their default (the SPA shell).
+ """
+ if not relative:
+ return None
+ root = os.path.realpath(str(base_dir))
+ candidate = os.path.normpath(os.path.join(root, relative))
+ if not candidate.startswith(root + os.sep):
+ return None
+ if not os.path.isfile(candidate):
+ return None
+ return candidate
+
+
def env_template_path() -> Path:
"""The canonical ``.env.template`` (baseline for every env var)."""
return _env_path("OPENCOMPANY_ENV_TEMPLATE") or (app_root() / ".env.template")
@@ -98,6 +121,7 @@ __all__ = [
"app_root",
"server_root",
"client_dist",
+ "resolve_static_asset",
"env_template_path",
"env_file_path",
"package_json_path",
diff --git a/server/main.py b/server/main.py
index 94cb7c1b..c6d43b99 100644
--- a/server/main.py
+++ b/server/main.py
@@ -57,7 +57,11 @@ from core.env_defaults import apply_file_defaults_to_environ
apply_file_defaults_to_environ()
-from core.approot import client_dist as _client_dist, package_json_path as _package_json_path
+from core.approot import (
+ client_dist as _client_dist,
+ package_json_path as _package_json_path,
+ resolve_static_asset as _resolve_static_asset,
+)
from core.config import Settings, cookie_posture_warnings, dev_secret_offenders
from core.logging import configure_logging, get_logger, setup_websocket_logging, shutdown_websocket_logging
from core.tracing import init_tracing
@@ -798,11 +802,12 @@ if _SERVE_STATIC and (_CLIENT_DIST / "index.html").is_file():
"""Serve a built static asset when it exists, else the SPA shell."""
if full_path.startswith(_NON_SPA_PREFIXES):
return JSONResponse(status_code=404, content={"detail": "Not Found"})
- candidate = (_CLIENT_DIST / full_path).resolve()
- # is_file() + containment check guard against ``..`` path traversal
- # escaping the build directory.
- if full_path and candidate.is_file() and _CLIENT_DIST in candidate.parents:
- return FileResponse(str(candidate))
+ # The request path is user input; core.approot normalises it and
+ # refuses anything that does not stay inside the build directory
+ # (``..`` traversal, absolute paths, prefix siblings).
+ asset = _resolve_static_asset(_CLIENT_DIST, full_path)
+ if asset is not None:
+ return FileResponse(asset)
return FileResponse(str(_CLIENT_DIST / "index.html"))
logger.info("Serving built client from %s", _CLIENT_DIST)
diff --git a/server/nodejs/package.json b/server/nodejs/package.json
index 8f32ff6a..2b7b1d23 100644
--- a/server/nodejs/package.json
+++ b/server/nodejs/package.json
@@ -10,7 +10,8 @@
"dev": "bun --watch src/index.ts"
},
"dependencies": {
- "express": "^5.2.1"
+ "express": "^5.2.1",
+ "express-rate-limit": "^8.7.0"
},
"devDependencies": {
"@types/express": "^5.0.6",
diff --git a/server/nodejs/src/index.ts b/server/nodejs/src/index.ts
index 3291f5e1..452e0d68 100644
--- a/server/nodejs/src/index.ts
+++ b/server/nodejs/src/index.ts
@@ -4,6 +4,7 @@
*/
import express, { Request, Response, NextFunction } from 'express';
+import rateLimit from 'express-rate-limit';
import vm from 'node:vm';
import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
@@ -32,6 +33,16 @@ const bunVersion = (globalThis as { Bun?: { version: string } }).Bun?.version ??
const app = express();
app.use(express.json({ limit: BODY_LIMIT }));
+// The package routes touch the filesystem and spawn `bun add`. The only
+// caller is the same-machine Python backend, so the ceiling is generous;
+// it exists so a stray loop cannot hammer the disk or the registry.
+const packageRouteLimiter = rateLimit({
+ windowMs: 60_000,
+ limit: 120,
+ standardHeaders: true,
+ legacyHeaders: false,
+});
+
interface ExecuteRequest {
code: string;
language?: 'javascript' | 'typescript';
@@ -99,8 +110,8 @@ app.post('/execute', (req: Request, res: Response) => {
// the deployment context is: server binds to localhost only (line 16,
// default 'localhost') and is invoked exclusively by the same-machine
// Python backend via NodeJSClient. Public network exposure is the
- // operator's responsibility.
- // codeql[js/code-injection]
+ // operator's responsibility. CodeQL's js/code-injection finding on this
+ // line is by design and is dismissed on the repository as "won't fix".
vm.runInContext(prepareSource(code, language), context, { timeout, filename: language === 'typescript' ? 'user-code.ts' : 'user-code.js' });
res.json({
@@ -131,10 +142,8 @@ function ensureUserPackagesTree(): void {
// Install packages - package list from request.
// Localhost-only service (see server.listen at the bottom); same trust
-// boundary as the /execute sandbox. No request-rate limiting because the
-// only caller is the same-machine Python backend.
-// codeql[js/missing-rate-limiting]
-app.post('/packages/install', (req: Request, res: Response) => {
+// boundary as the /execute sandbox.
+app.post('/packages/install', packageRouteLimiter, (req: Request, res: Response) => {
const { packages } = req.body as { packages: string[] };
if (!packages || !Array.isArray(packages) || packages.length === 0) {
@@ -165,8 +174,7 @@ app.post('/packages/install', (req: Request, res: Response) => {
// List packages — same localhost-only trust boundary as above. The tree's
// own manifest is the source of truth (what `bun add` wrote), so no
// package-manager listing command is needed.
-// codeql[js/missing-rate-limiting]
-app.get('/packages', (_req: Request, res: Response) => {
+app.get('/packages', packageRouteLimiter, (_req: Request, res: Response) => {
try {
const manifest = JSON.parse(readFileSync(path.join(USER_PACKAGES_DIR, 'package.json'), 'utf-8')) as {
dependencies?: Record<string, string>;