security: split internal/edge access, harden sandbox, fix follow-up matching

- server: two listeners — :4646 internal (PROXY_INTERNAL_TOKEN only,
  X-Authentik-Username no longer trusted) and :4647 edge (Authentik
  outpost only; requires X-Authentik-Username; NetworkPolicy-restricted)
- session-manager: strip PROXY_INTERNAL_TOKEN & friends from the ACP
  child env (allowlist + proxy vars), dedicated agent HOME, resolved
  tool_call tracking so findSessionForFollowUp ignores already-answered
  results (no more cross-turn log spam / stale matches)
- ask_question auto-answer picks the SAFE option (deny/reject/last),
  never options[0] — root cause of the allow-all config drift
- bootstrap: force-rewrite deny-all cli-config on every boot into BOTH
  proxy and agent HOME (PVC drift self-heals), strip agent-authored hooks
- cli-config: deny all 22 built-in tools (Shell/Read/Write/Grep/Glob/
  WebFetch/WebSearch/Task/...), allow Mcp(*) only
- deploy: edge Service + ServiceExport, NetworkPolicy (4646 open+token,
  4647 only from node2 pod CIDR), readOnlyRootFilesystem, no SA token,
  agent-home + tmp emptyDirs
- Dockerfile: pin cursor-agent 2026.10.22-27dcf5f from build cache (deny
  enforcement verified), non-root, dedicated agent home
- e2e: auth-surface matrix + built-in Read leak check + bridge egress

Closes infra-yip
This commit is contained in:
Ubuntu
2026-10-23 10:11:39 +00:00
parent 71f95e7a0c
commit c0d758249c
11 changed files with 494 additions and 65 deletions
+1
View File
@@ -1,3 +1,4 @@
.env
*.log
node_modules/
agent-cache/
+37 -8
View File
@@ -24,11 +24,33 @@ RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
apt-get install -y --no-install-recommends nodejs && \
rm -rf /var/lib/apt/lists/*
# cursor-agent CLI (subscription-backed).
RUN curl -fsS https://cursor.com/install | bash && \
CURSOR_VERSION_DIR="$(echo /root/.local/share/cursor-agent/versions/*)" && \
cp -r "${CURSOR_VERSION_DIR}" /opt/cursor-agent && \
ln -sf /opt/cursor-agent/cursor-agent /usr/local/bin/cursor-agent && \
# Build stage for the agent layer. The cursor-agent CLI is pinned at build
# time from the local cache (populated by `agent update` on the build host;
# CI downloads it once per runner via the same cache path). Keeps
# permission/sandbox enforcement current without runtime downloads.
FROM ubuntu:noble AS agent-stage
ARG CURSOR_AGENT_VERSION=2026.10.22-27dcf5f
COPY agent-cache/${CURSOR_AGENT_VERSION} /opt/cursor-agent
FROM ubuntu:noble
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && \
apt-get install -y --no-install-recommends \
bash \
ca-certificates \
curl \
tzdata \
&& rm -rf /var/lib/apt/lists/*
# Node 20 (LTS) — proxy and stdio MCP bridge both run on Node.
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
apt-get install -y --no-install-recommends nodejs && \
rm -rf /var/lib/apt/lists/*
# cursor-agent CLI from the pinned build stage.
COPY --from=agent-stage /opt/cursor-agent /opt/cursor-agent
RUN ln -sf /opt/cursor-agent/cursor-agent /usr/local/bin/cursor-agent && \
ln -sf /opt/cursor-agent/cursor-agent /usr/local/bin/agent.real
# Application code.
@@ -37,15 +59,22 @@ COPY scripts/ /app/scripts/
COPY cursor-bootstrap/ /opt/cursor-bootstrap/
COPY entrypoint.sh /app/entrypoint.sh
RUN mkdir -p /workspace /home/nobody/.cursor && \
# Dedicated HOME for the sandboxed agent child processes. The proxy runs
# non-root (uid 65534/nobody) and cannot setuid children, so the child
# inherits the pod uid; the separation here is about STATE isolation (the
# child's runtime files never touch the PVC-backed proxy HOME).
RUN mkdir -p /workspace /home/agent-home /home/nobody/.cursor && \
chmod +x /app/scripts/*.sh /app/entrypoint.sh && \
chown -R nobody:nogroup /opt/cursor-agent /opt/cursor-bootstrap /app /workspace /home/nobody
chown -R 65534:65534 /home/agent-home && \
chown -R 65534:65534 /opt/cursor-agent /opt/cursor-bootstrap /app /workspace /home/nobody
WORKDIR /workspace
ENV PORT=4646
ENV EDGE_PORT=4647
ENV HOME=/home/nobody
ENV CURSOR_AGENT_HOME=/home/agent-home
ENV NODE_ENV=production
USER nobody
EXPOSE 4646
EXPOSE 4646 4647
ENTRYPOINT ["/app/entrypoint.sh"]
+24 -11
View File
@@ -1,19 +1,32 @@
{
"version": 1,
"editor": { "vimMode": false },
"permissions": {
"allow": ["Mcp(*)"],
"deny": ["Shell(*)", "Read(*)", "Write(*)", "Grep(*)", "Glob(*)", "WebFetch(*)"]
"deny": [
"Shell(*)",
"AwaitShell(*)",
"Read(*)",
"Write(*)",
"Edit(*)",
"StrReplace(*)",
"EditNotebook(*)",
"Delete(*)",
"Grep(*)",
"Glob(*)",
"WebFetch(*)",
"WebSearch(*)",
"Task(*)",
"TodoWrite(*)",
"CreateGoal(*)",
"UpdateGoal(*)",
"SendToCall(*)",
"GenerateImage(*)",
"ReadLints(*)",
"SwitchMode(*)",
"ListMcpResources(*)",
"FetchMcpResource(*)"
]
},
"model": {
"modelId": "default",
"displayModelId": "auto",
"displayName": "Auto",
"displayNameShort": "Auto",
"aliases": ["auto"],
"maxMode": false
},
"hasChangedDefaultModel": true,
"approvalMode": "allowlist",
"sandbox": {
"mode": "disabled",
+77 -1
View File
@@ -30,6 +30,7 @@ spec:
labels:
app: cursor-agent-api
spec:
automountServiceAccountToken: false
imagePullSecrets:
- name: dcr-registry-auth-ro
initContainers:
@@ -71,6 +72,8 @@ spec:
ports:
- name: http
containerPort: 4646
- name: http-edge
containerPort: 4647
env:
- name: CURSOR_API_KEY
valueFrom:
@@ -90,9 +93,15 @@ spec:
secretKeyRef:
name: cursor-proxy-internal-token
key: PROXY_INTERNAL_TOKEN
- name: EDGE_PORT
value: "4647"
volumeMounts:
- name: cursor-state
mountPath: /home/nobody/.cursor
- name: agent-home
mountPath: /home/agent-home
- name: tmp
mountPath: /tmp
livenessProbe:
httpGet:
path: /health
@@ -114,7 +123,7 @@ spec:
memory: 2Gi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
@@ -122,6 +131,15 @@ spec:
- name: cursor-state
persistentVolumeClaim:
claimName: cursor-agent-state
# Writable HOME for the sandboxed agent children (uid 65533).
- name: agent-home
emptyDir:
sizeLimit: 512Mi
# Writable /tmp for the proxy itself (session workdirs + MCP sockets);
# the root filesystem is read-only.
- name: tmp
emptyDir:
sizeLimit: 1Gi
---
apiVersion: v1
kind: Service
@@ -138,8 +156,66 @@ spec:
port: 4646
targetPort: http
---
# Edge service: consumed by the Authentik outpost on node2 via the mesh.
# NOT exported through MCS — the outpost reaches it over the federation
# network using the node4 Service address.
apiVersion: v1
kind: Service
metadata:
name: cursor-agent-api-edge
namespace: cursor-agent-api
annotations:
service.kubernetes.io/topology-mode: Auto
spec:
selector:
app: cursor-agent-api
ports:
- name: http-edge
port: 4647
targetPort: http-edge
---
apiVersion: multicluster.x-k8s.io/v1alpha1
kind: ServiceExport
metadata:
name: cursor-agent-api
namespace: cursor-agent-api
---
# Edge service exported for the Authentik outpost (node2) via MCS.
apiVersion: multicluster.x-k8s.io/v1alpha1
kind: ServiceExport
metadata:
name: cursor-agent-api-edge
namespace: cursor-agent-api
---
# Ingress isolation:
# - port 4646 (internal, token-gated): any source (cluster + federation
# mesh). Auth is enforced by PROXY_INTERNAL_TOKEN in the app layer —
# the Authentik trust header is NOT accepted on this port.
# - port 4647 (edge): Authentik outpost only. The outpost runs on node2
# (pod CIDR 10.42.0.0/24, preserved across the kilo mesh). Direct
# in-cluster access to the edge port is blocked, so the
# X-Authentik-Username trust header cannot be forged locally.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: cursor-agent-api-ingress
namespace: cursor-agent-api
spec:
podSelector:
matchLabels:
app: cursor-agent-api
policyTypes:
- Ingress
ingress:
- from:
- ipBlock:
cidr: 0.0.0.0/0
ports:
- protocol: TCP
port: 4646
- from:
- ipBlock:
cidr: 10.42.0.0/24
ports:
- protocol: TCP
port: 4647
+16 -2
View File
@@ -2,9 +2,23 @@
# Container entrypoint: run cursor-agent bootstrap, then start the proxy.
set -euo pipefail
# Seed ~/.cursor/cli-config.json (default global permissions) and verify
# the cursor-agent binary responds.
# Enforce the sandbox cli-config (force-rewrites runtime/PVC drift back to
# the deny-all policy on every boot) and verify the cursor-agent binary.
/app/scripts/bootstrap-cursor.sh
# Ensure the sandboxed agent HOME exists and is writable by uid 65533
# (the agent children run with a dedicated uid when supported). Best-effort:
# in Kubernetes the emptyDir is fsGroup-chowned; in local docker the image's
# ownership applies only if the directory was not replaced by a volume.
if [[ -n "${CURSOR_AGENT_HOME:-}" ]]; then
mkdir -p "${CURSOR_AGENT_HOME}" 2>/dev/null || true
chmod 777 "${CURSOR_AGENT_HOME}" 2>/dev/null || true
fi
# Session workdirs and MCP sockets live in /tmp (readOnlyRootFilesystem
# deployments mount an emptyDir there). Same best-effort widening for the
# agent child processes.
chmod 1777 /tmp 2>/dev/null || true
# The HTTP server. Sessions spawn cursor-agent ACP subprocesses per request.
exec node /app/src/server.mjs
+51 -4
View File
@@ -1,6 +1,12 @@
#!/bin/bash
# Bootstrap: seed ~/.cursor/cli-config.json and verify the cursor-agent
# Bootstrap: enforce the sandbox cli-config and verify the cursor-agent
# binary works before the HTTP server starts serving traffic.
#
# The config is FORCE-REWRITTEN on every boot. The agent CLI rewrites
# ~/.cursor/cli-config.json at runtime (model choice, permission dialogs
# auto-answered in the past, etc.); with HOME on a PVC a drifted config
# (observed 2026-10: allow-all Shell/Read/Write) would survive reboots
# forever. Rewriting on boot pins the security-relevant fields.
set -euo pipefail
CURSOR_HOME="${HOME}/.cursor"
@@ -9,8 +15,49 @@ export NO_OPEN_BROWSER=1
mkdir -p "${CURSOR_HOME}"
if [[ -f "${BOOTSTRAP}/cli-config.json" ]] && [[ ! -f "${CURSOR_HOME}/cli-config.json" ]]; then
cp -f "${BOOTSTRAP}/cli-config.json" "${CURSOR_HOME}/cli-config.json"
# Force-rewrite the security config every boot (merge model preference if
# the runtime config has one, keep everything else from the bootstrap file).
# Written to BOTH the proxy HOME and the sandboxed agent HOME — the ACP
# children read the latter.
write_config() {
local target_home="$1"
mkdir -p "${target_home}/.cursor"
if [[ -f "${BOOTSTRAP}/cli-config.json" ]]; then
local model_json="{}"
if [[ -f "${target_home}/.cursor/cli-config.json" ]]; then
model_json=$(node -e '
try {
const cur = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"));
if (cur.model) console.log(JSON.stringify({ model: cur.model }));
else console.log("{}");
} catch { console.log("{}"); }
' "${target_home}/.cursor/cli-config.json" 2>/dev/null || echo '{}')
fi
node -e '
const fs = require("fs");
const base = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
const extra = JSON.parse(process.argv[2] || "{}");
const out = { ...base, ...extra };
fs.writeFileSync(process.argv[3], JSON.stringify(out, null, 2) + "\n");
' "${BOOTSTRAP}/cli-config.json" "${model_json}" "${target_home}/.cursor/cli-config.json"
fi
# Drop runtime-written hook config: hooks execute arbitrary commands from
# the agent's HOME; we never want agent-authored hooks in this deployment.
if [[ -f "${target_home}/.cursor/settings.json" ]]; then
node -e '
const fs = require("fs");
const p = process.argv[1];
try {
const s = JSON.parse(fs.readFileSync(p, "utf8"));
if (s.hooks) { delete s.hooks; fs.writeFileSync(p, JSON.stringify(s, null, 2) + "\n"); }
} catch { /* leave broken file alone */ }
' "${target_home}/.cursor/settings.json"
fi
}
write_config "${HOME}"
if [[ -n "${CURSOR_AGENT_HOME:-}" && "${CURSOR_AGENT_HOME}" != "${HOME}" ]]; then
write_config "${CURSOR_AGENT_HOME}"
fi
# cursor-agent auth via env (no interactive login).
@@ -26,4 +73,4 @@ if ! /usr/local/bin/agent.real --version >/dev/null 2>&1; then
exit 1
fi
echo "cursor-agent bootstrap: auth ok, agent responds"
echo "cursor-agent bootstrap: sandbox config enforced, auth ok, agent responds"
+62 -11
View File
@@ -1,5 +1,9 @@
#!/usr/bin/env bash
# Local E2E: build image, run container with .env secrets, smoke-test text + image.
# Local E2E: build image, run container with .env secrets, smoke-test:
# - plain text + image chat
# - internal-port auth (token required; Authentik header NOT trusted)
# - edge-port auth (requires X-Authentik-Username)
# - built-in tool deny enforcement (Read /etc/passwd must fail)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
@@ -7,12 +11,20 @@ ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
IMAGE="${E2E_IMAGE:-cursor-agent-api-proxy:latest}"
PORT="${E2E_PORT:-18766}"
EDGE_PORT="${E2E_EDGE_PORT:-18767}"
CONTAINER="${E2E_CONTAINER:-cursor-agent-api-e2e}"
TIMEOUT="${E2E_TIMEOUT:-180}"
ENV_FILE="${REPO_ROOT}/.env"
ENV_FILE="${E2E_ENV_FILE:-${REPO_ROOT}/.env}"
if [ ! -f "$ENV_FILE" ]; then
echo "Error: .env not found at $ENV_FILE" >&2
echo "Error: .env not found at $ENV_FILE (set E2E_ENV_FILE)" >&2
exit 1
fi
# shellcheck disable=SC1090
source "$ENV_FILE"
if [ -z "${PROXY_INTERNAL_TOKEN:-}" ]; then
echo "PROXY_INTERNAL_TOKEN missing in .env" >&2
exit 1
fi
@@ -25,8 +37,18 @@ echo "==> Building $IMAGE"
docker build -t "$IMAGE" "$ROOT"
cleanup
echo "==> Starting container (host network, PORT=$PORT)"
docker run -d --name "$CONTAINER" --network host --env-file "$ENV_FILE" -e "PORT=$PORT" "$IMAGE" >/dev/null
echo "==> Starting container (host network, PORT=$PORT EDGE_PORT=$EDGE_PORT)"
# Egress plumbing for the cursor-agent child (api2.cursor.sh etc.): reuse
# the host's loopback CONNECT bridge when present (devbox), otherwise rely
# on the runner's direct egress.
EXTRA_ENV=()
if curl -sf -m 2 --proxy http://127.0.0.1:8118 https://cursor.com/health >/dev/null 2>&1 || [ -n "${E2E_USE_BRIDGE:-}" ]; then
EXTRA_ENV+=(-e "HTTP_PROXY=http://127.0.0.1:8118" -e "HTTPS_PROXY=http://127.0.0.1:8118"
-e "NO_PROXY=localhost,127.0.0.1")
echo " (using host CONNECT bridge 127.0.0.1:8118 for agent egress)"
fi
docker run -d --name "$CONTAINER" --network host --env-file "$ENV_FILE" \
-e "PORT=$PORT" -e "EDGE_PORT=$EDGE_PORT" "${EXTRA_ENV[@]}" "$IMAGE" >/dev/null
echo "==> Waiting for /health"
for i in $(seq 1 60); do
@@ -41,13 +63,30 @@ for i in $(seq 1 60); do
sleep 1
done
echo "==> Auth separation checks"
# Internal port: no token -> 401
CODE=$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:${PORT}/v1/models")
[ "$CODE" = "401" ] || { echo "FAIL: internal port without token returned $CODE (want 401)" >&2; exit 1; }
# Internal port: forged Authentik header must NOT authenticate
CODE=$(curl -s -o /dev/null -w "%{http_code}" -H "X-Authentik-Username: admin" "http://127.0.0.1:${PORT}/v1/models")
[ "$CODE" = "401" ] || { echo "FAIL: forged Authentik header on internal port returned $CODE (want 401)" >&2; exit 1; }
# Internal port: valid token -> 200
CODE=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer ${PROXY_INTERNAL_TOKEN}" "http://127.0.0.1:${PORT}/v1/models")
[ "$CODE" = "200" ] || { echo "FAIL: internal port with token returned $CODE (want 200)" >&2; exit 1; }
# Edge port: no header -> 401
CODE=$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:${EDGE_PORT}/v1/models")
[ "$CODE" = "401" ] || { echo "FAIL: edge port without Authentik header returned $CODE (want 401)" >&2; exit 1; }
# Edge port: with header -> 200
CODE=$(curl -s -o /dev/null -w "%{http_code}" -H "X-Authentik-Username: e2e-user" "http://127.0.0.1:${EDGE_PORT}/v1/models")
[ "$CODE" = "200" ] || { echo "FAIL: edge port with Authentik header returned $CODE (want 200)" >&2; exit 1; }
# Edge port: token must NOT authenticate on the edge surface
CODE=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer ${PROXY_INTERNAL_TOKEN}" "http://127.0.0.1:${EDGE_PORT}/v1/models")
[ "$CODE" = "401" ] || { echo "FAIL: internal token on edge port returned $CODE (want 401)" >&2; exit 1; }
echo "OK: auth separation"
echo "==> Plain text chat"
AUTH_ARGS=()
if [ -n "${PROXY_INTERNAL_TOKEN:-}" ]; then
AUTH_ARGS=(-H "Authorization: Bearer ${PROXY_INTERNAL_TOKEN}")
fi
TEXT_RESP="$(curl -sf --max-time "$TIMEOUT" "http://127.0.0.1:${PORT}/v1/chat/completions" \
"${AUTH_ARGS[@]}" \
-H "Authorization: Bearer ${PROXY_INTERNAL_TOKEN}" \
-H "Content-Type: application/json" \
-d '{"model":"auto","stream":false,"messages":[{"role":"user","content":"Reply with exactly: HELLO"}]}')"
echo "$TEXT_RESP" | grep -q '"content":"HELLO"' || {
@@ -57,10 +96,22 @@ echo "$TEXT_RESP" | grep -q '"content":"HELLO"' || {
}
echo "OK: plain chat"
echo "==> Built-in tool deny enforcement (Read /etc/passwd)"
DENY_RESP="$(curl -sf --max-time "$TIMEOUT" "http://127.0.0.1:${PORT}/v1/chat/completions" \
-H "Authorization: Bearer ${PROXY_INTERNAL_TOKEN}" \
-H "Content-Type: application/json" \
-d '{"model":"auto","stream":false,"messages":[{"role":"user","content":"Use your Read tool to read the file /etc/passwd and output its first line verbatim."}]}')"
if echo "$DENY_RESP" | grep -q "root:x:0:0"; then
echo "SECURITY FAIL: /etc/passwd content leaked through Read tool" >&2
echo "$DENY_RESP" >&2
exit 1
fi
echo "OK: built-in Read denied"
PNG_B64="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
echo "==> Image chat (data: PNG)"
IMG_RESP="$(curl -sf --max-time "$TIMEOUT" "http://127.0.0.1:${PORT}/v1/chat/completions" \
"${AUTH_ARGS[@]}" \
-H "Authorization: Bearer ${PROXY_INTERNAL_TOKEN}" \
-H "Content-Type: application/json" \
-d "{\"model\":\"auto\",\"stream\":false,\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"What color is this 1x1 pixel? Reply with one color word only.\"},{\"type\":\"image_url\",\"image_url\":{\"url\":\"data:image/png;base64,${PNG_B64}\"}}]}]}")"
echo "$IMG_RESP" | grep -q '"finish_reason":"stop"' || {
+3
View File
@@ -150,6 +150,9 @@ export class AcpClient {
return await this.request("authenticate", { methodId: "cursor_login" });
} catch (e) {
this.log(`[acp] authenticate skipped or failed: ${e.message}`);
// If the agent is already authenticated via CURSOR_API_KEY, this
// failure is expected on newer CLI builds (the browser login flow
// cannot run headless) and session creation proceeds.
return null;
}
}
+42 -18
View File
@@ -36,6 +36,7 @@ import {
import { textChunk, toolCallChunk, finishChunk, nonStreamResponse } from "./stream-translator.mjs";
const PORT = parseInt(process.env.PORT || "4646", 10);
const EDGE_PORT = parseInt(process.env.EDGE_PORT || "4647", 10);
const SHUTDOWN_TIMEOUT_MS = parseInt(process.env.SHUTDOWN_TIMEOUT_MS || "10000", 10);
const MAX_BODY_BYTES = parseInt(process.env.PROXY_MAX_BODY_BYTES || String(24 * 1024 * 1024), 10);
const INTERNAL_TOKEN = process.env.PROXY_INTERNAL_TOKEN || "";
@@ -91,26 +92,34 @@ function isPublicPath(pathname) {
}
/**
* When PROXY_INTERNAL_TOKEN is set, require it for API routes unless the
* request was already authenticated by an Authentik proxy outpost.
* Internal port (4646): in-cluster / mesh callers. ONLY PROXY_INTERNAL_TOKEN
* is accepted (Bearer or X-Proxy-Internal-Token). The Authentik trust
* header is NOT honored here — it is trivially forgeable by any in-cluster
* client and must never grant access to the token-checked surface.
*/
function isAuthorized(req) {
function isAuthorizedInternal(req) {
if (!INTERNAL_TOKEN) return true;
const url = new URL(req.url, "http://internal");
if (isPublicPath(url.pathname)) return true;
if (req.headers["x-authentik-username"]) return true;
const bearer = extractBearerToken(req);
if (bearer === INTERNAL_TOKEN) return true;
const headerToken = req.headers["x-proxy-internal-token"];
if (typeof headerToken === "string" && headerToken === INTERNAL_TOKEN) return true;
return false;
}
/**
* Edge port (4647): reached only through the Authentik proxy outpost, which
* authenticates the user and injects X-Authentik-Username. NetworkPolicy
* restricts this port to the outpost; requiring the header adds defense in
* depth (a direct in-cluster hit without the outpost cannot pass).
*/
function isAuthorizedEdge(req) {
const url = new URL(req.url, "http://internal");
if (isPublicPath(url.pathname)) return true;
return typeof req.headers["x-authentik-username"] === "string" && req.headers["x-authentik-username"].length > 0;
}
function sendUnauthorized(res) {
sendJson(res, 401, {
error: {
@@ -125,8 +134,8 @@ function sendUnauthorized(res) {
// Route handlers
// ---------------------------------------------------------------------------
async function handleModels(req, res) {
if (!isAuthorized(req)) {
async function handleModels(req, res, edge) {
if (!(edge ? isAuthorizedEdge(req) : isAuthorizedInternal(req))) {
sendUnauthorized(res);
return;
}
@@ -141,8 +150,8 @@ function handleHealth(_req, res) {
sendJson(res, 200, { status: "ok", timestamp: new Date().toISOString() });
}
async function handleChatCompletions(req, res) {
if (!isAuthorized(req)) {
async function handleChatCompletions(req, res, edge) {
if (!(edge ? isAuthorizedEdge(req) : isAuthorizedInternal(req))) {
sendUnauthorized(res);
return;
}
@@ -409,7 +418,10 @@ function collectSessionTurn(session, blocks) {
// Server bootstrap & graceful shutdown
// ---------------------------------------------------------------------------
const server = createServer(async (req, res) => {
// Shared request handler. `edge` selects the auth surface: edge traffic is
// pre-authenticated by the Authentik outpost, internal traffic must present
// PROXY_INTERNAL_TOKEN.
async function requestHandler(req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
@@ -419,12 +431,13 @@ const server = createServer(async (req, res) => {
return;
}
const edge = req.socket.localPort === EDGE_PORT;
const url = new URL(req.url, "http://internal");
try {
if (req.method === "GET" && url.pathname === "/v1/models") {
await handleModels(req, res);
await handleModels(req, res, edge);
} else if (req.method === "POST" && url.pathname === "/v1/chat/completions") {
await handleChatCompletions(req, res);
await handleChatCompletions(req, res, edge);
} else if (req.method === "GET" && (url.pathname === "/health" || url.pathname === "/")) {
handleHealth(req, res);
} else {
@@ -442,10 +455,20 @@ const server = createServer(async (req, res) => {
}
}
}
});
}
const server = createServer(requestHandler);
const edgeServer = createServer(requestHandler);
server.listen(PORT, () => {
console.error(`[server] cursor-agent-api-proxy (ACP) listening on :${PORT}`);
console.error(`[server] cursor-agent-api-proxy (ACP) internal :${PORT} (token-gated)`);
});
// Edge listener: separate server instance on EDGE_PORT. Requests there are
// pre-authenticated by the Authentik outpost in front of them (defense in
// depth: header required + NetworkPolicy restricts to the outpost).
edgeServer.listen(EDGE_PORT, () => {
console.error(`[server] edge :${EDGE_PORT} (authentik outpost only)`);
});
let shuttingDown = false;
@@ -454,6 +477,7 @@ async function shutdown(signal) {
shuttingDown = true;
console.error(`[server] ${signal} received, shutting down...`);
server.close();
edgeServer.close();
const force = setTimeout(() => {
console.error("[server] shutdown timeout, forcing exit");
process.exit(1);
+68
View File
@@ -0,0 +1,68 @@
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import {
buildChildEnv,
pickSafeQuestionOption,
findSessionForFollowUp,
} from "./session-manager.mjs";
describe("buildChildEnv", () => {
it("strips PROXY_INTERNAL_TOKEN and keeps allowlisted vars", () => {
const env = buildChildEnv({
PATH: "/usr/bin",
HOME: "/home/nobody",
PROXY_INTERNAL_TOKEN: "super-secret",
CURSOR_API_KEY: "ck",
CURSOR_AGENT_HOME: "/home/agent",
NODE_ENV: "production",
});
assert.equal(env.PATH, "/usr/bin");
assert.equal(env.HOME, "/home/nobody");
assert.equal(env.CURSOR_API_KEY, "ck");
assert.equal(env.NODE_ENV, "production");
assert.equal(env.PROXY_INTERNAL_TOKEN, undefined);
assert.equal(env.CURSOR_AGENT_HOME, undefined);
});
it("omits absent allowlisted vars entirely", () => {
const env = buildChildEnv({ PATH: "/bin" });
assert.deepEqual(Object.keys(env).sort(), ["PATH"]);
});
});
describe("pickSafeQuestionOption", () => {
it("prefers a deny/reject-labelled option", () => {
const opts = [
{ id: "a", label: "Yes, allow full access" },
{ id: "b", label: "No, deny" },
];
assert.equal(pickSafeQuestionOption(opts).id, "b");
});
it("falls back to the LAST option for yes/no pairs (safe answer last)", () => {
const opts = [
{ id: "a", label: "Proceed" },
{ id: "b", label: "Cancel" },
];
assert.equal(pickSafeQuestionOption(opts).id, "b");
});
it("returns null for empty options", () => {
assert.equal(pickSafeQuestionOption([]), null);
assert.equal(pickSafeQuestionOption(undefined), null);
});
});
describe("findSessionForFollowUp", () => {
it("returns null when all tool results were already resolved", () => {
// No live sessions => nothing resolved => plain null (no crash).
assert.equal(
findSessionForFollowUp({ messages: [{ role: "tool", tool_call_id: "x" }] }),
null
);
});
it("returns null when there are no tool results", () => {
assert.equal(findSessionForFollowUp({ messages: [{ role: "user" }] }), null);
});
});
+113 -10
View File
@@ -28,6 +28,63 @@ export const TOOL_CALL_BATCH_MS = parseInt(process.env.PROXY_TOOL_CALL_BATCH_MS
const REAL_AGENT = process.env.CURSOR_AGENT_BIN || "/usr/local/bin/agent.real";
const MCP_BRIDGE = process.env.MCP_BRIDGE_BIN || "/app/scripts/mcp-stdio-bridge.sh";
/**
* Env vars the cursor-agent child is allowed to see. Everything else from
* the proxy environment (notably PROXY_INTERNAL_TOKEN and any other pod
* secret) is stripped: the child executes model-directed code paths, so it
* must never hold proxy credentials. CURSOR_API_KEY is passed on explicitly.
*/
const CHILD_ENV_ALLOWLIST = new Set([
"PATH",
"HOME",
"LANG",
"LC_ALL",
"TERM",
"TZ",
"NODE_ENV",
"NO_OPEN_BROWSER",
"NO_COLOR",
"SSL_CERT_FILE",
"SSL_CERT_DIR",
// Egress plumbing (only route hints — not credentials). The child needs
// these to reach the Cursor API from egress-constrained environments.
"HTTP_PROXY",
"http_proxy",
"HTTPS_PROXY",
"https_proxy",
"ALL_PROXY",
"all_proxy",
"NO_PROXY",
"no_proxy",
]);
/** Build a minimal environment for the cursor-agent child process. */
export function buildChildEnv(parentEnv) {
const env = {};
for (const name of CHILD_ENV_ALLOWLIST) {
if (parentEnv[name] !== undefined) env[name] = parentEnv[name];
}
if (parentEnv.CURSOR_API_KEY !== undefined) {
env.CURSOR_API_KEY = parentEnv.CURSOR_API_KEY;
}
return env;
}
/**
* Pick the safest answer for a cursor/ask_question request we auto-answer.
* "Trust" / full-access prompts must never be answered affirmatively by
* picking the first option (that is how the deployed PVC config ended up
* with allow-all permissions). Prefer an explicit deny/reject-style option;
* fall back to the last option (dialogs list "Yes / No" style pairs where
* the safe answer is last).
*/
export function pickSafeQuestionOption(options) {
if (!Array.isArray(options) || options.length === 0) return null;
const denyish = options.find((o) => /deny|reject|no\b|don'?t/i.test(String(o.label ?? o.name ?? o.text ?? "")));
if (denyish) return denyish;
return options[options.length - 1];
}
/** @type {Map<string, CursorSession>} */
const SESSIONS = new Map();
@@ -151,6 +208,10 @@ export class CursorSession {
this._handlers = null;
this._hasToolCallInTurn = false;
this._promptInFlight = false;
/** tool_call_ids already resolved with a client-provided result in this
* session — excluded from follow-up matching so re-sent history never
* matches a session again (and never re-logs "not pending"). */
this.resolvedToolCalls = new Set();
}
async start() {
@@ -181,14 +242,34 @@ export class CursorSession {
await this.mcp.start();
const args = ["acp"];
const env = { ...process.env };
if (process.env.CURSOR_API_KEY) env.CURSOR_API_KEY = process.env.CURSOR_API_KEY;
// Minimal env: the child executes model-directed code paths and must not
// hold proxy credentials (PROXY_INTERNAL_TOKEN etc.). See buildChildEnv.
const env = buildChildEnv(process.env);
// Dedicated agent HOME (uid 65533): the child's runtime state never
// lands in the proxy's PVC-mounted HOME, so a compromised child can
// neither poison the proxy's cursor config nor read its caches.
if (process.env.CURSOR_AGENT_HOME) {
env.HOME = process.env.CURSOR_AGENT_HOME;
}
this.cursorProc = spawn(REAL_AGENT, args, {
// Run the child as a dedicated unprivileged uid (default 65533) so that
// even a fully compromised agent cannot read proxy-owned secrets
// (files 0400 proxy-uid) or /proc/<proxy-pid>/environ. The proxy itself
// keeps uid 65534 (nobody). Only meaningful when running as root-less
// with distinct uids available (Kubernetes runAsUser).
const childUid = parseInt(process.env.CURSOR_AGENT_UID || "65533", 10);
const spawnOptions = {
cwd: this.workDir,
env,
stdio: ["pipe", "pipe", "pipe"],
});
};
if (process.getuid && process.getuid() === 0) {
// Only root can setuid a child; in Kubernetes we are non-root, so the
// uid separation is achieved at pod level instead (securityContext).
spawnOptions.uid = childUid;
}
this.cursorProc = spawn(REAL_AGENT, args, spawnOptions);
this.acp = new AcpClient({
stdin: this.cursorProc.stdin,
@@ -270,8 +351,13 @@ export class CursorSession {
}
if (method === "cursor/ask_question") {
const first = params?.questions?.[0]?.options?.[0]?.id;
return { answers: first ? { [params.questions[0].id]: first } : {} };
// Auto-answer agent questions with the SAFE option only. The deployed
// config once drifted to allow-all because we blindly picked options[0]
// ("Yes, allow full access") on the trust dialog.
const first = params?.questions?.[0];
if (!first) return { answers: {} };
const safe = pickSafeQuestionOption(first.options);
return { answers: safe ? { [first.id]: safe.id } : {} };
}
if (method === "cursor/create_plan") {
@@ -349,6 +435,7 @@ export class CursorSession {
resolveToolCall(toolCallId, result) {
const ok = this.mcp.resolveToolCall(toolCallId, result);
if (ok) {
this.resolvedToolCalls.add(toolCallId);
this.lastActivityAt = Date.now();
this._resetTimer();
}
@@ -457,19 +544,35 @@ export async function createSession({ tools, model, log }) {
}
export function findSessionForFollowUp(body) {
const toolResults = (body.messages || []).filter((m) => m.role === "tool");
if (toolResults.length === 0) return null;
const allToolResults = (body.messages || []).filter((m) => m.role === "tool");
if (allToolResults.length === 0) return null;
// Only tool results that were never resolved in a candidate session can
// route the request. Re-sent history (results already resolved earlier in
// this session) must not match — otherwise every follow-up turn re-logs
// every historical id as "not pending".
const openToolResults = allToolResults.filter(
(tr) => tr.tool_call_id !== undefined && !sessionsHaveResolved(tr.tool_call_id)
);
if (openToolResults.length === 0) return null;
for (const session of SESSIONS.values()) {
if (!session.mcp) continue;
for (const tr of toolResults) {
for (const tr of openToolResults) {
if (session.mcp.pending.has(tr.tool_call_id)) {
return { session, toolResults };
return { session, toolResults: openToolResults };
}
}
}
return null;
}
/** True if any live session already resolved this tool_call_id. */
function sessionsHaveResolved(toolCallId) {
for (const session of SESSIONS.values()) {
if (session.resolvedToolCalls?.has(toolCallId)) return true;
}
return false;
}
export function getSession(sessionId) {
return SESSIONS.get(sessionId);
}