Repository navigation
Conversation
…CP azp to close cross-tenant ATO Two vulnerabilities responsibly disclosed by Jemin Khunt and Hitarth Shah. Issue 1 (RCE, CVSS 9.9): settings.agentConfigs stored env keys unrestricted (z.record(z.string(), z.string())), and runTerminalAgent interpolated them into a PTY shell prefix via envOverlayPrefix (values quoted, keys not). A crafted key like 'FOO;curl$IFS...' executed arbitrary shell on any connected host. - Constrain env keys to POSIX identifiers at the tRPC boundary. - Defense in depth: thread agent env structurally into the PTY spawn env (buildV2TerminalEnv agentEnv / createTerminalSessionInternal extraEnv) instead of building a shell prefix, so keys never touch shell parsing. Issue 2 (cross-tenant ATO): the MCP OAuth bearer path verified JWTs by signature/issuer/audience only and ignored azp, so a victim-scoped token minted to an attacker-registered DCR client was accepted. Gate azp against the trusted client set in buildOAuthAuthInfo and at /api/auth/oauth2/userinfo, reusing a shared TRUSTED_API_CLIENTS helper (also now used by trpc/context.ts). Chat-session BOLA (#5017) is already fixed and out of scope.
|
Ready to review this PR? Stage has broken it down into 4 individual chapters for you: Chapters generated by Stage for commit 5fd55a1 on Jul 17, 2026 3:39pm UTC. |
📝 WalkthroughWalkthroughThe PR centralizes OAuth ChangesOAuth trust gates
Terminal environment overlays
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant OAuthClient
participant UserinfoRoute
participant TokenVerifier
participant TrustedClientCheck
participant BetterAuth
OAuthClient->>UserinfoRoute: GET or POST /oauth2/userinfo
UserinfoRoute->>TokenVerifier: verify bearer JWT using JWKS
TokenVerifier-->>UserinfoRoute: verified token payload
UserinfoRoute->>TrustedClientCheck: inspect azp claim
TrustedClientCheck-->>UserinfoRoute: trusted or untrusted
UserinfoRoute-->>OAuthClient: 401 for untrusted token
UserinfoRoute->>BetterAuth: forward trusted request
BetterAuth-->>OAuthClient: userinfo response
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
🚀 Preview Deployment🔗 Preview Links
Preview updates automatically with new commits |
Greptile SummaryThis PR patches two externally-disclosed vulnerabilities: shell injection via env-var keys in the host-service PTY launch path (fixed by structural env passing + POSIX key validation), and a cross-tenant ATO via un-gated
Confidence Score: 3/5The RCE and tRPC/MCP ATO fixes are correct and well-tested, but the userinfo pre-flight guard uses a narrower audience list than the MCP handler, leaving a narrow bypass path that should be closed before merging. Both core fixes are structurally sound and backed by targeted tests. The outstanding concern is in rejectsUntrustedUserInfo: the audience set used for pre-flight JWT verification excludes the MCP-specific audience accepted by the MCP handler, so a token carrying that audience with an untrusted azp would slip past the pre-flight catch {} path and reach Better Auth's native userinfo handler without azp validation. This is a one-line fix but represents an incomplete closure of the ATO attack surface the PR is specifically targeting. apps/api/src/app/api/auth/[...all]/route.ts — the pre-flight audience list in rejectsUntrustedUserInfo needs to include the MCP-specific audience to fully close the cross-tenant ATO path.
|
| Filename | Overview |
|---|---|
| apps/api/src/lib/trusted-clients.ts | New shared helper; extracts TRUSTED_API_CLIENTS set and isUntrustedAuthorizedParty predicate to eliminate duplication. Logic is correct. |
| apps/api/src/app/api/agent/[transport]/auth-flow.ts | Adds azp gate in buildOAuthAuthInfo via isUntrustedAuthorizedParty before any identity claims are used; correctly blocks cross-tenant ATO on the MCP surface. |
| apps/api/src/app/api/auth/[...all]/route.ts | Adds pre-flight azp check for /oauth2/userinfo; the audience list used for pre-flight verification is narrower than what the MCP handler accepts, creating a potential bypass path for tokens with an MCP-specific audience. |
| apps/api/src/trpc/context.ts | Removes the inline TRUSTED_API_CLIENTS Set and local azp check, replacing both with the shared isUntrustedAuthorizedParty helper. Behaviour is identical. |
| packages/host-service/src/trpc/router/settings/agent-configs.ts | Introduces envKeySchema with POSIX regex guard on env var names; comment describing the motivation references the old shell-prefix approach and contains a stale claim about shell-quoting values. |
| packages/host-service/src/trpc/router/agents/agents.ts | Removes envOverlayPrefix shell-string construction; agent env is now threaded structurally as extraEnv, eliminating the shell-injection vector. |
| packages/host-service/src/terminal/env.ts | Adds agentEnv parameter applied via Object.assign at the end of buildV2TerminalEnv; keys never touch shell parsing. |
| packages/host-service/src/terminal/terminal.ts | Adds extraEnv to CreateTerminalSessionOptions and threads it into buildV2TerminalEnv; clean structural pass-through. |
Sequence Diagram
%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant Attacker
participant UserInfoRoute as /api/auth/[...all]/route.ts
participant MCP as /api/agent/mcp (auth-flow.ts)
participant tRPC as tRPC context.ts
participant TrustedClients as trusted-clients.ts
participant BetterAuth as Better Auth handler
Note over Attacker,BetterAuth: Issue 2 — Cross-tenant ATO fix (azp gate)
Attacker->>UserInfoRoute: "Bearer token (azp=attacker-dcr-client)"
UserInfoRoute->>UserInfoRoute: rejectsUntrustedUserInfo()
UserInfoRoute->>TrustedClients: isUntrustedAuthorizedParty(payload)
TrustedClients-->>UserInfoRoute: true (azp not in TRUSTED_API_CLIENTS)
UserInfoRoute-->>Attacker: 401 Unauthorized
Attacker->>MCP: "Bearer token (azp=attacker-dcr-client)"
MCP->>MCP: verifyToken → buildOAuthAuthInfo()
MCP->>TrustedClients: isUntrustedAuthorizedParty(payload)
TrustedClients-->>MCP: true
MCP-->>Attacker: 401 Unauthorized
Attacker->>tRPC: "Bearer token (azp=attacker-dcr-client)"
tRPC->>TrustedClients: isUntrustedAuthorizedParty(payload)
TrustedClients-->>tRPC: true
tRPC-->>Attacker: null session → reject
Note over Attacker,BetterAuth: Issue 1 — RCE fix (structural env passing)
participant AgentRouter as agents.ts (runTerminalAgent)
participant Terminal as createTerminalSessionInternal
participant Env as buildV2TerminalEnv
participant PTY as node-pty
AgentRouter->>AgentRouter: "agentEnv = config.env + modelEnv (no shell prefix)"
AgentRouter->>Terminal: "extraEnv=agentEnv"
Terminal->>Env: agentEnv parameter
Env->>Env: Object.assign(env, agentEnv)
Env-->>PTY: structured env map (keys never shell-parsed)
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant Attacker
participant UserInfoRoute as /api/auth/[...all]/route.ts
participant MCP as /api/agent/mcp (auth-flow.ts)
participant tRPC as tRPC context.ts
participant TrustedClients as trusted-clients.ts
participant BetterAuth as Better Auth handler
Note over Attacker,BetterAuth: Issue 2 — Cross-tenant ATO fix (azp gate)
Attacker->>UserInfoRoute: "Bearer token (azp=attacker-dcr-client)"
UserInfoRoute->>UserInfoRoute: rejectsUntrustedUserInfo()
UserInfoRoute->>TrustedClients: isUntrustedAuthorizedParty(payload)
TrustedClients-->>UserInfoRoute: true (azp not in TRUSTED_API_CLIENTS)
UserInfoRoute-->>Attacker: 401 Unauthorized
Attacker->>MCP: "Bearer token (azp=attacker-dcr-client)"
MCP->>MCP: verifyToken → buildOAuthAuthInfo()
MCP->>TrustedClients: isUntrustedAuthorizedParty(payload)
TrustedClients-->>MCP: true
MCP-->>Attacker: 401 Unauthorized
Attacker->>tRPC: "Bearer token (azp=attacker-dcr-client)"
tRPC->>TrustedClients: isUntrustedAuthorizedParty(payload)
TrustedClients-->>tRPC: true
tRPC-->>Attacker: null session → reject
Note over Attacker,BetterAuth: Issue 1 — RCE fix (structural env passing)
participant AgentRouter as agents.ts (runTerminalAgent)
participant Terminal as createTerminalSessionInternal
participant Env as buildV2TerminalEnv
participant PTY as node-pty
AgentRouter->>AgentRouter: "agentEnv = config.env + modelEnv (no shell prefix)"
AgentRouter->>Terminal: "extraEnv=agentEnv"
Terminal->>Env: agentEnv parameter
Env->>Env: Object.assign(env, agentEnv)
Env-->>PTY: structured env map (keys never shell-parsed)
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 2
apps/api/src/app/api/auth/[...all]/route.ts:24-30
The audience list in `rejectsUntrustedUserInfo` is narrower than what the MCP auth handler accepts. When `verifyAccessToken` throws an audience-mismatch error (e.g. for a token issued with audience `${apiUrl}/api/agent/mcp` only), the `catch {}` block returns `false` and the request falls through to Better Auth's own handler — which does not validate `azp`. An attacker who can obtain a victim-scoped DCR token with that audience would bypass this guard entirely. Adding the MCP-specific audience here closes the gap.
```suggestion
const payload = (await verifyAccessToken(token, {
jwksUrl: `${apiUrl}/api/auth/jwks`,
verifyOptions: {
issuer: apiUrl,
audience: [apiUrl, `${apiUrl}/`, `${apiUrl}/api/agent/mcp`],
},
})) as Record<string, unknown>;
```
### Issue 2 of 2
packages/host-service/src/trpc/router/settings/agent-configs.ts:17-20
The comment says "values are still shell-quoted at the launch site," but `agents.ts` no longer builds a shell-prefix string — values are passed structurally via `extraEnv` and never reach a shell parser. This stale claim contradicts the defence-in-depth rationale and could mislead a future reviewer into thinking shell-quoting is still the primary mitigation.
```suggestion
// Env keys are validated as POSIX identifiers for defence in depth: even
// though agent env is now passed structurally into the PTY (no shell
// interpolation), rejecting non-identifier keys at the boundary prevents
// accidental regressions if the launch path ever reverts to a shell prefix.
const envKeySchema = z
```
Reviews (1): Last reviewed commit: "fix(security): validate env keys to clos..." | Re-trigger Greptile
| const payload = (await verifyAccessToken(token, { | ||
| jwksUrl: `${apiUrl}/api/auth/jwks`, | ||
| verifyOptions: { | ||
| issuer: apiUrl, | ||
| audience: [apiUrl, `${apiUrl}/`], | ||
| }, | ||
| })) as Record<string, unknown>; |
There was a problem hiding this comment.
The audience list in
rejectsUntrustedUserInfo is narrower than what the MCP auth handler accepts. When verifyAccessToken throws an audience-mismatch error (e.g. for a token issued with audience ${apiUrl}/api/agent/mcp only), the catch {} block returns false and the request falls through to Better Auth's own handler — which does not validate azp. An attacker who can obtain a victim-scoped DCR token with that audience would bypass this guard entirely. Adding the MCP-specific audience here closes the gap.
| const payload = (await verifyAccessToken(token, { | |
| jwksUrl: `${apiUrl}/api/auth/jwks`, | |
| verifyOptions: { | |
| issuer: apiUrl, | |
| audience: [apiUrl, `${apiUrl}/`], | |
| }, | |
| })) as Record<string, unknown>; | |
| const payload = (await verifyAccessToken(token, { | |
| jwksUrl: `${apiUrl}/api/auth/jwks`, | |
| verifyOptions: { | |
| issuer: apiUrl, | |
| audience: [apiUrl, `${apiUrl}/`, `${apiUrl}/api/agent/mcp`], | |
| }, | |
| })) as Record<string, unknown>; |
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/api/src/app/api/auth/[...all]/route.ts
Line: 24-30
Comment:
The audience list in `rejectsUntrustedUserInfo` is narrower than what the MCP auth handler accepts. When `verifyAccessToken` throws an audience-mismatch error (e.g. for a token issued with audience `${apiUrl}/api/agent/mcp` only), the `catch {}` block returns `false` and the request falls through to Better Auth's own handler — which does not validate `azp`. An attacker who can obtain a victim-scoped DCR token with that audience would bypass this guard entirely. Adding the MCP-specific audience here closes the gap.
```suggestion
const payload = (await verifyAccessToken(token, {
jwksUrl: `${apiUrl}/api/auth/jwks`,
verifyOptions: {
issuer: apiUrl,
audience: [apiUrl, `${apiUrl}/`, `${apiUrl}/api/agent/mcp`],
},
})) as Record<string, unknown>;
```
How can I resolve this? If you propose a fix, please make it concise.| // Env keys become `KEY=value` assignments in a PTY launch prefix, so an | ||
| // unconstrained key is a shell-injection vector (RCE). Only accept valid POSIX | ||
| // env-var identifiers; values are still shell-quoted at the launch site. | ||
| const envKeySchema = z |
There was a problem hiding this comment.
The comment says "values are still shell-quoted at the launch site," but
agents.ts no longer builds a shell-prefix string — values are passed structurally via extraEnv and never reach a shell parser. This stale claim contradicts the defence-in-depth rationale and could mislead a future reviewer into thinking shell-quoting is still the primary mitigation.
| // Env keys become `KEY=value` assignments in a PTY launch prefix, so an | |
| // unconstrained key is a shell-injection vector (RCE). Only accept valid POSIX | |
| // env-var identifiers; values are still shell-quoted at the launch site. | |
| const envKeySchema = z | |
| // Env keys are validated as POSIX identifiers for defence in depth: even | |
| // though agent env is now passed structurally into the PTY (no shell | |
| // interpolation), rejecting non-identifier keys at the boundary prevents | |
| // accidental regressions if the launch path ever reverts to a shell prefix. | |
| const envKeySchema = z |
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/host-service/src/trpc/router/settings/agent-configs.ts
Line: 17-20
Comment:
The comment says "values are still shell-quoted at the launch site," but `agents.ts` no longer builds a shell-prefix string — values are passed structurally via `extraEnv` and never reach a shell parser. This stale claim contradicts the defence-in-depth rationale and could mislead a future reviewer into thinking shell-quoting is still the primary mitigation.
```suggestion
// Env keys are validated as POSIX identifiers for defence in depth: even
// though agent env is now passed structurally into the PTY (no shell
// interpolation), rejecting non-identifier keys at the boundary prevents
// accidental regressions if the launch path ever reverts to a shell prefix.
const envKeySchema = z
```
How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/host-service/src/terminal/terminal.ts (1)
1063-1063: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify optional environment property assignments.
Both files use conditional object spreads to omit an environment object when it is empty or falsy. Since the downstream receiver (
Object.assigninbuildV2TerminalEnv) safely performs a no-op on empty objects and properly ignoresundefinedinputs, you can pass the variables directly to reduce complexity.
packages/host-service/src/terminal/terminal.ts#L1063-L1063: Replace the conditional spread withagentEnv: extraEnv,.packages/host-service/src/trpc/router/agents/agents.ts#L274-L274: Replace the conditional spread withextraEnv: agentEnv,.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/host-service/src/terminal/terminal.ts` at line 1063, Replace the conditional environment-property spreads with direct assignments: in packages/host-service/src/terminal/terminal.ts (1063-1063), assign extraEnv directly to agentEnv; in packages/host-service/src/trpc/router/agents/agents.ts (274-274), assign agentEnv directly to extraEnv. Preserve the existing downstream handling through buildV2TerminalEnv.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/api/src/app/api/auth/`[...all]/route.ts:
- Around line 18-34: Update rejectsUntrustedUserInfo to distinguish
absent/non-JWT credentials from JWT-shaped tokens whose verifyAccessToken call
fails: propagate a failure state for verification errors so the route returns
401 instead of forwarding the request to Better Auth. Preserve the existing azp
check for successfully verified payloads, and add a regression test confirming
verifier errors never reach the underlying userinfo handler.
In `@apps/api/src/lib/trusted-clients.ts`:
- Around line 14-21: Update isUntrustedAuthorizedParty to distinguish a missing
azp claim from a present malformed value: return false only when payload.azp is
absent, and return true for null, arrays, objects, and other non-string present
values; for string values, retain the existing TRUSTED_API_CLIENTS check. Add
regression cases covering null, arrays, and objects.
---
Nitpick comments:
In `@packages/host-service/src/terminal/terminal.ts`:
- Line 1063: Replace the conditional environment-property spreads with direct
assignments: in packages/host-service/src/terminal/terminal.ts (1063-1063),
assign extraEnv directly to agentEnv; in
packages/host-service/src/trpc/router/agents/agents.ts (274-274), assign
agentEnv directly to extraEnv. Preserve the existing downstream handling through
buildV2TerminalEnv.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: d13a3e20-684d-4d6e-8fa6-62e9f440863a
📒 Files selected for processing (11)
apps/api/src/app/api/agent/[transport]/auth-flow.test.tsapps/api/src/app/api/agent/[transport]/auth-flow.tsapps/api/src/app/api/auth/[...all]/route.tsapps/api/src/lib/trusted-clients.tsapps/api/src/trpc/context.tspackages/host-service/src/terminal/env.test.tspackages/host-service/src/terminal/env.tspackages/host-service/src/terminal/terminal.tspackages/host-service/src/trpc/router/agents/agents.tspackages/host-service/src/trpc/router/settings/agent-configs.test.tspackages/host-service/src/trpc/router/settings/agent-configs.ts
| async function rejectsUntrustedUserInfo(req: Request): Promise<boolean> { | ||
| const match = req.headers.get("authorization")?.match(/^Bearer\s+(.+)$/i); | ||
| const token = match?.[1]; | ||
| if (!token || token.split(".").length !== 3) return false; | ||
|
|
||
| try { | ||
| const payload = (await verifyAccessToken(token, { | ||
| jwksUrl: `${apiUrl}/api/auth/jwks`, | ||
| verifyOptions: { | ||
| issuer: apiUrl, | ||
| audience: [apiUrl, `${apiUrl}/`], | ||
| }, | ||
| })) as Record<string, unknown>; | ||
| return isUntrustedAuthorizedParty(payload); | ||
| } catch { | ||
| return false; | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Fail closed when a JWT-shaped userinfo token cannot be verified.
The catch currently returns false, forwarding the token to Better Auth without enforcing the azp gate. Any validation discrepancy between these two paths can therefore bypass this security fix. Once a bearer token is JWT-shaped, verification failure should produce 401.
Proposed fix
} catch {
- return false;
+ return true;
}
}Add a regression test proving a verifier error cannot reach the underlying userinfo handler.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| async function rejectsUntrustedUserInfo(req: Request): Promise<boolean> { | |
| const match = req.headers.get("authorization")?.match(/^Bearer\s+(.+)$/i); | |
| const token = match?.[1]; | |
| if (!token || token.split(".").length !== 3) return false; | |
| try { | |
| const payload = (await verifyAccessToken(token, { | |
| jwksUrl: `${apiUrl}/api/auth/jwks`, | |
| verifyOptions: { | |
| issuer: apiUrl, | |
| audience: [apiUrl, `${apiUrl}/`], | |
| }, | |
| })) as Record<string, unknown>; | |
| return isUntrustedAuthorizedParty(payload); | |
| } catch { | |
| return false; | |
| } | |
| async function rejectsUntrustedUserInfo(req: Request): Promise<boolean> { | |
| const match = req.headers.get("authorization")?.match(/^Bearer\s+(.+)$/i); | |
| const token = match?.[1]; | |
| if (!token || token.split(".").length !== 3) return false; | |
| try { | |
| const payload = (await verifyAccessToken(token, { | |
| jwksUrl: `${apiUrl}/api/auth/jwks`, | |
| verifyOptions: { | |
| issuer: apiUrl, | |
| audience: [apiUrl, `${apiUrl}/`], | |
| }, | |
| })) as Record<string, unknown>; | |
| return isUntrustedAuthorizedParty(payload); | |
| } catch { | |
| return true; | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/api/src/app/api/auth/`[...all]/route.ts around lines 18 - 34, Update
rejectsUntrustedUserInfo to distinguish absent/non-JWT credentials from
JWT-shaped tokens whose verifyAccessToken call fails: propagate a failure state
for verification errors so the route returns 401 instead of forwarding the
request to Better Auth. Preserve the existing azp check for successfully
verified payloads, and add a regression test confirming verifier errors never
reach the underlying userinfo handler.
| export function isUntrustedAuthorizedParty( | ||
| payload: Record<string, unknown>, | ||
| ): boolean { | ||
| const authorizedClientId = | ||
| typeof payload.azp === "string" ? payload.azp : null; | ||
| return ( | ||
| authorizedClientId !== null && !TRUSTED_API_CLIENTS.has(authorizedClientId) | ||
| ); |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Reject present, non-string azp claims.
The current coercion treats malformed claims such as azp: null or azp: [] as if the claim were absent. Preserve the missing-claim exception, but reject every present value unless it is a trusted string.
Proposed fix
export function isUntrustedAuthorizedParty(
payload: Record<string, unknown>,
): boolean {
- const authorizedClientId =
- typeof payload.azp === "string" ? payload.azp : null;
- return (
- authorizedClientId !== null && !TRUSTED_API_CLIENTS.has(authorizedClientId)
- );
+ if (payload.azp === undefined) return false;
+ return (
+ typeof payload.azp !== "string" ||
+ !TRUSTED_API_CLIENTS.has(payload.azp)
+ );
}Add regression cases for null, arrays, and objects.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function isUntrustedAuthorizedParty( | |
| payload: Record<string, unknown>, | |
| ): boolean { | |
| const authorizedClientId = | |
| typeof payload.azp === "string" ? payload.azp : null; | |
| return ( | |
| authorizedClientId !== null && !TRUSTED_API_CLIENTS.has(authorizedClientId) | |
| ); | |
| export function isUntrustedAuthorizedParty( | |
| payload: Record<string, unknown>, | |
| ): boolean { | |
| if (payload.azp === undefined) return false; | |
| return ( | |
| typeof payload.azp !== "string" || | |
| !TRUSTED_API_CLIENTS.has(payload.azp) | |
| ); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/api/src/lib/trusted-clients.ts` around lines 14 - 21, Update
isUntrustedAuthorizedParty to distinguish a missing azp claim from a present
malformed value: return false only when payload.azp is absent, and return true
for null, arrays, objects, and other non-string present values; for string
values, retain the existing TRUSTED_API_CLIENTS check. Add regression cases
covering null, arrays, and objects.
There was a problem hiding this comment.
8 issues found across 11 files
You’re at about 91% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/api/src/lib/trusted-clients.ts">
<violation number="1" location="apps/api/src/lib/trusted-clients.ts:18">
P1: Tokens carrying a malformed non-string `azp` are allowed because this normalizes them to `null`, the missing-claim case. Fail closed for every present `azp` unless it is a trusted string client ID.</violation>
</file>
<file name="packages/host-service/src/trpc/router/settings/agent-configs.ts">
<violation number="1" location="packages/host-service/src/trpc/router/settings/agent-configs.ts:17">
P3: This comment documents the old shell-prefix design and says values require shell quoting, contradicting the structured-env implementation. Update it so future changes do not reintroduce shell interpolation based on misleading security guidance.</violation>
<violation number="2" location="packages/host-service/src/trpc/router/settings/agent-configs.ts:26">
P1: Existing persisted agent configs bypass this schema, so malicious env keys saved before upgrade remain usable and the RCE fix is incomplete. Validate/filter keys in `parseEnv` (or migrate stored `envJson`) before returning configs to the terminal launcher.</violation>
</file>
<file name="apps/api/src/app/api/auth/[...all]/route.ts">
<violation number="1" location="apps/api/src/app/api/auth/[...all]/route.ts:28">
P1: The audience list `[apiUrl, \`${apiUrl}/\`]` doesn't include the MCP-specific audience (`${apiUrl}/api/agent/mcp`). A token legitimately issued with only the MCP audience will cause `verifyAccessToken` to throw `JWTClaimValidationFailed`, and given the current `catch` behavior (returning `false`), the request falls through to Better Auth's handler without the `azp` gate. Consider adding the MCP audience to this list so that valid MCP tokens are verified and subjected to the `azp` check rather than bypassing it via the error path.</violation>
<violation number="2" location="apps/api/src/app/api/auth/[...all]/route.ts:33">
P0: Userinfo falls back to Better Auth when this verification fails, bypassing the new `azp` gate during JWKS/network or validation failures. Reject JWT-shaped bearer tokens on this error path; Better Auth's userinfo handler does not enforce `azp`.</violation>
</file>
<file name="apps/api/src/app/api/agent/[transport]/auth-flow.ts">
<violation number="1" location="apps/api/src/app/api/agent/[transport]/auth-flow.ts:168">
P3: Rejected OAuth requests now emit an error on every attempt, so a DCR client with a valid token can flood MCP logs without changing the response. Return the authorization failure without logging this expected denial.
(Based on your team's feedback about excessive logs.) [FEEDBACK_USED].</violation>
</file>
<file name="apps/api/src/app/api/agent/[transport]/auth-flow.test.ts">
<violation number="1" location="apps/api/src/app/api/agent/[transport]/auth-flow.test.ts:3">
P3: `mock.module("@/env", ...)` mocks a module that `auth-flow.ts` does not import — either directly or transitively through any of its dependencies (`@/lib/oauth-metadata`, `@/lib/trusted-clients`). The mock is dead test setup code that adds noise for future readers.</violation>
</file>
<file name="packages/host-service/src/terminal/env.ts">
<violation number="1" location="packages/host-service/src/terminal/env.ts:233">
P1: Merging the overlay with `Object.assign` lets a valid `__proto__` key mutate the PTY env object's prototype instead of becoming an environment variable. Filtering the dangerous keys or using a null-prototype target would keep the new env merge from turning into prototype pollution.</violation>
</file>
Architecture diagram
sequenceDiagram
participant Client as Client (UI/Agent)
participant API as API Server
participant AuthBetter as Better Auth (/api/auth/oauth2/userinfo)
participant AuthToken as JWT Verification
participant TrustedClients as trusted-clients.ts
participant tRPC as tRPC Context
participant MCP as MCP Endpoint (/api/agent/mcp)
participant AgentConfig as Agent Config Schema
participant HostService as Host-Service (agents.ts)
participant TerminalEnv as Terminal Env Builder (env.ts)
participant PTY as PTY spawn (node-pty)
Note over Client,PTY: RCE Fix: Env Key Validation & Structural Passing
Client->>API: POST /trpc (agentConfigs.add with env keys)
API->>AgentConfig: Validate env keys (new regex /^[A-Za-z_][A-Za-z0-9_]*$/)
alt Invalid key (shell metacharacters, spaces, etc.)
AgentConfig-->>API: Reject with error
API-->>Client: 400 Bad Request
else Valid POSIX identifier keys
AgentConfig-->>API: Accept configuration
end
Client->>HostService: trpc agents.run (with env overlay)
HostService->>HostService: Build agentEnv from config.env + modelEnv
HostService->>TerminalEnv: createTerminalSessionInternal(extraEnv=agentEnv, initialCommand=command only)
TerminalEnv->>TerminalEnv: buildV2TerminalEnv(agentEnv) – assign structurally via Object.assign
TerminalEnv->>PTY: Spawn PTY with env vars in process environment (keys never parsed as shell)
PTY-->>HostService: PTY session started
HostService-->>Client: Terminal ID
Note over Client,MCP: Cross-tenant ATO Fix: azp Validation
Client->>MCP: POST /api/agent/mcp (Authorization: Bearer JWT)
MCP->>AuthToken: verifyAccessToken (validate signature, issuer, audience)
AuthToken-->>MCP: payload (sub, orgId, azp)
MCP->>TrustedClients: isUntrustedAuthorizedParty(payload)
alt azp present and not in trusted set
TrustedClients-->>MCP: true (untrusted)
MCP-->>Client: 401 Unauthorized
else azp trusted or missing
TrustedClients-->>MCP: false (trusted)
MCP->>MCP: Accept token, grant agent context
MCP-->>Client: MCP session established
end
Note over Client,AuthBetter: Additional azp Gate on Userinfo Endpoint
Client->>AuthBetter: GET /api/auth/oauth2/userinfo (Bearer JWT)
AuthBetter->>AuthToken: verifyAccessToken (same as above)
AuthToken-->>AuthBetter: payload
AuthBetter->>TrustedClients: isUntrustedAuthorizedParty(payload)
alt azp untrusted
TrustedClients-->>AuthBetter: true
AuthBetter-->>Client: 401 Unauthorized
else trusted or missing
TrustedClients-->>AuthBetter: false
AuthBetter->>AuthBetter: Process userinfo request normally
AuthBetter-->>Client: User identity
end
Note over tRPC,TrustedClients: Shared Trusted Client Helper
tRPC->>TrustedClients: isUntrustedAuthorizedParty (same function)
alt azp untrusted
TrustedClients-->>tRPC: true
tRPC-->>Client: 401 (existing behavior)
else trusted or missing
TrustedClients-->>tRPC: false
tRPC-->>Client: Proceed with TRPC context
end
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| })) as Record<string, unknown>; | ||
| return isUntrustedAuthorizedParty(payload); | ||
| } catch { | ||
| return false; |
There was a problem hiding this comment.
P0: Userinfo falls back to Better Auth when this verification fails, bypassing the new azp gate during JWKS/network or validation failures. Reject JWT-shaped bearer tokens on this error path; Better Auth's userinfo handler does not enforce azp.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/app/api/auth/[...all]/route.ts, line 33:
<comment>Userinfo falls back to Better Auth when this verification fails, bypassing the new `azp` gate during JWKS/network or validation failures. Reject JWT-shaped bearer tokens on this error path; Better Auth's userinfo handler does not enforce `azp`.</comment>
<file context>
@@ -1,8 +1,39 @@
+ })) as Record<string, unknown>;
+ return isUntrustedAuthorizedParty(payload);
+ } catch {
+ return false;
+ }
+}
</file context>
| return false; | |
| return true; |
| payload: Record<string, unknown>, | ||
| ): boolean { | ||
| const authorizedClientId = | ||
| typeof payload.azp === "string" ? payload.azp : null; |
There was a problem hiding this comment.
P1: Tokens carrying a malformed non-string azp are allowed because this normalizes them to null, the missing-claim case. Fail closed for every present azp unless it is a trusted string client ID.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/lib/trusted-clients.ts, line 18:
<comment>Tokens carrying a malformed non-string `azp` are allowed because this normalizes them to `null`, the missing-claim case. Fail closed for every present `azp` unless it is a trusted string client ID.</comment>
<file context>
@@ -0,0 +1,22 @@
+ payload: Record<string, unknown>,
+): boolean {
+ const authorizedClientId =
+ typeof payload.azp === "string" ? payload.azp : null;
+ return (
+ authorizedClientId !== null && !TRUSTED_API_CLIENTS.has(authorizedClientId)
</file context>
| /^[A-Za-z_][A-Za-z0-9_]*$/, | ||
| "Env var names must be valid POSIX identifiers ([A-Za-z_][A-Za-z0-9_]*)", | ||
| ); | ||
| const envSchema = z.record(envKeySchema, z.string()); |
There was a problem hiding this comment.
P1: Existing persisted agent configs bypass this schema, so malicious env keys saved before upgrade remain usable and the RCE fix is incomplete. Validate/filter keys in parseEnv (or migrate stored envJson) before returning configs to the terminal launcher.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/trpc/router/settings/agent-configs.ts, line 26:
<comment>Existing persisted agent configs bypass this schema, so malicious env keys saved before upgrade remain usable and the RCE fix is incomplete. Validate/filter keys in `parseEnv` (or migrate stored `envJson`) before returning configs to the terminal launcher.</comment>
<file context>
@@ -14,7 +14,16 @@ import { protectedProcedure, router } from "../../index";
+ /^[A-Za-z_][A-Za-z0-9_]*$/,
+ "Env var names must be valid POSIX identifiers ([A-Za-z_][A-Za-z0-9_]*)",
+ );
+const envSchema = z.record(envKeySchema, z.string());
export interface HostAgentConfig {
</file context>
| // POSIX identifier keys reach here (validated at the tRPC boundary), and | ||
| // they never touch shell parsing — node-pty sets them structurally. | ||
| if (agentEnv) { | ||
| Object.assign(env, agentEnv); |
There was a problem hiding this comment.
P1: Merging the overlay with Object.assign lets a valid __proto__ key mutate the PTY env object's prototype instead of becoming an environment variable. Filtering the dangerous keys or using a null-prototype target would keep the new env merge from turning into prototype pollution.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/terminal/env.ts, line 233:
<comment>Merging the overlay with `Object.assign` lets a valid `__proto__` key mutate the PTY env object's prototype instead of becoming an environment variable. Filtering the dangerous keys or using a null-prototype target would keep the new env merge from turning into prototype pollution.</comment>
<file context>
@@ -219,5 +226,12 @@ export function buildV2TerminalEnv(
+ // POSIX identifier keys reach here (validated at the tRPC boundary), and
+ // they never touch shell parsing — node-pty sets them structurally.
+ if (agentEnv) {
+ Object.assign(env, agentEnv);
+ }
+
</file context>
| jwksUrl: `${apiUrl}/api/auth/jwks`, | ||
| verifyOptions: { | ||
| issuer: apiUrl, | ||
| audience: [apiUrl, `${apiUrl}/`], |
There was a problem hiding this comment.
P1: The audience list [apiUrl, \${apiUrl}/`] doesn't include the MCP-specific audience (${apiUrl}/api/agent/mcp). A token legitimately issued with only the MCP audience will cause verifyAccessTokento throwJWTClaimValidationFailed, and given the current catchbehavior (returningfalse), the request falls through to Better Auth's handler without the azpgate. Consider adding the MCP audience to this list so that valid MCP tokens are verified and subjected to theazp` check rather than bypassing it via the error path.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/app/api/auth/[...all]/route.ts, line 28:
<comment>The audience list `[apiUrl, \`${apiUrl}/\`]` doesn't include the MCP-specific audience (`${apiUrl}/api/agent/mcp`). A token legitimately issued with only the MCP audience will cause `verifyAccessToken` to throw `JWTClaimValidationFailed`, and given the current `catch` behavior (returning `false`), the request falls through to Better Auth's handler without the `azp` gate. Consider adding the MCP audience to this list so that valid MCP tokens are verified and subjected to the `azp` check rather than bypassing it via the error path.</comment>
<file context>
@@ -1,8 +1,39 @@
+ jwksUrl: `${apiUrl}/api/auth/jwks`,
+ verifyOptions: {
+ issuer: apiUrl,
+ audience: [apiUrl, `${apiUrl}/`],
+ },
+ })) as Record<string, unknown>;
</file context>
| audience: [apiUrl, `${apiUrl}/`], | |
| audience: [apiUrl, `${apiUrl}/`, `${apiUrl}/api/agent/mcp`], |
| // Env keys become `KEY=value` assignments in a PTY launch prefix, so an | ||
| // unconstrained key is a shell-injection vector (RCE). Only accept valid POSIX | ||
| // env-var identifiers; values are still shell-quoted at the launch site. |
There was a problem hiding this comment.
P3: This comment documents the old shell-prefix design and says values require shell quoting, contradicting the structured-env implementation. Update it so future changes do not reintroduce shell interpolation based on misleading security guidance.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/trpc/router/settings/agent-configs.ts, line 17:
<comment>This comment documents the old shell-prefix design and says values require shell quoting, contradicting the structured-env implementation. Update it so future changes do not reintroduce shell interpolation based on misleading security guidance.</comment>
<file context>
@@ -14,7 +14,16 @@ import { protectedProcedure, router } from "../../index";
const argvSchema = z.array(z.string());
-const envSchema = z.record(z.string(), z.string());
+// Env keys become `KEY=value` assignments in a PTY launch prefix, so an
+// unconstrained key is a shell-injection vector (RCE). Only accept valid POSIX
+// env-var identifiers; values are still shell-quoted at the launch site.
</file context>
| // Env keys become `KEY=value` assignments in a PTY launch prefix, so an | |
| // unconstrained key is a shell-injection vector (RCE). Only accept valid POSIX | |
| // env-var identifiers; values are still shell-quoted at the launch site. | |
| // Env keys must be valid POSIX identifiers before persistence so every launch | |
| // path receives a safe environment map. |
| console.error("[mcp/auth] Access token has untrusted azp; rejecting", { | ||
| azp: payload.azp, | ||
| }); | ||
| return undefined; |
There was a problem hiding this comment.
P3: Rejected OAuth requests now emit an error on every attempt, so a DCR client with a valid token can flood MCP logs without changing the response. Return the authorization failure without logging this expected denial.
(Based on your team's feedback about excessive logs.) .
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/app/api/agent/[transport]/auth-flow.ts, line 168:
<comment>Rejected OAuth requests now emit an error on every attempt, so a DCR client with a valid token can flood MCP logs without changing the response. Return the authorization failure without logging this expected denial.
(Based on your team's feedback about excessive logs.) .</comment>
<file context>
@@ -159,6 +160,17 @@ function buildOAuthAuthInfo(
+ // grants the attacker the victim's agent context (cross-tenant ATO). This
+ // mirrors the tRPC boundary check in trpc/context.ts.
+ if (isUntrustedAuthorizedParty(payload)) {
+ console.error("[mcp/auth] Access token has untrusted azp; rejecting", {
+ azp: payload.azp,
+ });
</file context>
| console.error("[mcp/auth] Access token has untrusted azp; rejecting", { | |
| azp: payload.azp, | |
| }); | |
| return undefined; | |
| return undefined; |
| @@ -0,0 +1,81 @@ | |||
| import { describe, expect, mock, test } from "bun:test"; | |||
|
|
|||
| mock.module("@/env", () => ({ | |||
There was a problem hiding this comment.
P3: mock.module("@/env", ...) mocks a module that auth-flow.ts does not import — either directly or transitively through any of its dependencies (@/lib/oauth-metadata, @/lib/trusted-clients). The mock is dead test setup code that adds noise for future readers.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/app/api/agent/[transport]/auth-flow.test.ts, line 3:
<comment>`mock.module("@/env", ...)` mocks a module that `auth-flow.ts` does not import — either directly or transitively through any of its dependencies (`@/lib/oauth-metadata`, `@/lib/trusted-clients`). The mock is dead test setup code that adds noise for future readers.</comment>
<file context>
@@ -0,0 +1,81 @@
+import { describe, expect, mock, test } from "bun:test";
+
+mock.module("@/env", () => ({
+ env: { NEXT_PUBLIC_API_URL: "http://localhost" },
+}));
</file context>
|
Closing without merging. Neither change fits as written: Env-key "RCE": anyone who can call MCP |
Summary
Fixes two critical vulnerabilities responsibly disclosed by external researchers Jemin Khunt (cyber.jemin@gmail.com) and Hitarth Shah (shahhits12@gmail.com). Both were confirmed present in this codebase.
The third finding from the same disclosure — chat-session BOLA (PR #5017) — is already fixed and out of scope here; this PR does not touch it.
Issue 1 — RCE via env-key shell injection in host-service (P0, CVSS 9.9)
runTerminalAgentbuilt a PTY launch command by prefixingKEY=valueassignments viaenvOverlayPrefix(). Values were shell-quoted (quoteSingleShell), but keys were not, andsettings.agentConfigs.addacceptedz.record(z.string(), z.string())with no key format restriction. An attacker could store an env key containing shell metacharacters (e.g.FOO;curl$IFS-sSf…|sh), then triggeragents.runto execute arbitrary shell on any connected host — full RCE with access to~/.ssh,~/.aws/credentials, API keys, and all git repos. Researchers confirmed live hostname/username exfiltration.Fix (both layers):
/^[A-Za-z_][A-Za-z0-9_]*$/) inagentConfigsadd/update schemas.buildV2TerminalEnvagentEnv→createTerminalSessionInternalextraEnv) instead of being interpolated into a shell prefix, so keys/values never touch shell parsing.runTerminalAgentno longer builds a shell prefix string.Issue 2 — OAuth cross-tenant ATO via un-gated MCP surface (azp not validated)
The tRPC boundary already rejected attacker-registered DCR-client tokens via a
TRUSTED_API_CLIENTS/azpcheck. The MCP bearer path had no such gate:buildOAuthAuthInfoverified the JWT by signature + issuer + audience only and readazpbut never validated it. A victim-scoped token minted to an attacker-registered DCR client was accepted at/api/agent/mcpand/api/v2/agent/mcp, granting the attacker the victim's agent context. Native Better Auth/api/auth/oauth2/userinfowas likewise un-gated.Fix:
azpis present and not in the trusted client set insidebuildOAuthAuthInfo./api/auth/oauth2/userinfo(GET and POST) in the Better Auth[...all]route.apps/api/src/lib/trusted-clients.tshelper, now reused bytrpc/context.ts(no duplicated list).Tests
agent-configs.test.ts: malicious/invalid env keys (incl.FOO;curl$IFS…) are rejected; valid POSIX identifiers accepted.env.test.ts: agent env is applied structurally and a metacharacter key is carried as an inert plain var, never parsed as shell.auth-flow.test.ts: an MCP token with an untrustedazpis rejected atverifyToken; trusted / no-azptokens still accepted.Each new test was verified to fail against the unpatched code and pass after the fix.
bun run lintexits 0;typecheckand the affected test suites pass.Credits
Thanks to Jemin Khunt and Hitarth Shah for the responsible disclosure.
Summary by cubic
Fixes a host-service RCE by validating env keys and passing env vars structurally, and closes a cross-tenant OAuth ATO by enforcing
azpchecks on MCP and/api/auth/oauth2/userinfo.Bug Fixes
agent-configsto POSIX identifiers (/^[A-Za-z_][A-Za-z0-9_]*$/) to block shell injection.buildV2TerminalEnvagentEnv,createTerminalSessionInternalextraEnv); stop prefixingKEY=valueonto commands inrunTerminalAgent.azpin MCP OAuth auth and in Better Auth/api/auth/oauth2/userinfo(GET/POST); allow first‑party tokens withoutazp.Refactors
apps/api/src/lib/trusted-clients.tswithTRUSTED_API_CLIENTSandisUntrustedAuthorizedParty, reused bytrpc/context.tsand MCP auth.Written for commit 5fd55a1. Summary will update on new commits.
Summary by CodeRabbit
Security
Enhancements
Tests