Skip to content

fix(security): validate env keys to close host-service RCE and gate MCP azp to close cross-tenant ATO - #5735

Closed
Kitenite wants to merge 1 commit into
mainfrom
security/mcp-rce-oauth-azp-fixes
Closed

Kitenite wants to merge 1 commit into
mainfrom
security/mcp-rce-oauth-azp-fixes

Conversation

@Kitenite

@Kitenite Kitenite commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

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)

runTerminalAgent built a PTY launch command by prefixing KEY=value assignments via envOverlayPrefix(). Values were shell-quoted (quoteSingleShell), but keys were not, and settings.agentConfigs.add accepted z.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 trigger agents.run to 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):

  • Boundary validation: env keys must now be valid POSIX identifiers (/^[A-Za-z_][A-Za-z0-9_]*$/) in agentConfigs add/update schemas.
  • Defense in depth: agent env is now threaded structurally into the PTY spawn env (buildV2TerminalEnv agentEnv → createTerminalSessionInternal extraEnv) instead of being interpolated into a shell prefix, so keys/values never touch shell parsing. runTerminalAgent no 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 / azp check. The MCP bearer path had no such gate: buildOAuthAuthInfo verified the JWT by signature + issuer + audience only and read azp but never validated it. A victim-scoped token minted to an attacker-registered DCR client was accepted at /api/agent/mcp and /api/v2/agent/mcp, granting the attacker the victim's agent context. Native Better Auth /api/auth/oauth2/userinfo was likewise un-gated.

Fix:

  • Reject tokens whose azp is present and not in the trusted client set inside buildOAuthAuthInfo.
  • Apply the same gate to /api/auth/oauth2/userinfo (GET and POST) in the Better Auth [...all] route.
  • Extracted the trusted-client list + check into a shared apps/api/src/lib/trusted-clients.ts helper, now reused by trpc/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 untrusted azp is rejected at verifyToken; trusted / no-azp tokens still accepted.

Each new test was verified to fail against the unpatched code and pass after the fix. bun run lint exits 0; typecheck and the affected test suites pass.

Credits

Thanks to Jemin Khunt and Hitarth Shah for the responsible disclosure.


Open in Stage

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 azp checks on MCP and /api/auth/oauth2/userinfo.

  • Bug Fixes

    • Validate env keys in agent-configs to POSIX identifiers (/^[A-Za-z_][A-Za-z0-9_]*$/) to block shell injection.
    • Pass agent env structurally to the PTY (buildV2TerminalEnv agentEnv, createTerminalSessionInternal extraEnv); stop prefixing KEY=value onto commands in runTerminalAgent.
    • Reject tokens with untrusted azp in MCP OAuth auth and in Better Auth /api/auth/oauth2/userinfo (GET/POST); allow first‑party tokens without azp.
  • Refactors

    • Added apps/api/src/lib/trusted-clients.ts with TRUSTED_API_CLIENTS and isUntrustedAuthorizedParty, reused by trpc/context.ts and MCP auth.

Written for commit 5fd55a1. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • Security

    • Strengthened OAuth authentication by rejecting tokens from untrusted clients.
    • Added protection for OAuth user-info requests against unauthorized tokens.
  • Enhancements

    • Agent environment variables are now applied directly to terminal sessions.
    • Agent configuration validates environment variable names using POSIX-compatible rules.
  • Tests

    • Added coverage for trusted and untrusted OAuth clients.
    • Added tests for environment variable overrides and validation, including shell-metacharacter protection.

…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.
@ghost

ghost commented Jul 17, 2026

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 4 individual chapters for you:

Title
1 Centralize trusted OAuth client validation
2 Gate MCP and UserInfo endpoints against untrusted clients
3 Validate environment variable keys in agent configs
4 Pass agent environment structurally to PTY
Open in Stage

Chapters generated by Stage for commit 5fd55a1 on Jul 17, 2026 3:39pm UTC.

