fix(cloud): harden edge gateways, api-server ssrf, supabase fail-closed quota, and web/admin lifecycle
This commit is contained in:
parent
2a009e421a
commit
c68e81e0aa
46 changed files with 2553 additions and 294 deletions
127
server/cloudflare-site-bridge/src/index.test.ts
Normal file
127
server/cloudflare-site-bridge/src/index.test.ts
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import { handleBridgeRequest, resolvePagesTargetUrl, servedByOrigin } from './index.ts'
|
||||
|
||||
function assert(condition: boolean, message: string): asserts condition {
|
||||
if (!condition) throw new Error(message)
|
||||
}
|
||||
|
||||
function assertEquals(actual: unknown, expected: unknown, message: string): void {
|
||||
const a = JSON.stringify(actual)
|
||||
const e = JSON.stringify(expected)
|
||||
if (a !== e) throw new Error(`${message}: expected ${e}, got ${a}`)
|
||||
}
|
||||
|
||||
Deno.test('servedByOrigin_웹앱API경로와랜딩경로_라우팅분기를정확히구분한다', () => {
|
||||
assert(servedByOrigin('/app'), '/app goes to origin')
|
||||
assert(servedByOrigin('/app/login'), '/app/login goes to origin')
|
||||
assert(servedByOrigin('/api/health'), '/api/health goes to origin')
|
||||
assert(servedByOrigin('/health'), '/health goes to origin')
|
||||
assert(!servedByOrigin('/'), '/ goes to pages')
|
||||
assert(!servedByOrigin('/ko/'), '/ko/ goes to pages')
|
||||
assert(!servedByOrigin('/app-info'), '/app-info goes to pages')
|
||||
})
|
||||
|
||||
Deno.test('resolvePagesTargetUrl_경로스머글링_null로차단한다', () => {
|
||||
assertEquals(resolvePagesTargetUrl(new URL('https://d3ro.chanpaca.net//evil.com/path')), null, 'double slash blocked')
|
||||
assertEquals(resolvePagesTargetUrl(new URL('https://d3ro.chanpaca.net/\\evil.com')), null, 'backslash blocked')
|
||||
const valid = resolvePagesTargetUrl(new URL('https://d3ro.chanpaca.net/ko/?utm=1'))
|
||||
assertEquals(valid?.toString(), 'https://d3ro.pages.dev/ko/?utm=1', 'valid pages target')
|
||||
})
|
||||
|
||||
Deno.test('handleBridgeRequest_경로스머글링및루프헤더_요청전달없이실패폐쇄한다', async () => {
|
||||
let called = false
|
||||
const neverFetch: typeof fetch = () => {
|
||||
called = true
|
||||
return Promise.resolve(new Response('unexpected', { status: 200 }))
|
||||
}
|
||||
|
||||
const smuggled = await handleBridgeRequest(new Request('https://d3ro.chanpaca.net//evil.com'), neverFetch)
|
||||
assertEquals(called, false, 'smuggled request must not trigger fetch')
|
||||
assertEquals(smuggled.status, 400, 'smuggled path returns 400')
|
||||
|
||||
const looped = await handleBridgeRequest(
|
||||
new Request('https://d3ro.chanpaca.net/ko/', {
|
||||
headers: { 'X-D3RO-Site-Bridge': '1' },
|
||||
}),
|
||||
neverFetch,
|
||||
)
|
||||
assertEquals(called, false, 'looped request must not trigger fetch')
|
||||
assertEquals(looped.status, 508, 'loop header returns 508')
|
||||
})
|
||||
|
||||
Deno.test('handleBridgeRequest_Pages및원본프록시_홉바이홉헤더제거및타임아웃전달한다', async () => {
|
||||
const seen: Array<{ url: string; init?: RequestInit }> = []
|
||||
const fakeFetch: typeof fetch = (input, init) => {
|
||||
const url = input instanceof Request ? input.url : String(input)
|
||||
const rawHeaders = input instanceof Request
|
||||
? input.headers
|
||||
: (init as { headers?: HeadersInit } | undefined)?.headers
|
||||
const headers = new Headers(rawHeaders)
|
||||
seen.push({
|
||||
url,
|
||||
init: {
|
||||
...(init as RequestInit | undefined),
|
||||
headers,
|
||||
},
|
||||
})
|
||||
return Promise.resolve(
|
||||
new Response('<html>ok</html>', {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'text/html',
|
||||
Connection: 'x-hop-secret',
|
||||
'x-hop-secret': 'drop',
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const pagesResp = await handleBridgeRequest(
|
||||
new Request('https://d3ro.chanpaca.net/en/', {
|
||||
headers: {
|
||||
Host: 'd3ro.chanpaca.net',
|
||||
Connection: 'keep-alive',
|
||||
Accept: 'text/html',
|
||||
},
|
||||
}),
|
||||
fakeFetch,
|
||||
)
|
||||
assertEquals(pagesResp.status, 200, 'pages status')
|
||||
assertEquals(pagesResp.headers.has('x-hop-secret'), false, 'response hop-by-hop stripped')
|
||||
assertEquals(seen[0].url, 'https://d3ro.pages.dev/en/', 'proxied to pages target')
|
||||
assertEquals(seen[0].init?.redirect, 'manual', 'manual redirect')
|
||||
assert(seen[0].init?.signal instanceof AbortSignal, 'timeout signal attached')
|
||||
const sentHeaders = new Headers(seen[0].init?.headers)
|
||||
assertEquals(sentHeaders.has('host'), false, 'host header stripped')
|
||||
assertEquals(sentHeaders.has('connection'), false, 'connection header stripped')
|
||||
assertEquals(sentHeaders.get('x-d3ro-site-bridge'), '1', 'bridge marker set')
|
||||
await pagesResp.body?.cancel()
|
||||
|
||||
const originResp = await handleBridgeRequest(new Request('https://d3ro.chanpaca.net/app/login'), fakeFetch)
|
||||
assertEquals(originResp.status, 200, 'origin status')
|
||||
assertEquals(seen[1].url, 'https://d3ro.chanpaca.net/app/login', 'origin passthrough url')
|
||||
assertEquals(seen[1].init?.redirect, 'manual', 'origin request disables auto-redirect')
|
||||
assert(seen[1].init?.signal instanceof AbortSignal, 'origin request has timeout signal')
|
||||
await originResp.body?.cancel()
|
||||
})
|
||||
|
||||
Deno.test('handleBridgeRequest_업스트림네트워크오류와타임아웃_502및504로실패폐쇄하고무본문응답을처리한다', async () => {
|
||||
const errResp = await handleBridgeRequest(
|
||||
new Request('https://d3ro.chanpaca.net/'),
|
||||
() => Promise.reject(new TypeError('connect failed to internal host')),
|
||||
)
|
||||
assertEquals(errResp.status, 502, 'network error maps to 502')
|
||||
const errText = await errResp.text()
|
||||
assert(!errText.includes('internal host'), 'must not leak error message')
|
||||
|
||||
const timeoutResp = await handleBridgeRequest(
|
||||
new Request('https://d3ro.chanpaca.net/'),
|
||||
() => Promise.reject(new DOMException('timed out', 'TimeoutError')),
|
||||
)
|
||||
assertEquals(timeoutResp.status, 504, 'timeout maps to 504')
|
||||
|
||||
const noContent = await handleBridgeRequest(
|
||||
new Request('https://d3ro.chanpaca.net/favicon.ico'),
|
||||
() => Promise.resolve(new Response(null, { status: 304, headers: { ETag: '"1"' } })),
|
||||
)
|
||||
assertEquals(noContent.status, 304, '304 status preserved without null-body error')
|
||||
})
|
||||
|
|
@ -13,34 +13,137 @@
|
|||
import { API_PATH_PREFIXES, WEB_APP_BASE_PATH } from '../../../packages/core/src/web-urls'
|
||||
|
||||
const PAGES_ORIGIN = 'https://d3ro.pages.dev'
|
||||
const UPSTREAM_TIMEOUT_MS = 30_000
|
||||
const BRIDGE_HEADER = 'X-D3RO-Site-Bridge'
|
||||
const NULL_BODY_STATUSES = new Set([204, 205, 304])
|
||||
const ORIGIN_PATH_PREFIXES: readonly string[] = [WEB_APP_BASE_PATH, ...API_PATH_PREFIXES]
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'connection',
|
||||
'keep-alive',
|
||||
'proxy-authenticate',
|
||||
'proxy-authorization',
|
||||
'te',
|
||||
'trailer',
|
||||
'transfer-encoding',
|
||||
'upgrade',
|
||||
'host',
|
||||
])
|
||||
|
||||
function servedByOrigin(pathname: string): boolean {
|
||||
return ORIGIN_PATH_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`))
|
||||
function stripHopByHopHeaders(headers: Headers): void {
|
||||
const connectionValue = headers.get('connection')
|
||||
if (connectionValue) {
|
||||
for (const token of connectionValue.split(',')) {
|
||||
const name = token.trim().toLowerCase()
|
||||
if (name) headers.delete(name)
|
||||
}
|
||||
}
|
||||
for (const name of HOP_BY_HOP_HEADERS) {
|
||||
headers.delete(name)
|
||||
}
|
||||
}
|
||||
|
||||
async function fromPages(request: Request): Promise<Response> {
|
||||
const target = new URL(request.url)
|
||||
target.protocol = 'https:'
|
||||
target.hostname = new URL(PAGES_ORIGIN).hostname
|
||||
target.port = ''
|
||||
|
||||
const headers = new Headers(request.headers)
|
||||
headers.delete('host')
|
||||
|
||||
const hasBody = request.method !== 'GET' && request.method !== 'HEAD'
|
||||
return fetch(target.toString(), {
|
||||
method: request.method,
|
||||
headers,
|
||||
body: hasBody ? request.body : undefined,
|
||||
redirect: 'manual',
|
||||
function bridgeErrorJson(error: string, message: string, status: number): Response {
|
||||
return new Response(JSON.stringify({ error, message }), {
|
||||
status,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function servedByOrigin(pathname: string): boolean {
|
||||
return ORIGIN_PATH_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`))
|
||||
}
|
||||
|
||||
export function resolvePagesTargetUrl(requestUrl: URL): URL | null {
|
||||
if (requestUrl.pathname.startsWith('//') || requestUrl.pathname.includes('\\')) {
|
||||
return null
|
||||
}
|
||||
const target = new URL(requestUrl.toString())
|
||||
target.protocol = 'https:'
|
||||
target.hostname = new URL(PAGES_ORIGIN).hostname
|
||||
target.port = ''
|
||||
if (target.origin !== PAGES_ORIGIN) {
|
||||
return null
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
function buildForwardHeaders(requestHeaders: Headers): Headers {
|
||||
const headers = new Headers(requestHeaders)
|
||||
stripHopByHopHeaders(headers)
|
||||
headers.set(BRIDGE_HEADER, '1')
|
||||
return headers
|
||||
}
|
||||
|
||||
async function forwardRequest(
|
||||
request: Request,
|
||||
targetUrl: string,
|
||||
fetchImpl: typeof fetch,
|
||||
): Promise<Response> {
|
||||
const headers = buildForwardHeaders(request.headers)
|
||||
const hasBody = request.method !== 'GET' && request.method !== 'HEAD'
|
||||
|
||||
try {
|
||||
const response = await fetchImpl(targetUrl, {
|
||||
method: request.method,
|
||||
headers,
|
||||
body: hasBody ? request.body : undefined,
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
|
||||
})
|
||||
|
||||
const responseHeaders = new Headers(response.headers)
|
||||
stripHopByHopHeaders(responseHeaders)
|
||||
|
||||
let body: ReadableStream<Uint8Array> | null = response.body
|
||||
if (NULL_BODY_STATUSES.has(response.status)) {
|
||||
await response.body?.cancel().catch(() => undefined)
|
||||
body = null
|
||||
}
|
||||
|
||||
return new Response(body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} catch (err: unknown) {
|
||||
const isTimeout = err instanceof DOMException && err.name === 'TimeoutError'
|
||||
return bridgeErrorJson(
|
||||
isTimeout ? 'SiteBridgeTimeout' : 'SiteBridgeError',
|
||||
isTimeout ? 'Upstream request timed out.' : 'Upstream service unavailable.',
|
||||
isTimeout ? 504 : 502,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleBridgeRequest(
|
||||
request: Request,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<Response> {
|
||||
if (request.headers.get(BRIDGE_HEADER)) {
|
||||
return bridgeErrorJson('SiteBridgeLoopDetected', 'Bridge proxy loop detected.', 508)
|
||||
}
|
||||
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname.startsWith('//') || url.pathname.includes('\\')) {
|
||||
return bridgeErrorJson('InvalidBridgeRequest', 'Invalid request path.', 400)
|
||||
}
|
||||
|
||||
if (servedByOrigin(url.pathname)) {
|
||||
return forwardRequest(request, request.url, fetchImpl)
|
||||
}
|
||||
|
||||
const pagesTarget = resolvePagesTargetUrl(url)
|
||||
if (!pagesTarget) {
|
||||
return bridgeErrorJson('InvalidBridgeRequest', 'Invalid target URL.', 400)
|
||||
}
|
||||
return forwardRequest(request, pagesTarget.toString(), fetchImpl)
|
||||
}
|
||||
|
||||
export default {
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const { pathname } = new URL(request.url)
|
||||
if (servedByOrigin(pathname)) return fetch(request)
|
||||
return fromPages(request)
|
||||
fetch(request: Request): Promise<Response> {
|
||||
return handleBridgeRequest(request)
|
||||
},
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue