Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
85 changes: 77 additions & 8 deletions src/app/[transport]/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ describe("native OAuth credentials", () => {
let kernelTokens: string[];
let kernelPaths: string[];
let browsersRequested: () => void;
let credentialProjectId: string | null;
let fetchSpy: ReturnType<typeof spyOn<typeof globalThis, "fetch">>;

beforeEach(async () => {
Expand All @@ -156,6 +157,7 @@ describe("native OAuth credentials", () => {
kernelTokens = [];
kernelPaths = [];
browsersRequested = () => {};
credentialProjectId = "proj_123";
defaultMcpDependencies.createKernelClient = (token) => {
kernelTokens.push(token);
return new Kernel({
Expand Down Expand Up @@ -184,7 +186,7 @@ describe("native OAuth credentials", () => {
principal: { type: "user", id: "user_123" },
organization: { id: "org_123" },
authorization: {
credential_scope: { project_id: "proj_123" },
credential_scope: { project_id: credentialProjectId },
effective_scope: { project_id: "proj_123" },
},
});
Expand Down Expand Up @@ -430,11 +432,38 @@ describe("native OAuth credentials", () => {
]);
});

test("post-authentication bugs propagate as server errors", async () => {
failingAuthContext(new Error("unaccountable"));
await expect(POST(mcpRequest(await issuer.parent()))).rejects.toThrow(
"Unable to resolve Kernel connection scope",
// A grant limited to one non-default project names no credential project;
// the API runs its requests in that project.
test("fix a grant's implicit project as the connection scope", async () => {
credentialProjectId = null;
const response = await POST(
mcpRequest(await issuer.parent(), "tools/call", {
name: "get_connection_context",
arguments: {},
}),
);
expect(response.status).toBe(200);
const text = await response.text();
const event = text.split("\n").find((line) => line.startsWith("data: "));
const result = JSON.parse(event ? event.slice(6) : text).result;
expect(result.isError).not.toBe(true);
expect(JSON.parse(result.content[0].text).connection_scope).toEqual({
kind: "project",
organization_id: "org_123",
project_id: "proj_123",
source: "credential",
project_id_required: false,
});
});

test("answer post-authentication bugs with a JSON server error", async () => {
failingAuthContext(new Error("unaccountable"));
const response = await POST(mcpRequest(await issuer.parent()));
expect(response.status).toBe(500);
expect(await response.json()).toEqual({
error: "server_error",
error_description: "Unable to resolve Kernel connection scope",
});
});

describe("end with the exchanged token", () => {
Expand Down Expand Up @@ -705,17 +734,57 @@ describe("connection scope failures through the handler", () => {
test("still surfaces an unaccountable failure as a server error", async () => {
failingAuthContext(new TypeError("cannot read properties of undefined"));

await expect(POST(initializeRequest())).rejects.toThrow(
"Unable to resolve Kernel connection scope",
);
const response = await POST(initializeRequest());

expect(response.status).toBe(500);
expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*");
expect(await response.json()).toEqual({
error: "server_error",
error_description: "Unable to resolve Kernel connection scope",
});
expect(captured).toEqual([
{
stage: "scope",
outcome: "invalid",
credentialType: "api_key",
upstreamStatusCode: undefined,
responseStatusCode: 500,
},
]);
});

test("answers an inconsistent connection scope with a server error", async () => {
defaultMcpDependencies.createKernelClient = () =>
({
auth: {
context: {
retrieve: async () => ({
authentication: {
method: "api_key",
source: "api_key",
credential_id: "key_123",
},
principal: { type: "api_key", id: "key_123" },
organization: { id: "org_123" },
authorization: {
credential_scope: { project_id: "proj_1" },
effective_scope: { project_id: "proj_2" },
},
}),
},
},
}) as never;

const response = await POST(initializeRequest());

expect(response.status).toBe(500);
expect((await response.json()).error).toBe("server_error");
expect(captured[0]).toMatchObject({
stage: "scope",
outcome: "invalid",
responseStatusCode: 500,
});
});
});

describe("capability routing", () => {
Expand Down
21 changes: 13 additions & 8 deletions src/app/[transport]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,15 @@ function createAuthErrorResponse(

export function connectionScopeFailureResponse(
req: Request,
failure: Exclude<McpConnectionContextFailure, { status: "invalid" }>,
failure: McpConnectionContextFailure,
): Response {
if (failure.status === "invalid") {
return errorResponse(
500,
"server_error",
"Unable to resolve Kernel connection scope",
);
}
if (failure.status === "rejected") {
switch (failure.statusCode) {
case 403:
Expand Down Expand Up @@ -202,19 +209,17 @@ function refuseConnection(
failure: McpConnectionContextFailure,
): Response {
if (failure.status === "invalid") {
captureMcpConnectionScopeFailure({
stage,
outcome: failure.status,
credentialType,
});
throw new Error("Unable to resolve Kernel connection scope");
console.error(`Unable to resolve Kernel connection scope at ${stage}`);
}
const response = connectionScopeFailureResponse(req, failure);
captureMcpConnectionScopeFailure({
stage,
outcome: failure.status,
credentialType,
upstreamStatusCode: stage === "scope" ? failure.statusCode : undefined,
upstreamStatusCode:
stage === "scope" && "statusCode" in failure
? failure.statusCode
: undefined,
responseStatusCode: response.status,
});
return response;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/mcp/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export type McpConnectionScopeFailureAnalytics = {
credentialType: McpCredentialType;
// Status the Kernel API returned from /auth/context. Only set for "scope".
upstreamStatusCode?: number;
// Status this server answered with. Unset for "invalid", which throws.
// Status this server answered with.
responseStatusCode?: number;
};

Expand Down
44 changes: 43 additions & 1 deletion src/lib/mcp/auth-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,39 @@ describe("resolveMcpConnectionContext", () => {
});
});

describe("OAuth grants", () => {
const grant = (effectiveProjectId: string | null) =>
response({
method: "jwt",
source: "oauth",
principalType: "user",
principalId: "user_123",
effectiveProjectId,
});

// The API runs a single-project grant's requests in its project, and
// reports a non-default one as the effective scope.
test("fixes a single non-default project grant to that project", () => {
expect(connectionScopeFromAuthContext(grant("project_granted"))).toEqual({
kind: "project",
organizationId: "org_123",
projectId: "project_granted",
source: "credential",
});
});

// The API reports neither a default-project grant nor an all-projects
// grant with an effective project, so both stay organization-wide.
test("keeps default-project and all-projects grants organization-wide", () => {
expect(connectionScopeFromAuthContext(grant(null))).toEqual({
kind: "organization",
organizationId: "org_123",
projectId: null,
source: "credential",
});
});
});

test("rejects inconsistent credential, effective, and server scope", () => {
expect(
connectionScopeFromAuthContext(
Expand All @@ -297,7 +330,7 @@ describe("resolveMcpConnectionContext", () => {
).toBeNull();
expect(
connectionScopeFromAuthContext(
response({ effectiveProjectId: "project_1" }),
response({ credentialProjectId: "project_1" }),
),
).toBeNull();
expect(
Expand All @@ -306,6 +339,15 @@ describe("resolveMcpConnectionContext", () => {
"project_2",
),
).toBeNull();
expect(
connectionScopeFromAuthContext(
response({
credentialProjectId: "project_1",
effectiveProjectId: "project_1",
}),
"project_2",
),
).toBeNull();
});

test("reuses normalized scope across token refreshes in one session", async () => {
Expand Down
11 changes: 10 additions & 1 deletion src/lib/mcp/auth-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,16 @@ export function connectionScopeFromAuthContext(
};
}

if (effectiveProjectId) return null;
// A credential whose grant is limited to one project runs requests that
// name none in that project, so the API reports it as the effective scope.
if (effectiveProjectId) {
return {
kind: "project",
organizationId,
projectId: effectiveProjectId,
source: "credential",
};
}
return {
kind: "organization",
organizationId,
Expand Down
Loading