mirror of
https://github.com/gethomepage/homepage.git
synced 2026-08-30 17:05:52 -07:00
Fix: enforce MCP token length too
This commit is contained in:
+2
-2
@@ -28,7 +28,7 @@ http://your-homepage-instance/api/mcp
|
||||
|
||||
The MCP endpoint requires authentication. Requests from an authenticated Homepage session are allowed when Homepage auth is enabled with `HOMEPAGE_AUTH_ENABLED`.
|
||||
|
||||
For MCP clients that cannot use the browser session, set `HOMEPAGE_MCP_TOKEN`. An MCP token is required when Homepage auth is not enabled. Requests can include either of the following headers:
|
||||
For MCP clients that cannot use the browser session, set `HOMEPAGE_MCP_TOKEN`. An MCP token is required when Homepage auth is not enabled. The token grants read access to every configured service credential and, with writes enabled, control of `custom.js` (which runs in every browser), so it must be at least 32 characters — generate one with `openssl rand -base64 32`. Homepage refuses MCP requests while a shorter token is configured. Requests can include either of the following headers:
|
||||
|
||||
```txt
|
||||
Authorization: Bearer your-token
|
||||
@@ -46,7 +46,7 @@ Example Docker Compose environment block:
|
||||
environment:
|
||||
HOMEPAGE_MCP_ENABLED: "true"
|
||||
HOMEPAGE_AUTH_ENABLED: "true"
|
||||
HOMEPAGE_MCP_TOKEN: "change-me"
|
||||
HOMEPAGE_MCP_TOKEN: "generate-with-openssl-rand-base64-32"
|
||||
```
|
||||
|
||||
## Read-only by default
|
||||
|
||||
@@ -2,7 +2,8 @@ import { getServerSession } from "next-auth/next";
|
||||
|
||||
import { authOptions } from "pages/api/auth/[...nextauth]";
|
||||
import { isAuthEnabled } from "utils/env";
|
||||
import { handleMcpRequest, mcpEnabled, mcpTokenAuthorized } from "utils/mcp/homepage-mcp";
|
||||
import createLogger from "utils/logger";
|
||||
import { handleMcpRequest, mcpEnabled, mcpTokenAuthorized, mcpTokenConfigError } from "utils/mcp/homepage-mcp";
|
||||
|
||||
async function hasHomepageSession(req, res) {
|
||||
if (!isAuthEnabled()) return false;
|
||||
@@ -14,6 +15,12 @@ export default async function handler(req, res) {
|
||||
return res.status(404).end("Not Found");
|
||||
}
|
||||
|
||||
const tokenError = mcpTokenConfigError();
|
||||
if (tokenError) {
|
||||
createLogger("mcp").error(tokenError);
|
||||
return res.status(500).json({ error: "MCP token is misconfigured. See logs for details." });
|
||||
}
|
||||
|
||||
if (!mcpTokenAuthorized(req) && !(await hasHomepageSession(req, res))) {
|
||||
return res.status(401).json({ error: "Unauthorized" });
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { getServerSession } = vi.hoisted(() => ({
|
||||
const { getServerSession, errorMock } = vi.hoisted(() => ({
|
||||
getServerSession: vi.fn(),
|
||||
errorMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("next-auth/next", () => ({ getServerSession }));
|
||||
vi.mock("utils/logger", () => ({ default: () => ({ error: errorMock, warn: vi.fn(), debug: vi.fn() }) }));
|
||||
|
||||
function mockResponse() {
|
||||
const res = {
|
||||
@@ -41,6 +43,7 @@ describe("pages/api/mcp", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
getServerSession.mockReset();
|
||||
errorMock.mockReset();
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
@@ -60,7 +63,7 @@ describe("pages/api/mcp", () => {
|
||||
|
||||
it("requires bearer token when configured", async () => {
|
||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "secret";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "mcp-tok-0123456789abcdefghijklmnopqrstuv";
|
||||
const handler = await loadHandler();
|
||||
const res = mockResponse();
|
||||
|
||||
@@ -69,6 +72,27 @@ describe("pages/api/mcp", () => {
|
||||
expect(res.status).toHaveBeenCalledWith(401);
|
||||
});
|
||||
|
||||
it("fails closed with 500 when the configured MCP token is too short", async () => {
|
||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "change-me";
|
||||
const handler = await loadHandler();
|
||||
const res = mockResponse();
|
||||
|
||||
// even presenting the weak token verbatim must not authorize
|
||||
await handler(
|
||||
{
|
||||
method: "POST",
|
||||
headers: { authorization: "Bearer change-me" },
|
||||
body: { jsonrpc: "2.0", id: 1, method: "tools/list" },
|
||||
},
|
||||
res,
|
||||
);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(500);
|
||||
expect(getServerSession).not.toHaveBeenCalled();
|
||||
expect(errorMock).toHaveBeenCalledWith(expect.stringContaining("at least 32 characters"));
|
||||
});
|
||||
|
||||
it("rejects requests when neither Homepage auth nor an MCP token is configured", async () => {
|
||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
||||
delete process.env.HOMEPAGE_AUTH_ENABLED;
|
||||
@@ -84,14 +108,14 @@ describe("pages/api/mcp", () => {
|
||||
|
||||
it("handles JSON-RPC requests when enabled and authorized", async () => {
|
||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "secret";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "mcp-tok-0123456789abcdefghijklmnopqrstuv";
|
||||
const handler = await loadHandler();
|
||||
const res = mockResponse();
|
||||
|
||||
await handler(
|
||||
{
|
||||
method: "POST",
|
||||
headers: { authorization: "Bearer secret" },
|
||||
headers: { authorization: "Bearer mcp-tok-0123456789abcdefghijklmnopqrstuv" },
|
||||
body: { jsonrpc: "2.0", id: 1, method: "tools/list" },
|
||||
},
|
||||
res,
|
||||
@@ -140,14 +164,14 @@ describe("pages/api/mcp", () => {
|
||||
process.env.HOMEPAGE_AUTH_PASSWORD = "password";
|
||||
process.env.HOMEPAGE_AUTH_SECRET = "rk3Xk9wQ0mVJt7cZbN2yLpA8sHdF4gRuEwTiOaSvBnM=";
|
||||
process.env.HOMEPAGE_EXTERNAL_URL = "https://homepage.example";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "secret";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "mcp-tok-0123456789abcdefghijklmnopqrstuv";
|
||||
const handler = await loadHandler();
|
||||
const res = mockResponse();
|
||||
|
||||
await handler(
|
||||
{
|
||||
method: "POST",
|
||||
headers: { authorization: "Bearer secret" },
|
||||
headers: { authorization: "Bearer mcp-tok-0123456789abcdefghijklmnopqrstuv" },
|
||||
body: { jsonrpc: "2.0", id: 1, method: "tools/list" },
|
||||
},
|
||||
res,
|
||||
@@ -159,14 +183,14 @@ describe("pages/api/mcp", () => {
|
||||
|
||||
it("returns 202 for JSON-RPC notifications", async () => {
|
||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "secret";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "mcp-tok-0123456789abcdefghijklmnopqrstuv";
|
||||
const handler = await loadHandler();
|
||||
const res = mockResponse();
|
||||
|
||||
await handler(
|
||||
{
|
||||
method: "POST",
|
||||
headers: { authorization: "Bearer secret" },
|
||||
headers: { authorization: "Bearer mcp-tok-0123456789abcdefghijklmnopqrstuv" },
|
||||
body: { jsonrpc: "2.0", method: "notifications/initialized" },
|
||||
},
|
||||
res,
|
||||
@@ -178,11 +202,14 @@ describe("pages/api/mcp", () => {
|
||||
|
||||
it("rejects non-POST requests", async () => {
|
||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "secret";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "mcp-tok-0123456789abcdefghijklmnopqrstuv";
|
||||
const handler = await loadHandler();
|
||||
const res = mockResponse();
|
||||
|
||||
await handler({ method: "GET", headers: { authorization: "Bearer secret" }, body: {} }, res);
|
||||
await handler(
|
||||
{ method: "GET", headers: { authorization: "Bearer mcp-tok-0123456789abcdefghijklmnopqrstuv" }, body: {} },
|
||||
res,
|
||||
);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(405);
|
||||
expect(res.setHeader).toHaveBeenCalledWith("Allow", "POST");
|
||||
|
||||
@@ -12,6 +12,8 @@ const SERVER_INFO = {
|
||||
version: "1.0.0",
|
||||
};
|
||||
|
||||
const MIN_TOKEN_LENGTH = 32;
|
||||
|
||||
const CONFIG_FILES = [
|
||||
"settings.yaml",
|
||||
"services.yaml",
|
||||
@@ -442,9 +444,18 @@ export function mcpEnabled() {
|
||||
return enabled();
|
||||
}
|
||||
|
||||
export function mcpTokenConfigError() {
|
||||
if (!enabled()) return null;
|
||||
const token = requiredToken();
|
||||
if (token && token.length < MIN_TOKEN_LENGTH) {
|
||||
return `HOMEPAGE_MCP_TOKEN must be at least ${MIN_TOKEN_LENGTH} characters. Generate one with: openssl rand -base64 32`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function mcpTokenAuthorized(req) {
|
||||
const token = requiredToken();
|
||||
if (!token) return false;
|
||||
if (!token || token.length < MIN_TOKEN_LENGTH) return false;
|
||||
|
||||
const authHeader = req.headers.authorization;
|
||||
const bearerToken = typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.slice(7) : null;
|
||||
|
||||
@@ -622,13 +622,44 @@ describe("utils/mcp/homepage-mcp", () => {
|
||||
|
||||
expect(mod.mcpTokenAuthorized({ headers: {} })).toBe(false);
|
||||
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "secret";
|
||||
expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer secret" } })).toBe(true);
|
||||
expect(mod.mcpTokenAuthorized({ headers: { "x-homepage-mcp-token": "secret" } })).toBe(true);
|
||||
const token = "mcp-tok-0123456789abcdefghijklmnopqrstuv"; // 40 chars
|
||||
process.env.HOMEPAGE_MCP_TOKEN = token;
|
||||
expect(mod.mcpTokenAuthorized({ headers: { authorization: `Bearer ${token}` } })).toBe(true);
|
||||
expect(mod.mcpTokenAuthorized({ headers: { "x-homepage-mcp-token": token } })).toBe(true);
|
||||
expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer wrong" } })).toBe(false);
|
||||
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "é";
|
||||
// multibyte token at the minimum length still authorizes and doesn't throw on byte-length mismatch
|
||||
const multibyteToken = "é".repeat(32);
|
||||
process.env.HOMEPAGE_MCP_TOKEN = multibyteToken;
|
||||
expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer a" } })).toBe(false);
|
||||
expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer é" } })).toBe(true);
|
||||
expect(mod.mcpTokenAuthorized({ headers: { authorization: `Bearer ${multibyteToken}` } })).toBe(true);
|
||||
});
|
||||
|
||||
it("never authorizes a token below the minimum length, even when presented verbatim", async () => {
|
||||
const mod = await loadMcpWithConfigDir(mkdtempSync(path.join(tmpdir(), "homepage-mcp-test-")));
|
||||
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "change-me";
|
||||
expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer change-me" } })).toBe(false);
|
||||
expect(mod.mcpTokenAuthorized({ headers: { "x-homepage-mcp-token": "change-me" } })).toBe(false);
|
||||
});
|
||||
|
||||
it("reports a config error only when MCP is enabled with a too-short token", async () => {
|
||||
const mod = await loadMcpWithConfigDir(mkdtempSync(path.join(tmpdir(), "homepage-mcp-test-")));
|
||||
|
||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "change-me";
|
||||
expect(mod.mcpTokenConfigError()).toMatch(/at least 32 characters/i);
|
||||
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "mcp-tok-0123456789abcdefghijklmnopqrstuv";
|
||||
expect(mod.mcpTokenConfigError()).toBeNull();
|
||||
|
||||
// no token configured is valid (session-only mode), so it is not an error
|
||||
delete process.env.HOMEPAGE_MCP_TOKEN;
|
||||
expect(mod.mcpTokenConfigError()).toBeNull();
|
||||
|
||||
// a weak token is ignored entirely when MCP is disabled
|
||||
process.env.HOMEPAGE_MCP_ENABLED = "false";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "change-me";
|
||||
expect(mod.mcpTokenConfigError()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user