⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(api): never treat API keys as user sessions
Andrej23464e5c367f
diff --git a/apps/api/src/mcp/controllers/oauth-consent.ts b/apps/api/src/mcp/controllers/oauth-consent.tsindex 3763f7396..1f08b48ac 100644--- a/apps/api/src/mcp/controllers/oauth-consent.ts+++ b/apps/api/src/mcp/controllers/oauth-consent.ts@@ -1,7 +1,7 @@import { HTTPException } from "hono/http-exception";-import { auth } from "../../auth";import { publishEvent } from "../../events";import type { z } from "../../openapi";+import { getUserSession } from "../../utils/get-user-session";import {consumeAuthorizationRequest,createAuthCode,@@ -114,7 +114,7 @@ export async function decideMcpAuthorizationRequest(params: {throwOAuthError(403, "invalid_origin");}- const session = await auth.api.getSession({ headers: params.headers });+ const session = await getUserSession(params.headers);if (!session?.user?.id) throwOAuthError(401, "unauthorized");const request = await getAuthorizationRequest(params.requestId);diff --git a/apps/api/src/utils/authenticate-api-request.ts b/apps/api/src/utils/authenticate-api-request.tsindex 5b8a4230a..d20715181 100644--- a/apps/api/src/utils/authenticate-api-request.ts+++ b/apps/api/src/utils/authenticate-api-request.ts@@ -2,7 +2,7 @@ import * as Sentry from "@sentry/node";import { APIError } from "better-auth/api";import type { Context } from "hono";import { HTTPException } from "hono/http-exception";-import { auth } from "../auth";+import { getUserSession } from "./get-user-session";import { verifyApiKey } from "./verify-api-key";// User is tagged on Sentry's isolation scope; the per-request isolation@@ -22,7 +22,7 @@ function isAuthRejection(error: unknown) {async function getSession(headers: Headers) {try {- return await auth.api.getSession({ headers });+ return await getUserSession(headers);} catch (error) {if (isAuthRejection(error)) {return null;diff --git a/apps/api/src/utils/get-user-session.ts b/apps/api/src/utils/get-user-session.tsnew file mode 100644index 000000000..d00c9e236--- /dev/null+++ b/apps/api/src/utils/get-user-session.ts@@ -0,0 +1,7 @@+import { auth } from "../auth";++export function getUserSession(headers: Headers) {+ const sessionHeaders = new Headers(headers);+ sessionHeaders.delete("x-api-key");+ return auth.api.getSession({ headers: sessionHeaders });+}diff --git a/tests/api-integration/api-key-mixed-credentials.test.ts b/tests/api-integration/api-key-mixed-credentials.test.tsnew file mode 100644index 000000000..b689f96a8--- /dev/null+++ b/tests/api-integration/api-key-mixed-credentials.test.ts@@ -0,0 +1,157 @@+import { createHash, randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { auth } from "../../apps/api/src/auth";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import {+ createAuthorizationRequest,+ registerClient,+} from "../../apps/api/src/mcp/oauth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++vi.mock("../../apps/api/src/storage/s3", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ getPrivateObject: async () => ({+ body: new Uint8Array([1, 2, 3]),+ contentType: "image/png",+ contentLength: 3,+ }),+}));++const invalidBearer = { Authorization: "Bearer not-a-real-token" };++async function createKey(+ userId: string,+ permissions?: Record<string, string[]>,+) {+ const { key } = await auth.api.createApiKey({+ body: { userId, name: "Mixed credentials test", permissions },+ });+ return key;+}++describe("API integration: API key sent with an invalid bearer token", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });++ it("does not turn an administrator API key into a session", async () => {+ const { user } = await createWorkspaceMember();+ await db+ .update(schema.userTable)+ .set({ role: "admin" })+ .where(eq(schema.userTable.id, user.id));+ const key = await createKey(user.id);+ const { app } = createApp();++ const keyOnly = await app.request("/api/admin/users", {+ headers: { "x-api-key": key },+ });+ expect(keyOnly.status).toBe(403);++ const mixed = await app.request("/api/admin/users", {+ headers: { "x-api-key": key, ...invalidBearer },+ });+ expect(mixed.status).toBe(401);+ });++ it("keeps the API key scope", async () => {+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });+ const key = await createKey(user.id, { project: ["read"] });+ const { app } = createApp();+ const createProject = (headers: Record<string, string>) =>+ app.request("/api/project", {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: JSON.stringify({+ name: "Scoped",+ workspaceId: workspace.id,+ icon: "Layout",+ slug: "SCP",+ }),+ });++ const keyOnly = await createProject({ "x-api-key": key });+ expect(keyOnly.status).toBe(403);+ expect(await keyOnly.text()).toBe("Insufficient API key scope");++ const mixed = await createProject({ "x-api-key": key, ...invalidBearer });+ expect(mixed.status).toBe(401);+ expect(+ await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.workspaceId, workspace.id)),+ ).toHaveLength(0);+ });++ it("rejects private asset downloads", async () => {+ const { user, workspace } = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const [asset] = await db+ .insert(schema.assetTable)+ .values({+ workspaceId: workspace.id,+ projectId: project.id,+ objectKey: randomUUID(),+ filename: "image.png",+ mimeType: "image/png",+ size: 3,+ surface: "comment",+ createdBy: user.id,+ })+ .returning();+ const key = await createKey(user.id);+ const { app } = createApp();++ const keyOnly = await app.request(`/api/asset/${asset.id}`, {+ headers: { "x-api-key": key },+ });+ expect(keyOnly.status).toBe(200);++ const mixed = await app.request(`/api/asset/${asset.id}`, {+ headers: { "x-api-key": key, ...invalidBearer },+ });+ expect(mixed.status).toBe(401);+ });+});++describe("API integration: MCP consent with an API key", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });++ it("requires a user session to approve an authorization request", async () => {+ const { user } = await createWorkspaceMember();+ const key = await createKey(user.id, { project: ["read"] });+ const redirectUri = "https://client.example/callback";+ const client = await registerClient({ redirectUris: [redirectUri] });+ const id = await createAuthorizationRequest({+ clientId: client.clientId,+ codeChallenge: createHash("sha256")+ .update("test-verifier")+ .digest("base64url"),+ redirectUri,+ });+ const { app } = createApp();++ const response = await app.request(`/api/mcp/authorize/request/${id}`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ origin: "http://localhost:5173",+ "x-api-key": key,+ },+ body: JSON.stringify({ approved: true }),+ });++ expect(response.status).toBe(401);+ });+});