155 lines
8.5 KiB
JavaScript
155 lines
8.5 KiB
JavaScript
'use strict'
|
||
|
||
// functions/api/*.js 的行为测试(此前这两个 Pages 函数无任何自动化测试)。
|
||
// 用 Node 全局 Request/Response 调用 onRequest,并 mock 全局 fetch。
|
||
|
||
const assert = require('assert')
|
||
const path = require('path')
|
||
|
||
const calls = []
|
||
function setFetch(handler) {
|
||
globalThis.fetch = async (url, init) => {
|
||
const u = String(url)
|
||
calls.push({ url: u, init: init || {} })
|
||
return handler(u, init || {})
|
||
}
|
||
}
|
||
const req = (method, url, headers, body) => new Request(url, { method, headers: headers || {}, body })
|
||
const jsonReq = (url, payload, headers) => req('POST', url, Object.assign({ 'Content-Type': 'application/json' }, headers || {}), JSON.stringify(payload))
|
||
const noAcao = (res) => assert.strictEqual(res.headers.get('access-control-allow-origin'), null, '不应再有 CORS *')
|
||
|
||
;(async () => {
|
||
const img = await import(path.join(__dirname, '..', 'functions', 'api', 'img.js'))
|
||
|
||
// ---------- img.js ----------
|
||
const IMG = 'https://d1.cloudfront.net/a.png'
|
||
const okImg = () => new Response('PNGDATA', { status: 200, headers: { 'Content-Type': 'image/png' } })
|
||
const imgUrl = (host, p) => 'https://site.example/api/img?url=' + encodeURIComponent('https://' + host + (p || '/a.png'))
|
||
|
||
// 1) 非 https 400
|
||
setFetch(okImg)
|
||
let r = await img.onRequest({ request: req('GET', 'https://site.example/api/img?url=' + encodeURIComponent('http://d1.cloudfront.net/a.png')) })
|
||
assert.strictEqual(r.status, 400, 'img: http 应 400')
|
||
|
||
// 2) 非白名单 host 403
|
||
setFetch(okImg)
|
||
r = await img.onRequest({ request: req('GET', imgUrl('evil.example')) })
|
||
assert.strictEqual(r.status, 403, 'img: 非白名单 host 应 403')
|
||
|
||
// 3) 跨域 Origin 403
|
||
setFetch(okImg)
|
||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net'), { Origin: 'https://evil.example' }) })
|
||
assert.strictEqual(r.status, 403, 'img: 跨域 Origin 应 403')
|
||
|
||
// 4) 直连白名单 host 放行,无 CORS *,透传 image/*
|
||
setFetch(okImg)
|
||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||
assert.strictEqual(r.status, 200, 'img: 白名单 host 应 200')
|
||
assert.strictEqual(r.headers.get('content-type'), 'image/png', 'img: 应透传 image/png')
|
||
noAcao(r)
|
||
|
||
// 5) 重定向到非白名单 host 403(手动跟随并复检)
|
||
calls.length = 0
|
||
setFetch((u) => u.indexOf('d1.cloudfront.net') >= 0
|
||
? new Response(null, { status: 302, headers: { Location: 'https://evil.example/x.png' } })
|
||
: okImg())
|
||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||
assert.strictEqual(r.status, 403, 'img: 重定向到非白名单应 403')
|
||
|
||
// 6) 重定向到白名单 host 应跟随成功
|
||
calls.length = 0
|
||
setFetch((u) => u.indexOf('d1.cloudfront.net') >= 0
|
||
? new Response(null, { status: 302, headers: { Location: 'https://other.aliyuncs.com/b.png' } })
|
||
: okImg())
|
||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||
assert.strictEqual(r.status, 200, 'img: 重定向到白名单 host 应跟随 200')
|
||
assert.strictEqual(calls.length, 2, 'img: 应发生两跳请求')
|
||
|
||
// 7) 无 Location 的重定向 502
|
||
setFetch(() => new Response(null, { status: 302 }))
|
||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||
assert.strictEqual(r.status, 502, 'img: 重定向缺 Location 应 502')
|
||
|
||
// 8) content-length 超限 413
|
||
setFetch(() => new Response(null, { status: 200, headers: { 'Content-Type': 'image/png', 'Content-Length': '99999999' } }))
|
||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||
assert.strictEqual(r.status, 413, 'img: 超大 content-length 应 413')
|
||
|
||
// 9) 非图片 content-type 415
|
||
setFetch(() => new Response('{"a":1}', { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||
assert.strictEqual(r.status, 415, 'img: 非图片应 415')
|
||
|
||
// 10) 安全头:Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
|
||
// ⇒ 每个 Response 必须自带 nosniff + Referrer-Policy(否则未来某端点漏设 Content-Type
|
||
// 时浏览器会自行嗅探类型 → 可能演变成 XSS)。这是 H1 的回归守卫。
|
||
const hasSecurityHeaders = (res, who) => {
|
||
assert.strictEqual(res.headers.get('x-content-type-options'), 'nosniff', who + ': 应有 X-Content-Type-Options: nosniff')
|
||
assert.strictEqual(res.headers.get('referrer-policy'), 'no-referrer', who + ': 应有 Referrer-Policy: no-referrer')
|
||
}
|
||
setFetch(okImg)
|
||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||
assert.strictEqual(r.status, 200, 'img: 正常取图应 200')
|
||
hasSecurityHeaders(r, 'img 成功响应')
|
||
r = await img.onRequest({ request: req('GET', imgUrl('evil.example')) })
|
||
hasSecurityHeaders(r, 'img 403 响应')
|
||
r = await img.onRequest({ request: req('GET', 'https://site.example/api/img?url=' + encodeURIComponent('http://d1.cloudfront.net/a.png')) })
|
||
hasSecurityHeaders(r, 'img 400 响应')
|
||
|
||
// ---------- plugins/[[path]].js ----------
|
||
const pluginsFn = await import(path.join(__dirname, '..', 'functions', 'plugins', '[[path]].js'))
|
||
const pluginCtx = (tail, value, headers) => ({
|
||
params: { path: [tail] },
|
||
env: value === undefined ? {} : { PLUGINS: { get: async () => value } },
|
||
request: req('GET', 'https://site.example/plugins/' + tail, headers || {}),
|
||
})
|
||
|
||
// P1) 带内容哈希的 JS 名 → immutable + max-age=31536000
|
||
let pr = await pluginsFn.onRequestGet(pluginCtx('plugin-xianyi-cutout.0123456789ab.js', 'console.log(1)'))
|
||
assert.strictEqual(pr.status, 200, 'plugins: 带哈希 JS 应 200')
|
||
assert.strictEqual(pr.headers.get('content-type'), 'application/javascript; charset=utf-8', 'plugins: 带哈希 JS 应为 application/javascript')
|
||
assert.ok((pr.headers.get('cache-control') || '').indexOf('immutable') >= 0, 'plugins: 带哈希 JS 应含 immutable')
|
||
assert.ok((pr.headers.get('cache-control') || '').indexOf('max-age=31536000') >= 0, 'plugins: 带哈希 JS 应含 max-age=31536000')
|
||
|
||
// P2) 未哈希的 JS 名 → no-cache + 非空 etag(安全网,绝不许永久缓存)
|
||
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-xianyi-cutout.js', 'console.log(1)'))
|
||
assert.strictEqual(pr.headers.get('cache-control'), 'no-cache', 'plugins: 未哈希 JS 应 no-cache')
|
||
assert.ok(pr.headers.get('etag'), 'plugins: 未哈希 JS 应有非空 etag')
|
||
|
||
// P3) index.json → no-cache + 非空 etag,body 等于 KV 里的值
|
||
const manifest = '[{"id":"xianyi-cutout"}]'
|
||
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', manifest))
|
||
assert.strictEqual(pr.headers.get('content-type'), 'application/json; charset=utf-8', 'plugins: index.json 应为 application/json')
|
||
assert.strictEqual(pr.headers.get('cache-control'), 'no-cache', 'plugins: index.json 应 no-cache')
|
||
const manifestEtag = pr.headers.get('etag')
|
||
assert.ok(manifestEtag, 'plugins: index.json 应有非空 etag')
|
||
assert.strictEqual(await pr.text(), manifest, 'plugins: index.json body 应等于存储值')
|
||
|
||
// P4) if-none-match 命中 → 304 + 空 body + 同 etag
|
||
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', manifest, { 'if-none-match': manifestEtag }))
|
||
assert.strictEqual(pr.status, 304, 'plugins: if-none-match 命中应 304')
|
||
assert.strictEqual(await pr.text(), '', 'plugins: 304 应为空 body')
|
||
assert.strictEqual(pr.headers.get('etag'), manifestEtag, 'plugins: 304 应带相同 etag')
|
||
|
||
// P5) 缺 KV 绑定 → 500
|
||
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', undefined))
|
||
assert.strictEqual(pr.status, 500, 'plugins: 缺 PLUGINS 绑定应 500')
|
||
|
||
// P6) 未知键(KV 返回 null)→ 404 + no-store
|
||
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-nope.js', null))
|
||
assert.strictEqual(pr.status, 404, 'plugins: 未知键应 404')
|
||
assert.strictEqual(pr.headers.get('cache-control'), 'no-store', 'plugins: 404 应 no-store')
|
||
|
||
// P7) 安全头:`_headers` 不作用于 Functions 响应 ⇒ 每个 Response 自带 nosniff + Referrer-Policy
|
||
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-xianyi-cutout.0123456789ab.js', 'console.log(1)'))
|
||
hasSecurityHeaders(pr, 'plugins 200 响应')
|
||
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', manifest))
|
||
hasSecurityHeaders(pr, 'plugins 清单 200 响应')
|
||
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-nope.js', null))
|
||
hasSecurityHeaders(pr, 'plugins 404 响应')
|
||
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', undefined))
|
||
hasSecurityHeaders(pr, 'plugins 500 响应')
|
||
|
||
console.log('functions api tests passed')
|
||
})().catch((e) => { console.error(e); process.exit(1) })
|