mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 03:49:41 +00:00
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:
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { auth, authService } from './auth'
|
||||
import { auth, authService, isLoopbackHost, isMcpResourceValid } from './auth'
|
||||
import { userMetadataService } from '../user-metadata/user-metadata'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
|
||||
@@ -326,3 +326,48 @@ describe('AuthService Password Reset', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('MCP Resource Validation & Loopback Checking', () => {
|
||||
it('correctly identifies loopback hostnames', () => {
|
||||
expect(isLoopbackHost('localhost')).toBe(true)
|
||||
expect(isLoopbackHost('127.0.0.1')).toBe(true)
|
||||
expect(isLoopbackHost('127.0.0.254')).toBe(true)
|
||||
expect(isLoopbackHost('[::1]')).toBe(true)
|
||||
|
||||
expect(isLoopbackHost('43.133.100.178')).toBe(false)
|
||||
expect(isLoopbackHost('192.168.1.100')).toBe(false)
|
||||
expect(isLoopbackHost('10.0.0.1')).toBe(false)
|
||||
expect(isLoopbackHost('example.com')).toBe(false)
|
||||
expect(isLoopbackHost('128.0.0.1')).toBe(false)
|
||||
})
|
||||
|
||||
it('validates MCP resource URLs according to RFC 9728 and MCP security rules', () => {
|
||||
// Loopback HTTP URLs are allowed for development
|
||||
expect(isMcpResourceValid('http://localhost:3000/mcp')).toEqual({ valid: true })
|
||||
expect(isMcpResourceValid('http://127.0.0.1:3000/mcp')).toEqual({ valid: true })
|
||||
expect(isMcpResourceValid('http://[::1]:3000/mcp')).toEqual({ valid: true })
|
||||
|
||||
// HTTPS is allowed for any host (including domains and remote IPs)
|
||||
expect(isMcpResourceValid('https://shumai.example.com/mcp')).toEqual({ valid: true })
|
||||
expect(isMcpResourceValid('https://43.133.100.178:3000/mcp')).toEqual({ valid: true })
|
||||
|
||||
// Remote HTTP IPs and hostnames are rejected (the user issue)
|
||||
const remoteIpResult = isMcpResourceValid('http://43.133.100.178:3000/mcp')
|
||||
expect(remoteIpResult.valid).toBe(false)
|
||||
expect(remoteIpResult.error).toContain(
|
||||
'MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs',
|
||||
)
|
||||
|
||||
const remoteDomainResult = isMcpResourceValid('http://shumai.example.com/mcp')
|
||||
expect(remoteDomainResult.valid).toBe(false)
|
||||
expect(remoteDomainResult.error).toContain(
|
||||
'MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs',
|
||||
)
|
||||
|
||||
// Invalid URL formats
|
||||
expect(isMcpResourceValid('not-a-url').valid).toBe(false)
|
||||
expect(isMcpResourceValid('http://user:pass@localhost:3000/mcp').valid).toBe(false)
|
||||
expect(isMcpResourceValid('http://localhost:3000/mcp#frag').valid).toBe(false)
|
||||
expect(isMcpResourceValid('http://localhost:3000/mcp?query=1').valid).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ import { teamService } from '@shumai/core/src/team/team'
|
||||
import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { createAuthMiddleware } from 'better-auth/api'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
interface GeneratedResetLink {
|
||||
url: string
|
||||
@@ -22,22 +23,80 @@ export const authBaseUrl = (
|
||||
export const mcpResource = `${authBaseUrl}/mcp`
|
||||
export { hashPassword } from 'better-auth/crypto'
|
||||
|
||||
/**
|
||||
* Checks whether a host is a loopback address (localhost, 127.0.0.0/8, or [::1]).
|
||||
*/
|
||||
export function isLoopbackHost(hostname: string): boolean {
|
||||
const ipv4Octets = hostname.split('.')
|
||||
const isIpv4Loopback =
|
||||
ipv4Octets.length === 4 &&
|
||||
ipv4Octets[0] === '127' &&
|
||||
ipv4Octets.every((octet) => /^\d+$/.test(octet) && Number(octet) <= 255)
|
||||
return hostname === 'localhost' || hostname === '[::1]' || isIpv4Loopback
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates whether an MCP resource URL meets RFC 9728 and MCP security requirements
|
||||
* (HTTPS required unless using a localhost or loopback IP address).
|
||||
*/
|
||||
export function isMcpResourceValid(resource: string): { valid: boolean; error?: string } {
|
||||
if (typeof resource !== 'string' || !resource) {
|
||||
return { valid: false, error: 'MCP resource must be a non-empty string URL' }
|
||||
}
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(resource)
|
||||
} catch {
|
||||
return { valid: false, error: 'MCP resource must be an absolute URL' }
|
||||
}
|
||||
if (url.username || url.password) {
|
||||
return { valid: false, error: 'MCP resource URL must not contain credentials' }
|
||||
}
|
||||
if (resource.includes('#')) {
|
||||
return { valid: false, error: 'MCP resource URL must not contain a fragment' }
|
||||
}
|
||||
if (resource.includes('?')) {
|
||||
return { valid: false, error: 'MCP resource URL must not contain a query' }
|
||||
}
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHost(url.hostname))) {
|
||||
return {
|
||||
valid: false,
|
||||
error:
|
||||
'MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs',
|
||||
}
|
||||
}
|
||||
return { valid: true }
|
||||
}
|
||||
|
||||
const mcpValidation = isMcpResourceValid(mcpResource)
|
||||
export const isMcpOauthEnabled = mcpValidation.valid
|
||||
if (!isMcpOauthEnabled) {
|
||||
logger.error(
|
||||
{ mcpResource, error: mcpValidation.error },
|
||||
'MCP OAuth 2.1 is disabled: resource URL must use HTTPS for remote hosts. The main server and Web UI will continue running normally, but MCP OAuth clients cannot connect until HTTPS is configured.',
|
||||
)
|
||||
}
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, {
|
||||
provider: 'postgresql',
|
||||
}),
|
||||
plugins: [
|
||||
jwt(),
|
||||
mcp({
|
||||
loginPage: '/login',
|
||||
consentPage: '/consent',
|
||||
resource: mcpResource,
|
||||
resources: [{ identifier: mcpResource, allowedScopes: ['mcp'] }],
|
||||
scopes: ['openid', 'profile', 'email', 'offline_access', 'mcp'],
|
||||
allowDynamicClientRegistration: true,
|
||||
allowUnauthenticatedClientRegistration: true,
|
||||
clientRegistrationDefaultApplicationType: 'infer',
|
||||
}),
|
||||
...(isMcpOauthEnabled
|
||||
? [
|
||||
mcp({
|
||||
loginPage: '/login',
|
||||
consentPage: '/consent',
|
||||
resource: mcpResource,
|
||||
resources: [{ identifier: mcpResource, allowedScopes: ['mcp'] }],
|
||||
scopes: ['openid', 'profile', 'email', 'offline_access', 'mcp'],
|
||||
allowDynamicClientRegistration: true,
|
||||
allowUnauthenticatedClientRegistration: true,
|
||||
clientRegistrationDefaultApplicationType: 'infer',
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
|
||||
Reference in New Issue
Block a user