Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(web): require Bearer MCP_API_KEY on POST /mcp
Gate remote MCP with constant-time Bearer check (fail closed when
MCP_API_KEY is unset). Correct scan_business_website readOnly hint.
Add route auth tests and update SECURITY-REVIEW for H-11/H-02.

Co-authored-by: m-qm <m-qm@users.noreply.github.com>
  • Loading branch information
cursoragent and m-qm committed Nov 24, 2026
commit 50d5b7c68030c9fcbc4976d3c07756ee3c713b08
15 changes: 11 additions & 4 deletions SECURITY-REVIEW.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ Each finding is tagged **`[código]`**, **`[configuración]`**, or **`[proceso]`
| ID | Tag | Sev | Location | Description | Test | Mitigation |
| --- | --- | --- | --- | --- | --- | --- |
| H-01 | `[proceso]` | Medium | `.gitignore` (historical) | Worker prompts lived only on disk; audit drift from `.mdc`. | — | Version `brain/agents/**` (this PR). |
| H-02 | `[código]` | **High** | `blog-search-gap.mdc:3` (before fix) | Glob included `apps/web/public/blog/**` → agent could edit production markdown; deploy = publish without queue. | **T03** | **Fixed:** removed live blog from globs; read-only instruction. |
| H-02 | `[código]` | **High** (historical) | `blog-search-gap.mdc:3` | Historically glob included `apps/web/public/blog/**`. **Verificado 2025-11-24:** not confirmed in current tree; glob is examples-only; residual **process** risk (no CI hook on `public/blog` writes). | **T03** | Mitigated in tree; no code hook for live blog writes. |
| H-03 | `[proceso]` | Medium | `article-agent.mdc:9` | “Queue as pending” is policy, not enforcement. | T01–T02 | Mandatory frontmatter `status: pending`; CI on `public/blog` changes. |
| H-04 | `[código]` | Medium | `telegram-approval.ts:158` | UI string “Publicado.” after approve; queue does not publish. | **T05** | Rename copy to “Aprobado en cola”; doc link here. |
| H-05 | `[código]` | Control | `queue.ts`, CLI | Approve/reject never calls external publish APIs. | **T05** | Keep Act connectors out of core. |
Expand All @@ -92,7 +92,9 @@ Each finding is tagged **`[código]`**, **`[configuración]`**, or **`[proceso]`
| H-08 | `[código]` | Control | `eval-draft.ts` | Invented price fails against facts. | **T06** | Run `brain eval --all` before human copy. |
| H-09 | `[código]` | Medium | `extract-with-llm.ts` | Untrusted HTML in LLM prompt (indirect injection). | T08 | Human validate extract; don’t merge to facts unattended. |
| H-10 | `[configuración]` | High (if on) | `observe.ts` + `LANGFUSE_TRACE_CONTENT` | Brief/tool payloads may leave the host. | **T10** | Default off; redact in prod. |
| H-11 | `[configuración]` | Medium | Remote `/mcp` | No auth in v0; scan + hosted profile. | — | OAuth + rate limits (open question). |
| H-11 | `[código]` | Medium | `apps/web/app/mcp/route.ts` | Remote `POST /mcp` without auth; `scan_business_website` persists hosted profiles + fetches arbitrary URLs. | **T11** | **Mitigated:** `Authorization: Bearer <MCP_API_KEY>`; fail closed if unset. Tests: `apps/web/app/mcp/route.test.ts`. |
| H-11b | `[código]` | Low | `remote-mcp-server.ts` | `scan_business_website` annotated `readOnly` while writing profiles. | — | **Mitigated:** `readOnlyHint: false`. |
| H-11c | `[configuración]` | Medium | Remote `/mcp` | No rate limit on authenticated traffic (abuse / cost). | — | **Open:** needs Vercel Firewall, edge middleware, or external WAF (out of scope for route-only fix). |
| H-12 | `[proceso]` | Medium | Deploy pipeline | Human merges `public/blog` → site live. | — | PR review; separate approver from drafter. |

---
Expand All @@ -113,8 +115,9 @@ Each finding is tagged **`[código]`**, **`[configuración]`**, or **`[proceso]`
| **T08** | Extract | Hostile HTML in extract prompt | No unattended merge to facts | **Manual** / policy |
| **T09** | Mastra | `review-loop.test.ts` without `approved` | `posted: false` | **Pass** |
| **T10** | Langfuse | Prod with trace content on | Policy review | **N/A** in this VM |
| **T11** | MCP auth | `node --experimental-strip-types --test apps/web/app/mcp/route.test.ts` | No Bearer → 401; valid Bearer passes gate | **Pass** 4/4 (after `pnpm run build:packages`) |

Automated run summary: **34 tests passed** (core queue/telegram/eval, brain-files, MCP, mastra).
Automated run summary: **38 tests passed** (core queue/telegram/eval, brain-files, MCP, mastra, web MCP auth).

