mirror of
https://github.com/gethomepage/homepage.git
synced 2026-09-26 05:51:17 -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`.
|
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
|
```txt
|
||||||
Authorization: Bearer your-token
|
Authorization: Bearer your-token
|
||||||
@@ -46,7 +46,7 @@ Example Docker Compose environment block:
|
|||||||
environment:
|
environment:
|
||||||
HOMEPAGE_MCP_ENABLED: "true"
|
HOMEPAGE_MCP_ENABLED: "true"
|
||||||
HOMEPAGE_AUTH_ENABLED: "true"
|
HOMEPAGE_AUTH_ENABLED: "true"
|
||||||
HOMEPAGE_MCP_TOKEN: "change-me"
|
HOMEPAGE_MCP_TOKEN: "generate-with-openssl-rand-base64-32"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Read-only by default
|
## Read-only by default
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ import { getServerSession } from "next-auth/next";
|
|||||||
|
|
||||||
import { authOptions } from "pages/api/auth/[...nextauth]";
|
import { authOptions } from "pages/api/auth/[...nextauth]";
|
||||||
import { isAuthEnabled } from "utils/env";
|
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) {
|
async function hasHomepageSession(req, res) {
|
||||||
if (!isAuthEnabled()) return false;
|
if (!isAuthEnabled()) return false;
|
||||||
@@ -14,6 +15,12 @@ export default async function handler(req, res) {
|
|||||||
return res.status(404).end("Not Found");
|
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))) {
|
if (!mcpTokenAuthorized(req) && !(await hasHomepageSession(req, res))) {
|
||||||
return res.status(401).json({ error: "Unauthorized" });
|
return res.status(401).json({ error: "Unauthorized" });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
const { getServerSession } = vi.hoisted(() => ({
|
const { getServerSession, errorMock } = vi.hoisted(() => ({
|
||||||
getServerSession: vi.fn(),
|
getServerSession: vi.fn(),
|
||||||
|
errorMock: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("next-auth/next", () => ({ getServerSession }));
|
vi.mock("next-auth/next", () => ({ getServerSession }));
|
||||||
|
vi.mock("utils/logger", () => ({ default: () => ({ error: errorMock, warn: vi.fn(), debug: vi.fn() }) }));
|
||||||
|
|
||||||
function mockResponse() {
|
function mockResponse() {
|
||||||
const res = {
|
const res = {
|
||||||
@@ -41,6 +43,7 @@ describe("pages/api/mcp", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.resetModules();
|
vi.resetModules();
|
||||||
getServerSession.mockReset();
|
getServerSession.mockReset();
|
||||||
|
errorMock.mockReset();
|
||||||
process.env = { ...originalEnv };
|
process.env = { ...originalEnv };
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -60,7 +63,7 @@ describe("pages/api/mcp", () => {
|
|||||||
|
|
||||||
it("requires bearer token when configured", async () => {
|
it("requires bearer token when configured", async () => {
|
||||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
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 handler = await loadHandler();
|
||||||
const res = mockResponse();
|
const res = mockResponse();
|
||||||
|
|
||||||
@@ -69,6 +72,27 @@ describe("pages/api/mcp", () => {
|
|||||||
expect(res.status).toHaveBeenCalledWith(401);
|
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 () => {
|
it("rejects requests when neither Homepage auth nor an MCP token is configured", async () => {
|
||||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
||||||
delete process.env.HOMEPAGE_AUTH_ENABLED;
|
delete process.env.HOMEPAGE_AUTH_ENABLED;
|
||||||
@@ -84,14 +108,14 @@ describe("pages/api/mcp", () => {
|
|||||||
|
|
||||||
it("handles JSON-RPC requests when enabled and authorized", async () => {
|
it("handles JSON-RPC requests when enabled and authorized", async () => {
|
||||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
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 handler = await loadHandler();
|
||||||
const res = mockResponse();
|
const res = mockResponse();
|
||||||
|
|
||||||
await handler(
|
await handler(
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { authorization: "Bearer secret" },
|
headers: { authorization: "Bearer mcp-tok-0123456789abcdefghijklmnopqrstuv" },
|
||||||
body: { jsonrpc: "2.0", id: 1, method: "tools/list" },
|
body: { jsonrpc: "2.0", id: 1, method: "tools/list" },
|
||||||
},
|
},
|
||||||
res,
|
res,
|
||||||
@@ -140,14 +164,14 @@ describe("pages/api/mcp", () => {
|
|||||||
process.env.HOMEPAGE_AUTH_PASSWORD = "password";
|
process.env.HOMEPAGE_AUTH_PASSWORD = "password";
|
||||||
process.env.HOMEPAGE_AUTH_SECRET = "rk3Xk9wQ0mVJt7cZbN2yLpA8sHdF4gRuEwTiOaSvBnM=";
|
process.env.HOMEPAGE_AUTH_SECRET = "rk3Xk9wQ0mVJt7cZbN2yLpA8sHdF4gRuEwTiOaSvBnM=";
|
||||||
process.env.HOMEPAGE_EXTERNAL_URL = "https://homepage.example";
|
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 handler = await loadHandler();
|
||||||
const res = mockResponse();
|
const res = mockResponse();
|
||||||
|
|
||||||
await handler(
|
await handler(
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { authorization: "Bearer secret" },
|
headers: { authorization: "Bearer mcp-tok-0123456789abcdefghijklmnopqrstuv" },
|
||||||
body: { jsonrpc: "2.0", id: 1, method: "tools/list" },
|
body: { jsonrpc: "2.0", id: 1, method: "tools/list" },
|
||||||
},
|
},
|
||||||
res,
|
res,
|
||||||
@@ -159,14 +183,14 @@ describe("pages/api/mcp", () => {
|
|||||||
|
|
||||||
it("returns 202 for JSON-RPC notifications", async () => {
|
it("returns 202 for JSON-RPC notifications", async () => {
|
||||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
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 handler = await loadHandler();
|
||||||
const res = mockResponse();
|
const res = mockResponse();
|
||||||
|
|
||||||
await handler(
|
await handler(
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { authorization: "Bearer secret" },
|
headers: { authorization: "Bearer mcp-tok-0123456789abcdefghijklmnopqrstuv" },
|
||||||
body: { jsonrpc: "2.0", method: "notifications/initialized" },
|
body: { jsonrpc: "2.0", method: "notifications/initialized" },
|
||||||
},
|
},
|
||||||
res,
|
res,
|
||||||
@@ -178,11 +202,14 @@ describe("pages/api/mcp", () => {
|
|||||||
|
|
||||||
it("rejects non-POST requests", async () => {
|
it("rejects non-POST requests", async () => {
|
||||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
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 handler = await loadHandler();
|
||||||
const res = mockResponse();
|
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.status).toHaveBeenCalledWith(405);
|
||||||
expect(res.setHeader).toHaveBeenCalledWith("Allow", "POST");
|
expect(res.setHeader).toHaveBeenCalledWith("Allow", "POST");
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ const SERVER_INFO = {
|
|||||||
version: "1.0.0",
|
version: "1.0.0",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const MIN_TOKEN_LENGTH = 32;
|
||||||
|
|
||||||
const CONFIG_FILES = [
|
const CONFIG_FILES = [
|
||||||
"settings.yaml",
|
"settings.yaml",
|
||||||
"services.yaml",
|
"services.yaml",
|
||||||
@@ -442,9 +444,18 @@ export function mcpEnabled() {
|
|||||||
return enabled();
|
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) {
|
export function mcpTokenAuthorized(req) {
|
||||||
const token = requiredToken();
|
const token = requiredToken();
|
||||||
if (!token) return false;
|
if (!token || token.length < MIN_TOKEN_LENGTH) return false;
|
||||||
|
|
||||||
const authHeader = req.headers.authorization;
|
const authHeader = req.headers.authorization;
|
||||||
const bearerToken = typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.slice(7) : null;
|
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);
|
expect(mod.mcpTokenAuthorized({ headers: {} })).toBe(false);
|
||||||
|
|
||||||
process.env.HOMEPAGE_MCP_TOKEN = "secret";
|
const token = "mcp-tok-0123456789abcdefghijklmnopqrstuv"; // 40 chars
|
||||||
expect(mod.mcpTokenAuthorized({ headers: { authorization: "Bearer secret" } })).toBe(true);
|
process.env.HOMEPAGE_MCP_TOKEN = token;
|
||||||
expect(mod.mcpTokenAuthorized({ headers: { "x-homepage-mcp-token": "secret" } })).toBe(true);
|
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);
|
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 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