fix(auth,web): gracefully degrade MCP on remote HTTP and cache production static assets (#519)

* fix: gracefully handle remote HTTP URLs for MCP and cache production static assets

* test(mcp): add remote http mcp integration test and fix static etag normalization and fallback error
This commit is contained in:
Yiling-J
2026-11-05 22:21:11 +08:00
committed by GitHub
parent 65e2ac1383
commit f304caea00
12 changed files with 596 additions and 62 deletions
@@ -0,0 +1,100 @@
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { Hono } from 'hono'
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
import { prisma, type User } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { apiTokenService } from '@shumai/core/src/user/api-token'
import { projectService } from '@shumai/core/src/project/project'
describe('MCP server on remote HTTP BETTER_AUTH_URL', () => {
setupTestDbHooks()
const originalEnv = process.env.BETTER_AUTH_URL
let user: User
let token: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let app: Hono<any>
let isMcpOauthEnabled: boolean
beforeAll(async () => {
process.env.BETTER_AUTH_URL = 'http://43.133.100.178:3000'
vi.resetModules()
const authModule = await import('@shumai/core/src/auth/auth')
isMcpOauthEnabled = authModule.isMcpOauthEnabled
const mcpServerModule = await import('./mcp-server')
app = new Hono().route('/', mcpServerModule.default)
user = await prisma.user.create({
data: { name: 'Remote HTTP User', email: `remote-http-${Date.now()}@test.com` },
})
const team = await prisma.team.create({ data: { name: 'Remote HTTP Team' } })
await prisma.teamMember.create({ data: { teamId: team.id, userId: user.id, role: 'owner' } })
await projectService.createProject(user, { teamId: team.id, name: 'Remote HTTP Project' })
const tokenRes = await apiTokenService.createToken(user.id, 'remote-http-test')
token = tokenRes.token
})
afterAll(() => {
if (originalEnv !== undefined) {
process.env.BETTER_AUTH_URL = originalEnv
} else {
delete process.env.BETTER_AUTH_URL
}
vi.resetModules()
})
it('omits MCP OAuth plugin and disables isMcpOauthEnabled', () => {
expect(isMcpOauthEnabled).toBe(false)
})
it('returns 503 Service Unavailable for unauthenticated requests to /mcp', async () => {
const res = await app.request('/mcp', { method: 'POST' })
expect(res.status).toBe(503)
const body = await res.json()
expect(body).toMatchObject({
jsonrpc: '2.0',
error: {
code: -32000,
message: expect.stringContaining(
'MCP OAuth 2.1 is disabled on this server because BETTER_AUTH_URL is not HTTPS',
),
},
id: null,
})
})
it('allows valid API tokens to access /mcp and execute tools even when OAuth is disabled', async () => {
const transport = new StreamableHTTPClientTransport(new URL('http://localhost/mcp'), {
fetch: async (input, init) => {
const headers = new Headers(init?.headers)
headers.set('Authorization', `Bearer ${token}`)
return app.request(String(input), {
...init,
headers,
})
},
})
const client = new Client({ name: 'remote-http-client', version: '1.0.0' })
await client.connect(transport)
expect(client.getServerVersion()).toMatchObject({ name: 'shumai' })
const { tools } = await client.listTools()
expect(tools.length).toBeGreaterThan(0)
expect(tools.map((t) => t.name)).toContain('list_projects')
await client.close()
})
it('rejects invalid API tokens with 401 Unauthorized', async () => {
const res = await app.request('/mcp', {
method: 'POST',
headers: {
Authorization: 'Bearer shumai_invalidtoken1234567890',
},
})
expect(res.status).toBe(401)
})
})
+19 -1
View File
@@ -6,7 +6,7 @@ import { teamService } from '@shumai/core/src/team/team'
import { s3Service } from '@shumai/core/src/s3/s3'
import { createFolderOp, readAssetOp, runOperation } from '@shumai/core/src/operations'
import { MAX_INLINE_IMAGE_BYTES, MAX_INLINE_IMAGES } from './mcp-extensions/read-asset'
import mcpServerRoute, { MCP_SERVER_INSTRUCTIONS } from './mcp-server'
import mcpServerRoute, { disabledOauthHandler, MCP_SERVER_INSTRUCTIONS } from './mcp-server'
vi.mock('@shumai/core/src/operations', async (importOriginal) => ({
...(await importOriginal<typeof import('@shumai/core/src/operations')>()),
@@ -402,4 +402,22 @@ describe('MCP server', () => {
])
})
})
describe('Disabled OAuth Fallback', () => {
it('returns 503 Service Unavailable with standard JSON-RPC error payload', async () => {
const res = await disabledOauthHandler()
expect(res.status).toBe(503)
expect(res.headers.get('content-type')).toContain('application/json')
const body = await res.json()
expect(body).toEqual({
jsonrpc: '2.0',
error: {
code: -32000,
message:
'MCP OAuth 2.1 is disabled on this server because BETTER_AUTH_URL is not HTTPS or a loopback address. Please configure HTTPS or authenticate with a Shumai API token.',
},
id: null,
})
})
})
})
+54 -34
View File
@@ -5,7 +5,7 @@ import type { z } from 'zod'
import type { Prisma } from '@shumai/db'
import { dropNullOptionals } from '@shumai/operations'
import { getOperationsForSurface, runOperation, type Operation } from '@shumai/core/src/operations'
import { auth, authBaseUrl, mcpResource } from '@shumai/core/src/auth/auth'
import { auth, authBaseUrl, isMcpOauthEnabled, mcpResource } from '@shumai/core/src/auth/auth'
import { apiTokenService } from '@shumai/core/src/user/api-token'
import { mcpExtensions, type McpToolExtension } from './mcp-extensions'
import { assertWritableInDemoMode, describeOperationError } from './operation-support'
@@ -134,40 +134,60 @@ const mcpHandler = createMcpHandler(({ authInfo }) => {
return buildMcpServer(userId)
})
const oauthHandler = requireMcpAuth(
auth,
(req, claims) => {
const userId = claims.sub
if (!userId) {
throw new Error('OAuth token has no sub claim')
}
const clientId = (claims.azp as string) ?? (claims.client_id as string) ?? ''
const scopes =
typeof claims.scope === 'string'
? claims.scope.split(' ')
: ((claims.scopes as string[]) ?? [])
return mcpHandler.fetch(req, {
authInfo: {
token: '',
clientId,
scopes,
extra: { userId },
export const disabledOauthHandler = async (): Promise<Response> => {
return new Response(
JSON.stringify({
jsonrpc: '2.0',
error: {
code: -32000,
message:
'MCP OAuth 2.1 is disabled on this server because BETTER_AUTH_URL is not HTTPS or a loopback address. Please configure HTTPS or authenticate with a Shumai API token.',
},
})
},
{
resource: mcpResource,
// In-process verification: avoids HTTP loopback round-trip and works even in test environments
// where no HTTP port is bound.
jwksUrl: (async () => {
const res = await auth.handler(new Request(`${authBaseUrl}/api/auth/jwks`))
if (!res.ok) {
throw new Error(`Failed to load JWKS in-process: ${res.statusText}`)
}
return await res.json()
}) as unknown as string,
},
)
id: null,
}),
{
status: 503,
headers: { 'Content-Type': 'application/json' },
},
)
}
const oauthHandler = isMcpOauthEnabled
? requireMcpAuth(
auth,
(req, claims) => {
const userId = claims.sub
if (!userId) {
throw new Error('OAuth token has no sub claim')
}
const clientId = (claims.azp as string) ?? (claims.client_id as string) ?? ''
const scopes =
typeof claims.scope === 'string'
? claims.scope.split(' ')
: ((claims.scopes as string[]) ?? [])
return mcpHandler.fetch(req, {
authInfo: {
token: '',
clientId,
scopes,
extra: { userId },
},
})
},
{
resource: mcpResource,
// In-process verification: avoids HTTP loopback round-trip and works even in test environments
// where no HTTP port is bound.
jwksUrl: (async () => {
const res = await auth.handler(new Request(`${authBaseUrl}/api/auth/jwks`))
if (!res.ok) {
throw new Error(`Failed to load JWKS in-process: ${res.statusText}`)
}
return await res.json()
}) as unknown as string,
},
)
: disabledOauthHandler
/** Shumai's MCP server (Streamable HTTP). Mounted at `/mcp` with dual API token and OAuth 2.1 auth. */
const route = new Hono<{ Variables: { user: User } }>().all('/mcp', async (c) => {