---

Expand All @@ -124,7 +127,11 @@ Automated run summary: **34 tests passed** (core queue/telegram/eval, brain-file
globs: examples/content-ads-brain/brain/content/article-slate.md,examples/content-ads-brain/brain/content/articles/**/*.md
```

Live blog comparison is **read-only by instruction**, not by glob write scope.
Live blog comparison is **read-only by instruction**, not by glob write scope. **Re-verification (H-02):** current line 3 does not include `apps/web/public/blog/**`; finding not reproduced; enforcement remains policy/operator, not repository hooks.

## Remote MCP auth (H-11)

Set `MCP_API_KEY` in the deployment environment (e.g. Vercel project env). Clients must send `Authorization: Bearer <MCP_API_KEY>`. Without the variable, `POST /mcp` returns **401** (fail closed).

---

Expand Down
48 changes: 48 additions & 0 deletions apps/web/app/mcp/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import { afterEach, beforeEach, describe, test } from "node:test";
import { POST, isMcpAuthorized, mcpAuthGate } from "./route.ts";

const TEST_KEY = "test-mcp-key-0123456789";

describe("POST /mcp authorization", () => {
beforeEach(() => {
process.env.MCP_API_KEY = TEST_KEY;
});

afterEach(() => {
delete process.env.MCP_API_KEY;
});

test("POST without Authorization returns 401", async () => {
const res = await POST(new Request("http://localhost/mcp", { method: "POST", body: "{}" }));
assert.equal(res.status, 401);
});

test("POST with wrong Bearer returns 401", async () => {
const res = await POST(
new Request("http://localhost/mcp", {
method: "POST",
headers: { Authorization: "Bearer wrong-key" },
body: "{}",
}),
);
assert.equal(res.status, 401);
});

test("POST with valid Bearer is not rejected with 401", () => {
const req = new Request("http://localhost/mcp", {
method: "POST",
headers: { Authorization: `Bearer ${TEST_KEY}` },
body: JSON.stringify({ jsonrpc: "2.0", method: "initialize", id: 1, params: {} }),
});
assert.equal(mcpAuthGate(req), null, "POST must pass auth before MCP transport runs");
});

test("isMcpAuthorized fails closed when MCP_API_KEY is unset", () => {
delete process.env.MCP_API_KEY;
const req = new Request("http://localhost/mcp", {
headers: { Authorization: `Bearer ${TEST_KEY}` },
});
assert.equal(isMcpAuthorized(req), false);
});
});
44 changes: 42 additions & 2 deletions apps/web/app/mcp/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,45 @@
import { timingSafeEqual, createHash } from "node:crypto";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { createRemoteMcpServer } from "@/lib/remote-mcp-server";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const BEARER_PREFIX = "Bearer ";

function digestForCompare(value: string): Buffer {
return createHash("sha256").update(value, "utf8").digest();
}

/** Exported for route tests. Fail closed when MCP_API_KEY is unset. */
export function isMcpAuthorized(req: Request): boolean {
const expected = process.env.MCP_API_KEY?.trim();
if (!expected) return false;
const header = req.headers.get("authorization")?.trim() ?? "";
if (!header.startsWith(BEARER_PREFIX)) return false;
const token = header.slice(BEARER_PREFIX.length);
try {
return timingSafeEqual(digestForCompare(token), digestForCompare(expected));
} catch {
return false;
}
}

export function unauthorizedMcpResponse(): Response {
return Response.json(
{
jsonrpc: "2.0",
error: { code: -32001, message: "Unauthorized." },
id: null,
},
{ status: 401 },
);
}

/** Null when authorized; otherwise the 401 response POST should return. */
export function mcpAuthGate(req: Request): Response | null {
return isMcpAuthorized(req) ? null : unauthorizedMcpResponse();
}

const methodNotAllowed = () =>
Response.json(
{
Expand All @@ -15,6 +51,10 @@ const methodNotAllowed = () =>
);

export async function POST(req: Request) {
const denied = mcpAuthGate(req);
if (denied) return denied;

const { createRemoteMcpServer } = await import("../../lib/remote-mcp-server");
const server = createRemoteMcpServer();
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: undefined,
Expand Down Expand Up @@ -45,4 +85,4 @@ export async function GET() {

export async function DELETE() {
return methodNotAllowed();
}
}
9 changes: 8 additions & 1 deletion apps/web/lib/remote-mcp-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ export function createRemoteMcpServer(): McpServer {
version: "0.1.0",
});

const scanWebsiteAnnotations: ToolAnnotations = {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true,
};

server.registerTool(
"scan_business_website",
{
Expand All @@ -36,7 +43,7 @@ export function createRemoteMcpServer(): McpServer {
inputSchema: {
url: z.string().describe("Public https URL of the business site."),
},
annotations: readOnly,
annotations: scanWebsiteAnnotations,
},
async ({ url }) => {
try {
Expand Down
Loading