Skip to content
Merged
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
4 changes: 2 additions & 2 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"@modelcontextprotocol/core": "2.0.0",
"@modelcontextprotocol/server": "2.0.0",
"@onkernel/managed-auth-react": "0.5.5",
"@onkernel/sdk": "0.148.0",
"@onkernel/sdk": "0.152.0",
"@posthog/mcp": "0.17.0",
"@types/jsonwebtoken": "^9.0.10",
"@types/redis": "^4.0.11",
Expand Down
67 changes: 65 additions & 2 deletions src/app/[transport]/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ mock.module("@/lib/mcp-apps-request", () => ({
const originalCreateKernelClient = defaultMcpDependencies.createKernelClient;
const { GET, POST, connectionScopeFailureResponse } = await import("./route");

function initializeRequest(token = "sk_opaque_key") {
return new Request("https://mcp.example.test/sse", {
function initializeRequest(token = "sk_opaque_key", path = "/sse") {
return new Request(`https://mcp.example.test${path}`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
Expand Down Expand Up @@ -513,6 +513,69 @@ describe("native OAuth credentials", () => {
});
});

describe("workload-identity credentials", () => {
test(
"sends an API-audience JWT to the Kernel API instead of Clerk",
async () => {
const kernelTokens: string[] = [];
defaultMcpDependencies.createKernelClient = (token) => {
kernelTokens.push(token);
return {
auth: {
context: {
retrieve: async () => ({
authentication: {
method: "jwt",
source: "api_key",
credential_id: null,
},
principal: { type: "service_account", id: "svc_123" },
organization: { id: "org_123" },
authorization: {
credential_scope: { project_id: "proj_123" },
effective_scope: { project_id: "proj_123" },
effective_policy: {
statements: [
{
action: "browsers:use",
resource: "projects/proj_123/browsers/*",
},
],
},
},
workload_identity: {
issuer_id: "wii_123",
federation_rule_id: "wifr_123",
external_subject_digest: "sha256:subject-digest",
},
}),
},
},
} as never;
};
const token = [
Buffer.from(JSON.stringify({ alg: "HS256", typ: "at+jwt" })).toString(
"base64url",
),
Buffer.from(
JSON.stringify({
sub: "svc_123",
aud: ["https://api.onkernel.com"],
}),
).toString("base64url"),
Buffer.from("not-a-real-signature").toString("base64url"),
].join(".");

const response = await POST(initializeRequest(token, "/mcp"));

expect(response.status).toBe(200);
expect(await response.text()).toContain('"result"');
expect(kernelTokens).toEqual([token]);
},
10_000,
);
});

describe("unauthenticated discovery", () => {
for (const method of ["GET", "POST"]) {
test.each([
Expand Down
49 changes: 36 additions & 13 deletions src/app/[transport]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,32 @@ async function handleMcpRequestWithIdentity({
});
}

async function handleKernelCredentialRequest({
req,
token,
transportSessionId,
observeConnection,
}: {
req: NextRequest;
token: string;
transportSessionId: string | null;
observeConnection: boolean;
}): Promise<Response> {
// Kernel-native credentials (API keys and workload-identity access tokens)
// are authenticated by /auth/context rather than Clerk. Do not cache their
// context: every request must revalidate revocation, expiry, and policy.
return await handleMcpRequestWithIdentity({
req,
token,
authSubject: mcpAppsAuthSubject({ token }),
scopes: ["apikey"],
authInfoExtra: { userId: null, clerkToken: null },
credentialType: "api_key",
transportSessionId,
observeConnection,
});
}

async function handleAuthenticatedRequest(
req: NextRequest,
transportSessionId: string | null = null,
Expand Down Expand Up @@ -340,16 +366,9 @@ async function handleAuthenticatedRequest(
}

if (!isValidJwtFormat(token)) {
// Opaque API keys are authenticated by the Kernel API rather than Clerk.
// Do not cache their context: /auth/context must revalidate the credential
// on every request so revoked keys cannot keep using a cached scope.
return await handleMcpRequestWithIdentity({
return await handleKernelCredentialRequest({
req,
token,
authSubject: mcpAppsAuthSubject({ token }),
scopes: ["apikey"],
authInfoExtra: { userId: null, clerkToken: null },
credentialType: "api_key",
transportSessionId,
observeConnection,
});
Expand All @@ -368,12 +387,16 @@ async function handleAuthenticatedRequest(
);
}
userId = payload.sub;
} catch (authError) {
return createAuthErrorResponse(
} catch {
// Workload-identity federation can issue compact JWT access tokens. They
// are not Clerk sessions, so let the Kernel API authenticate them. A
// foreign or malformed JWT is still rejected by /auth/context.
return await handleKernelCredentialRequest({
req,
"invalid_token",
`Invalid token: ${authError instanceof Error ? authError.message : "Authentication failed"}`,
);
token,
transportSessionId,
observeConnection,
});
}

// Capability state is keyed only after Clerk verifies the JWT, and uses
Expand Down
88 changes: 87 additions & 1 deletion src/lib/mcp/auth-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function response({
}: {
method?: "api_key" | "jwt";
source?: "api_key" | "oauth" | "dashboard";
principalType?: "api_key" | "user";
principalType?: "api_key" | "service_account" | "user";
principalId?: string;
credentialProjectId?: string | null;
effectiveProjectId?: string | null;
Expand Down Expand Up @@ -133,6 +133,66 @@ describe("resolveMcpConnectionContext", () => {
).toBe("project");
});

test("treats service-account principals as API-key authentication", async () => {
const context = expectResolved(
await resolveMcpConnectionContext({
token: "sk_service_secret",
dependencies: dependencies(
response({
principalType: "service_account",
principalId: "svc_123",
credentialProjectId: "project_123",
effectiveProjectId: "project_123",
}),
),
}),
);

expect(connectionAnalyticsFromContext(context, "api_key")).toEqual({
authMethod: "api_key",
credentialScope: "project",
connectionScope: "project",
scopeSource: "credential",
organizationId: "org_123",
userId: null,
});
});

test("treats workload-identity access tokens as Kernel-native authentication", async () => {
const context = expectResolved(
await resolveMcpConnectionContext({
token: "header.payload.signature",
dependencies: dependencies({
authentication: {
method: "jwt",
source: "api_key",
credential_id: null,
},
principal: { type: "service_account", id: "svc_123" },
organization: { id: "org_123" },
authorization: {
credential_scope: { project_id: "project_123" },
effective_scope: { project_id: "project_123" },
},
workload_identity: {
issuer_id: "wii_123",
federation_rule_id: "wifr_123",
external_subject_digest: "sha256:subject-digest",
},
}),
}),
);

expect(connectionAnalyticsFromContext(context, "api_key")).toEqual({
authMethod: "api_key",
credentialScope: "project",
connectionScope: "project",
scopeSource: "credential",
organizationId: "org_123",
userId: null,
});
});

test("uses the canonical OAuth user principal for analytics", async () => {
const context = expectResolved(
await resolveMcpConnectionContext({
Expand Down Expand Up @@ -179,11 +239,37 @@ describe("resolveMcpConnectionContext", () => {
dependencies: dependencies(response({})),
}),
);
const mismatchedWorkloadContext = expectResolved(
await resolveMcpConnectionContext({
token: "header.payload.signature",
dependencies: dependencies({
authentication: {
method: "jwt",
source: "oauth",
credential_id: null,
},
principal: { type: "service_account", id: "svc_123" },
organization: { id: "org_123" },
authorization: {
credential_scope: { project_id: "project_123" },
effective_scope: { project_id: "project_123" },
},
workload_identity: {
issuer_id: "wii_123",
federation_rule_id: "wifr_123",
external_subject_digest: "sha256:subject-digest",
},
}),
}),
);

expect(connectionAnalyticsFromContext(oauthContext, "api_key")).toBeNull();
expect(
connectionAnalyticsFromContext(apiKeyContext, "native_oauth"),
).toBeNull();
expect(
connectionAnalyticsFromContext(mismatchedWorkloadContext, "api_key"),
).toBeNull();
});

test("normalizes KERNEL_PROJECT as a server pin", () => {
Expand Down
39 changes: 35 additions & 4 deletions src/lib/mcp/auth-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,30 @@ import {
type McpDependencies,
} from "@/lib/mcp/dependencies";

const policyConditionSchema = z.object({
key: z.literal("source_ip"),
operator: z.literal("in"),
values: z.array(z.string()),
});

const effectivePolicySchema = z.object({
statements: z.array(
z.object({
action: z.string(),
resource: z.string(),
condition: policyConditionSchema.optional(),
}),
),
});

const authContextSchema: z.ZodType<AuthContext> = z.object({
authentication: z.object({
method: z.enum(["api_key", "jwt"]),
source: z.enum(["api_key", "oauth", "dashboard"]),
credential_id: z.string().nullable(),
}),
principal: z.object({
type: z.enum(["api_key", "user"]),
type: z.enum(["api_key", "user", "service_account"]),
id: z.string().min(1),
}),
organization: z.object({
Expand All @@ -23,7 +39,15 @@ const authContextSchema: z.ZodType<AuthContext> = z.object({
authorization: z.object({
credential_scope: z.object({ project_id: z.string().nullable() }),
effective_scope: z.object({ project_id: z.string().nullable() }),
effective_policy: effectivePolicySchema.optional(),
}),
workload_identity: z
.object({
issuer_id: z.string().min(1),
federation_rule_id: z.string().min(1),
external_subject_digest: z.string().min(1),
})
.optional(),
});

export type ConnectionScope =
Expand Down Expand Up @@ -271,10 +295,17 @@ export function connectionAnalyticsFromContext(
{ authContext, scope }: McpConnectionContext,
credentialType: McpCredentialType,
): McpConnectionAnalyticsContext | null {
const isApiKey =
authContext.authentication.method === "api_key" &&
const isWorkloadIdentity =
authContext.authentication.method === "jwt" &&
authContext.authentication.source === "api_key" &&
authContext.principal.type === "api_key";
authContext.principal.type === "service_account" &&
authContext.workload_identity !== undefined;
const isApiKey =
(authContext.authentication.method === "api_key" &&
authContext.authentication.source === "api_key" &&
(authContext.principal.type === "api_key" ||
authContext.principal.type === "service_account")) ||
isWorkloadIdentity;
const isOAuth =
authContext.authentication.method === "jwt" &&
authContext.authentication.source === "oauth" &&
Expand Down
12 changes: 12 additions & 0 deletions src/lib/mcp/browser-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,22 @@

import { expect, test } from "bun:test";
import {
browserCaptchaSolverSchema,
buildBrowserCreateConfig,
buildBrowserUpdateConfig,
} from "@/lib/mcp/browser-config";

test("captcha solver config preserves false and rejects extra fields", () => {
expect(browserCaptchaSolverSchema.parse({ enabled: false })).toEqual({
enabled: false,
});
expect(browserCaptchaSolverSchema.safeParse({}).success).toBe(false);
expect(
browserCaptchaSolverSchema.safeParse({ enabled: true, provider: "other" })
.success,
).toBe(false);
});

test("browser create config rejects an empty start URL", () => {
expect(buildBrowserCreateConfig({ start_url: "" })).toEqual({
ok: false,
Expand Down
Loading
Loading