@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR centralizes OAuth azp trust validation across authentication paths and adds rejection for untrusted clients. It also validates agent environment keys and transfers environment overlays structurally into PTY sessions rather than shell commands.

Changes

OAuth trust gates

Layer / File(s) Summary
Centralized authorized-party validation
apps/api/src/lib/trusted-clients.ts, apps/api/src/trpc/context.ts
Adds the trusted client allowlist and shared azp validation helper, then uses it during OAuth bearer session creation.
OAuth endpoint rejection and coverage
apps/api/src/app/api/agent/[transport]/auth-flow.ts, apps/api/src/app/api/agent/[transport]/auth-flow.test.ts, apps/api/src/app/api/auth/[...all]/route.ts
Rejects untrusted OAuth tokens in MCP authentication and GET/POST userinfo handlers, with coverage for trusted, untrusted, and missing azp claims.

Terminal environment overlays

Layer / File(s) Summary
Agent environment key validation
packages/host-service/src/trpc/router/settings/agent-configs.ts, packages/host-service/src/trpc/router/settings/agent-configs.test.ts
Restricts agent environment keys to POSIX identifier syntax and tests invalid and valid key forms.
Structured PTY environment propagation
packages/host-service/src/trpc/router/agents/agents.ts, packages/host-service/src/terminal/terminal.ts, packages/host-service/src/terminal/env.ts, packages/host-service/src/terminal/env.test.ts
Passes merged agent and model environments through terminal options into the PTY environment, with tests for overrides and literal metacharacter-containing entries.

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
Loading

Possibly related PRs

Suggested reviewers: saddlepaddle

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is conventional, concise, and accurately summarizes the two security fixes in the change set.
Description check ✅ Passed The description covers the why, testing, and checklist items, though it uses custom headings instead of the exact template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch security/mcp-rce-oauth-azp-fixes

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Preview Deployment

🔗 Preview Links

Service Status Link
Neon Database (Neon) ✅ View Branch
Vercel API (Vercel) ✅ Open Preview
Vercel Web (Vercel) ✅ Open Preview
Vercel Marketing (Vercel) ✅ Open Preview
Vercel Admin (Vercel) ✅ Open Preview
Vercel Docs (Vercel) ✅ Open Preview

Preview updates automatically with new commits

@greptile-apps

greptile-apps Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This 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 azp on the MCP and Better Auth userinfo surfaces (fixed by a shared isUntrustedAuthorizedParty helper applied at all three boundaries).

  • RCE fix: envOverlayPrefix shell-string construction is removed from runTerminalAgent; agent env flows through extraEnv → buildV2TerminalEnv → node-pty without ever touching shell parsing. The envKeySchema POSIX regex guard at the tRPC input is defence-in-depth.
  • ATO fix: buildOAuthAuthInfo (MCP), sessionFromOAuthBearer (tRPC), and a new pre-flight interceptor on /api/auth/oauth2/userinfo all reject tokens whose azp is present and not in TRUSTED_API_CLIENTS, with the trusted-set and predicate deduplicated into apps/api/src/lib/trusted-clients.ts.
  • One gap: the pre-flight audience list in rejectsUntrustedUserInfo (route.ts) is missing ${apiUrl}/api/agent/mcp, which is accepted by the MCP handler; a token with only that audience would bypass the pre-flight catch {} path and land at Better Auth's azp-unaware handler.

Confidence Score: 3/5

The 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.

Security Review

  • Partial bypass of userinfo azp gate (route.ts line 24–30): rejectsUntrustedUserInfo only accepts audiences [apiUrl, "${apiUrl}/"]; a validly-signed token whose audience is exclusively ${apiUrl}/api/agent/mcp triggers an audience-mismatch exception, the catch {} block returns false, and the request falls through to Better Auth's native userinfo handler — which does not validate azp. Recommend adding the MCP audience to the pre-flight list to match the full set accepted by the MCP boundary check.
  • No new injection, credential-exposure, or SSRF vectors were introduced; the env-key fix eliminates rather than mitigates the shell-injection surface.

