Skip to content

Self-improving AI Employees for everyone

fix(security): validate Android ADB port-forward commands

trohitg1a5523e17b91
diff --git a/docs-internal/ci_cd.md b/docs-internal/ci_cd.md
index 278b3bf5..4e4dff77 100644
--- a/docs-internal/ci_cd.md
+++ b/docs-internal/ci_cd.md
@@ -243,6 +243,20 @@ Inline `// codeql[...]` / `# codeql[...]` comments do **not** suppress
anything under default setup — several sat in the sidecar for months while
the alerts stayed open. Dismiss in the Security tab instead.
+The Android port-forward endpoint addresses `py/command-line-injection`
+([alert #167](https://github.com/zeenie-ai/OpenCompany/security/code-scanning/167))
+by passing a literal argv beginning with `adb` directly to `subprocess.run`
+with `shell=False`. CodeQL's
+[subprocess model](https://github.com/github/codeql/blob/main/python/ql/lib/semmle/python/frameworks/Stdlib.qll)
+can identify the fixed executable in an inline sequence; a separately assigned
+argv variable can be treated as an entirely tainted command. FastAPI's
+`Query(pattern=...)` is not a command-injection sanitizer in that model.
+The handler also independently validates serials and integer port bounds before
+starting ADB. See the [Android contract](node-logic-flows/android/_pattern.md#adb-port-forwarding)
+and [security regressions](../server/tests/nodes/test_android_port_forward.py).
+Alert closure must be confirmed by a successful GitHub scan of the pushed fix;
+local test results do not change an alert's server-side state.
+
## Dependency update policy (Dependabot disabled)
The policy is **no automatic pull requests**, neither version bumps nor
@@ -322,7 +336,17 @@ untrusted input here:
| Advisory | Package | Reached through | Why it is ignored |
|---|---|---|---|
-| [GHSA-ch52-4w7c-c8xp](https://github.com/advisories/GHSA-ch52-4w7c-c8xp) | http-cache-semantics 4.2.0 | `desktop/`: Electron Builder → app-builder-lib → @electron/get 3.1.0 → got → cacheable-request | No patched release as of 2026-10-09. Build-time artifact downloading does not share authenticated user-response caches; this chain is absent from the shipped desktop runtime dependencies. |
+| [GHSA-ch52-4w7c-c8xp](https://github.com/advisories/GHSA-ch52-4w7c-c8xp) | http-cache-semantics 4.2.0 | `desktop/`: Electron Builder → app-builder-lib → @electron/get 3.1.0 → got → cacheable-request | No verified upstream fix as of 2026-10-09; published 4.3.0 also reproduces the reported behavior. Build-time artifact downloading does not share authenticated user-response caches; this chain is absent from the shipped desktop runtime dependencies. |
+
+The 4.3.0 registry tarball was checked against its published SHA-512 integrity
+and tested with a fixed-clock shared-cache fixture on 2026-10-09. Responses
+containing `Set-Cookie` or `proxy-revalidate` were rejected for ordinary requests
+but reused when the request supplied `max-stale=3600`; the cookie was returned
+in the first case. The `must-revalidate` control prevented reuse. Both installed
+4.2.0 and published 4.3.0 behaved this way. The
+[published 4.3.0 source](https://github.com/kornelski/http-cache-semantics/blob/b1d4bd682fbab0252985de45219f4e7497c0067c/index.js)
+retains this logic. Moving beyond an advisory's current version range alone
+does not establish remediation.
The shadcn CLI was removed from `client/package.json` and the root lockfile on
2026-10-09, removing `braces` and its advisory entirely. The client used one
diff --git a/docs-internal/node-logic-flows/android/_pattern.md b/docs-internal/node-logic-flows/android/_pattern.md
index 419d32f7..60393e91 100644
--- a/docs-internal/node-logic-flows/android/_pattern.md
+++ b/docs-internal/node-logic-flows/android/_pattern.md
@@ -152,6 +152,25 @@ preserved.
in relay mode. The relay `connected` state alone is not sufficient.
- **Environment variables**: none; host/port come from hidden node params.
+## ADB port forwarding
+
+`POST /api/android/port-forward` in the [Android router](../../../server/nodes/android/_router.py)
+sets up local device communication outside node execution. It accepts USB,
+emulator, TCP and wireless-debugging serials of up to 64 characters. Serials
+must start with an ASCII letter or digit; subsequent characters may also be
+`.`, `_`, `:`, or `-`. Both ports must be integers between 1024 and 65535.
+
+FastAPI checks the query parameters, and the handler validates them again
+before starting ADB, including when called directly from Python. Invalid input
+returns HTTP 422 without starting a subprocess. The subprocess receives a
+literal argument list beginning with `adb`, uses `shell=False`, has a five-second
+timeout, and excludes the 1Password bootstrap environment. Valid requests retain
+the existing success/error response envelopes and do not add device discovery.
+
+The [port-forward regression tests](../../../server/tests/nodes/test_android_port_forward.py)
+cover valid serials, boundary ports, malicious inputs, direct calls and ADB
+failures.
+
## Known inconsistencies & edge cases
1. **Frontend/backend service_id mismatch for four nodes**. The frontend
diff --git a/server/nodes/android/_router.py b/server/nodes/android/_router.py
index 70928667..e9299a99 100644
--- a/server/nodes/android/_router.py
+++ b/server/nodes/android/_router.py
@@ -1,6 +1,8 @@
"""Android System Services routes."""
-from fastapi import APIRouter, Depends, Query
+import re
+
+from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from typing import Dict, Any
@@ -11,15 +13,10 @@ from services.plugin.deps import get_android_service
logger = get_logger(__name__)
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 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}$"
+# USB, emulator, TCP and wireless-debugging serials. The first character
+# must be alphanumeric so a device ID cannot look like a command-line flag.
+# Also enforce this at the subprocess boundary for callers outside FastAPI.
+_DEVICE_ID_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"
class AndroidServiceRequest(BaseModel):
@@ -117,15 +114,31 @@ async def setup_port_forwarding(
"""Setup ADB port forwarding for Android device communication."""
import subprocess
- try:
- # Setup port forwarding: adb -s device_id forward tcp:local_port tcp:device_port
- # 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}"]
+ if not isinstance(device_id, str) or re.fullmatch(_DEVICE_ID_PATTERN, device_id) is None:
+ raise HTTPException(status_code=422, detail="Invalid Android device ID")
+ if (
+ type(local_port) is not int
+ or type(device_port) is not int
+ or not 1024 <= local_port <= 65535
+ or not 1024 <= device_port <= 65535
+ ):
+ raise HTTPException(status_code=422, detail="Ports must be integers between 1024 and 65535")
+ try:
from services.process_environment import without_onepassword_environment
- result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5, env=without_onepassword_environment())
+
+ # Keep the executable literal at the call site, with validated inputs
+ # confined to individual arguments. No shell interprets these values.
+ result = subprocess.run(
+ ["adb", "-s", device_id, "forward", f"tcp:{int(local_port)}", f"tcp:{int(device_port)}"],
+ shell=False,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=5,
+ env=without_onepassword_environment(),
+ )
if result.returncode == 0:
logger.info(f"[Android] Port forwarding setup: {device_id} tcp:{local_port} -> tcp:{device_port}")
diff --git a/server/tests/nodes/test_android_port_forward.py b/server/tests/nodes/test_android_port_forward.py
new file mode 100644
index 00000000..8587092c
--- /dev/null
+++ b/server/tests/nodes/test_android_port_forward.py
@@ -0,0 +1,185 @@
+"""ADB port forwarding rejects command inputs before starting a subprocess."""
+
+from __future__ import annotations
+
+import subprocess
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+import pytest
+
+from nodes.android._router import router, setup_port_forwarding
+
+
+def client():
+ app = FastAPI()
+ app.include_router(router)
+ with TestClient(app) as test_client:
+ yield test_client
+
+
+def _completed(*, returncode=0, stdout="", stderr=""):
+ return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)
+
+
+ "device_id",
+ [
+ "R58M123ABC",
+ "emulator-5554",
+ "192.168.1.20:5555",
+ "phone.local:5555",
+ "adb-serial-token._adb-tls-connect._tcp",
+ "A" * 64,
+ ],
+)
+def test_valid_serials_are_passed_as_one_fixed_command_argument(client, device_id):
+ with patch("subprocess.run", return_value=_completed()) as run:
+ response = client.post("/api/android/port-forward", params={"device_id": device_id})
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "success": True,
+ "device_id": device_id,
+ "local_port": 8888,
+ "device_port": 8888,
+ "message": "Port forwarding active: localhost:8888 -> device:8888",
+ }
+ assert run.call_count == 1
+ assert run.call_args.args == (["adb", "-s", device_id, "forward", "tcp:8888", "tcp:8888"],)
+ assert run.call_args.kwargs["shell"] is False
+ assert run.call_args.kwargs["timeout"] == 5
+ assert run.call_args.kwargs["capture_output"] is True
+ assert run.call_args.kwargs["text"] is True
+ assert run.call_args.kwargs["encoding"] == "utf-8"
+ assert run.call_args.kwargs["errors"] == "replace"
+
+
[email protected]("local_port,device_port", [(1024, 65535), (65535, 1024)])
+def test_port_boundaries_preserve_forwarding_contract(client, local_port, device_port):
+ with patch("subprocess.run", return_value=_completed()) as run:
+ response = client.post(
+ "/api/android/port-forward",
+ params={"device_id": "emulator-5554", "local_port": local_port, "device_port": device_port},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["local_port"] == local_port
+ assert response.json()["device_port"] == device_port
+ assert run.call_args.args[0][-2:] == [f"tcp:{local_port}", f"tcp:{device_port}"]
+
+
+ "device_id",
+ [
+ "",
+ "-Hlocalhost",
+ "--help",
+ ".device",
+ ":5555",
+ "serial other",
+ "serial;whoami",
+ "serial&&whoami",
+ "$(whoami)",
+ "`whoami`",
+ "serial/other",
+ "serial\\other",
+ "serial\n",
+ "serial\r",
+ "serial\t",
+ "serial\x00",
+ "A" * 65,
+ "телефон",
+ ],
+)
+def test_invalid_serials_are_rejected_before_starting_adb(client, device_id):
+ with patch("subprocess.run") as run:
+ response = client.post("/api/android/port-forward", params={"device_id": device_id})
+
+ assert response.status_code == 422
+ run.assert_not_called()
+
+
[email protected]("port_name", ["local_port", "device_port"])
[email protected]("port", [1023, 65536, "12.5", "true", "8888;whoami"])
+def test_invalid_query_ports_are_rejected_before_starting_adb(client, port_name, port):
+ with patch("subprocess.run") as run:
+ response = client.post(
+ "/api/android/port-forward", params={"device_id": "emulator-5554", port_name: port}
+ )
+
+ assert response.status_code == 422
+ run.assert_not_called()
+
+
[email protected]("device_id", ["--help", "serial\n", "A" * 65, None, 123])
+async def test_direct_calls_cannot_bypass_serial_validation(device_id):
+ with patch("subprocess.run") as run:
+ with pytest.raises(HTTPException) as error:
+ await setup_port_forwarding(device_id=device_id, local_port=8888, device_port=8888)
+
+ assert error.value.status_code == 422
+ run.assert_not_called()
+
+
[email protected]("port_name", ["local_port", "device_port"])
[email protected]("port", [1023, 65536, "8888", 8888.0, True, None])
+async def test_direct_calls_cannot_bypass_port_validation(port_name, port):
+ parameters = {"device_id": "emulator-5554", "local_port": 8888, "device_port": 8888}
+ parameters[port_name] = port
+ with patch("subprocess.run") as run:
+ with pytest.raises(HTTPException) as error:
+ await setup_port_forwarding(**parameters)
+
+ assert error.value.status_code == 422
+ run.assert_not_called()
+
+
+ "completed,expected_error",
+ [
+ (_completed(returncode=1, stderr=" device unavailable\n"), "device unavailable"),
+ (_completed(returncode=1, stdout=" adb server unavailable\n"), "adb server unavailable"),
+ ],
+)
+def test_adb_failures_keep_existing_error_contract(client, completed, expected_error):
+ with patch("subprocess.run", return_value=completed):
+ response = client.post("/api/android/port-forward", params={"device_id": "emulator-5554"})
+
+ assert response.status_code == 200
+ assert response.json() == {"success": False, "error": expected_error}
+
+
+ "exception,expected_error",
+ [
+ (FileNotFoundError(), "ADB not found. Please install Android SDK Platform Tools"),
+ (subprocess.TimeoutExpired(cmd=["adb"], timeout=5), "Port forwarding failed"),
+ (RuntimeError("internal subprocess details"), "Port forwarding failed"),
+ ],
+)
+def test_subprocess_exceptions_return_safe_error_contract(client, exception, expected_error):
+ with patch("subprocess.run", side_effect=exception):
+ response = client.post("/api/android/port-forward", params={"device_id": "emulator-5554"})
+
+ assert response.status_code == 200
+ assert response.json() == {"success": False, "error": expected_error}
+
+
+def test_adb_environment_excludes_onepassword_bootstrap_credentials(client, monkeypatch):
+ monkeypatch.setenv("OP_SERVICE_ACCOUNT_TOKEN", "private-test-token")
+ monkeypatch.setenv("OP_CONNECT_TOKEN", "private-connect-token")
+ monkeypatch.setenv("op_test_sensitive", "private-lowercase-token")
+ monkeypatch.setenv("ANDROID_TEST_VISIBLE", "ordinary-setting")
+ with patch("subprocess.run", return_value=_completed()) as run:
+ response = client.post("/api/android/port-forward", params={"device_id": "emulator-5554"})
+
+ assert response.json()["success"] is True
+ environment = run.call_args.kwargs["env"]
+ assert environment["ANDROID_TEST_VISIBLE"] == "ordinary-setting"
+ assert all(not key.upper().startswith("OP_") for key in environment)