Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
78 changes: 78 additions & 0 deletions apps/api/src/__tests__/route-policy-enforcement.test.ts

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

1 change: 1 addition & 0 deletions apps/api/src/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export { trpc } from './trpc';
// mcp
export { mcp } from './mcp';
export { mcpRouting } from './mcp/routing';
export { mcpOAuthMetadata } from './mcp-oauth';

// inference gateway
export { inference } from './inference';
Expand Down
23 changes: 23 additions & 0 deletions apps/api/src/handlers/mcp-oauth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Hono } from 'hono';

import { getRoomoteMcpResourceUrl, ROOMOTE_MCP_SCOPE } from '@roomote/auth';
import { Env } from '@roomote/env';

import type { Variables } from '../types';

const ROOMOTE_MCP_PROTECTED_RESOURCE_METADATA_PATH =
'/.well-known/oauth-protected-resource/api/mcp-routing/roomote';

export const mcpOAuthMetadata = new Hono<{ Variables: Variables }>();

mcpOAuthMetadata.get(ROOMOTE_MCP_PROTECTED_RESOURCE_METADATA_PATH, (c) => {
const authorizationServer = Env.R_PUBLIC_URL ?? Env.R_APP_URL;

c.header('Cache-Control', 'public, max-age=3600');
return c.json({
resource: getRoomoteMcpResourceUrl(Env.TRPC_URL),
authorization_servers: [new URL(authorizationServer).origin],
bearer_methods_supported: ['header'],
scopes_supported: [ROOMOTE_MCP_SCOPE],
});
});
12 changes: 12 additions & 0 deletions apps/api/src/handlers/mcp/roomote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,18 @@ async function resolveRoomoteMcpAuth(
};
}

if (
authContext.tokenType === 'mcp' &&
authContext.resource ===
new URL('/api/mcp-routing/roomote', Env.TRPC_URL).toString() &&
authContext.scopes.includes('mcp:roomote')
) {
return {
userId: authContext.userId,
tokenType: 'auth',
};
}

throw new McpProxyError(
403,
`${PRODUCT_NAME} MCP requires a user-scoped auth token or task run token`,
Expand Down
37 changes: 31 additions & 6 deletions apps/api/src/middleware/__tests__/tokenAuthMiddleware.test.ts

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

29 changes: 27 additions & 2 deletions apps/api/src/middleware/routePolicyMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { createHash } from 'node:crypto';
import type { Context } from 'hono';
import { createMiddleware } from 'hono/factory';

import type { RunTokenContext } from '@roomote/types';
import type { McpAccessTokenContext, RunTokenContext } from '@roomote/types';
import { getRedis } from '@roomote/redis';

import type { Variables } from '../types';
Expand Down Expand Up @@ -40,6 +40,12 @@ function isRunTokenContext(
return Boolean(auth && 'runId' in auth);
}

function isMcpTokenContext(
auth: Variables['authContext'],
): auth is McpAccessTokenContext {
return auth?.tokenType === 'mcp';
}

/**
* Pure policy evaluation: given a route's declared policy class and the
* request's validated auth context, decide whether the request may proceed.
Expand All @@ -61,6 +67,14 @@ export function evaluateRoutePolicy(
// in `server.ts` (outside development).
return undefined;
case 'authenticated':
if (!authContext) {
return { status: 401, body: { error: 'authentication_required' } };
}
if (isMcpTokenContext(authContext)) {
return { status: 403, body: { error: 'mcp_token_not_allowed' } };
}
return undefined;
case 'roomote-mcp':
if (!authContext) {
return { status: 401, body: { error: 'authentication_required' } };
}
Expand All @@ -69,7 +83,7 @@ export function evaluateRoutePolicy(
if (!authContext) {
return { status: 401, body: { error: 'authentication_required' } };
}
if (isRunTokenContext(authContext)) {
if (authContext.tokenType !== 'auth') {
return { status: 403, body: { error: 'user_token_required' } };
}
return undefined;
Expand All @@ -89,6 +103,17 @@ function rejectionResponse(
rule: RoutePolicyRule,
rejection: RoutePolicyRejection,
): Response {
if (rule.name === 'roomote-mcp' && rejection.status === 401) {
const resourceMetadata = new URL(
'/.well-known/oauth-protected-resource/api/mcp-routing/roomote',
c.req.url,
);
c.header(
'WWW-Authenticate',
`Bearer resource_metadata="${resourceMetadata.toString()}"`,
);
}

if (rule.errorFormat === 'json-rpc') {
// Match the JSON-RPC error envelope the MCP handlers emit themselves
// (see `handlers/mcp/proxy-utils.ts`) so Streamable HTTP clients that
Expand Down
42 changes: 33 additions & 9 deletions apps/api/src/middleware/tokenAuthMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import type { Context, Next } from 'hono';
import { createMiddleware } from 'hono/factory';

import { validateRunToken, validateAuthToken } from '@roomote/auth';
import {
validateAuthToken,
validateMcpAccessToken,
validateRunToken,
} from '@roomote/auth';
import { db, deploymentSettings, eq, users } from '@roomote/db/server';
import { isRoomoteDeploymentDisabled } from '@roomote/types';

Expand Down Expand Up @@ -71,23 +75,43 @@ export const tokenAuthMiddleware = () =>
return;
}

let userScopedAuth:
| Awaited<ReturnType<typeof validateMcpAccessToken>>
| Awaited<ReturnType<typeof validateAuthToken>>
| undefined;

try {
const authContext = await validateAuthToken(token);
if (await deploymentAllowsTokenAuth()) {
userScopedAuth = await validateMcpAccessToken(token);
} catch {
// Not an MCP OAuth token, try the internal user auth token below.
}

try {
userScopedAuth ??= await validateAuthToken(token);
} catch (error) {
if (!userScopedAuth) {
console.error(
`Failed to validate token: ${error instanceof Error ? error.message : String(error)}`,
);
}
}

if (userScopedAuth && (await deploymentAllowsTokenAuth())) {
try {
const user = await db.query.users.findFirst({
where: eq(users.id, authContext.userId),
where: eq(users.id, userScopedAuth.userId),
columns: { id: true, deletedAt: true },
});

// Removed users keep no standing access: their API tokens die with them.
if (user && user.deletedAt == null) {
c.set('authContext', authContext);
c.set('authContext', userScopedAuth);
}
} catch (error) {
console.error(
`Failed to resolve token user: ${error instanceof Error ? error.message : String(error)}`,
);
}
} catch (error) {
console.error(
`Failed to validate token: ${error instanceof Error ? error.message : String(error)}`,
);
}
}

Expand Down
Loading
Loading