Important Files Changed

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)
Loading
%%{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)
Loading
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

Comment on lines +24 to +30
const payload = (await verifyAccessToken(token, {
jwksUrl: `${apiUrl}/api/auth/jwks`,
verifyOptions: {
issuer: apiUrl,
audience: [apiUrl, `${apiUrl}/`],
},
})) as Record<string, unknown>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security 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.

Suggested change
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.

Comment on lines +17 to +20
// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Suggested change
// 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!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/host-service/src/terminal/terminal.ts (1)

1063-1063: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Simplify 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.assign in buildV2TerminalEnv) safely performs a no-op on empty objects and properly ignores undefined inputs, you can pass the variables directly to reduce complexity.

  • packages/host-service/src/terminal/terminal.ts#L1063-L1063: Replace the conditional spread with agentEnv: extraEnv,.
  • packages/host-service/src/trpc/router/agents/agents.ts#L274-L274: Replace the conditional spread with extraEnv: 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

📥 Commits

Reviewing files that changed from the base of the PR and between b13a92c and 5fd55a1.

📒 Files selected for processing (11)
  • apps/api/src/app/api/agent/[transport]/auth-flow.test.ts
  • apps/api/src/app/api/agent/[transport]/auth-flow.ts
  • apps/api/src/app/api/auth/[...all]/route.ts
  • apps/api/src/lib/trusted-clients.ts
  • apps/api/src/trpc/context.ts
  • packages/host-service/src/terminal/env.test.ts
  • packages/host-service/src/terminal/env.ts
  • packages/host-service/src/terminal/terminal.ts
  • packages/host-service/src/trpc/router/agents/agents.ts
  • packages/host-service/src/trpc/router/settings/agent-configs.test.ts
  • packages/host-service/src/trpc/router/settings/agent-configs.ts

Comment on lines +18 to +34
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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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.

Suggested change
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.

Comment on lines +14 to +21
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)
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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.

Suggested change
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.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

})) as Record<string, unknown>;
return isUntrustedAuthorizedParty(payload);
} catch {
return false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Suggested change
return false;
return true;

payload: Record<string, unknown>,
): boolean {
const authorizedClientId =
typeof payload.azp === "string" ? payload.azp : null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}/`],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Suggested change
audience: [apiUrl, `${apiUrl}/`],
audience: [apiUrl, `${apiUrl}/`, `${apiUrl}/api/agent/mcp`],

Comment on lines +17 to +19
// 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Suggested change
// 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.

Comment on lines +168 to +171
console.error("[mcp/auth] Access token has untrusted azp; rejecting", {
azp: payload.azp,
});
return undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.) .

View Feedback

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>
Suggested change
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", () => ({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

@Kitenite

Copy link
Copy Markdown
Member Author

Closing without merging. Neither change fits as written:

Env-key "RCE": anyone who can call agentConfigs.add/update can already set the free-form command field, which runs as shell. Injecting through an env key gives no access beyond that. Checking that keys are valid variable names is still worth doing, because a bad key breaks the launch. That will be a small separate PR.

MCP azp gate: the allowlist is {"superset-cli"}. Applying it to MCP would reject tokens from every client that registers itself through OAuth (Claude Code, Cursor, claude.ai connectors). The attack also needs the victim to approve the attacker's app on the consent screen, which is ordinary OAuth phishing, not a token-validation bug. The patched code is also gone: v1 MCP was removed in #6082, and MCP OAuth now lives in packages/mcp/src/auth.ts.

@Kitenite Kitenite closed this Nov 17, 2026

This branch was previously deployed

1 inactive deployment
preview — 5fd55a1c Deployed Jul 17, 2026 by Kitenite via Deploy Marketing #6579
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant