import { afterEach, describe, it } from 'bun:test'; import { expect } from 'chai'; import { Server } from 'node:http'; import { AddressInfo } from 'node:net'; import coreCommonStatic from '@celljs/core/lib/common/static-module'; import coreNodeStatic from '@celljs/core/lib/node/static-module'; import httpCommonModule from '@celljs/http/lib/common/module'; import { Application, autoBind, Component, Container, currentThis } from '@celljs/core'; import webCommonModule from '../common/module'; import webNodeModule from './module'; import { Context } from './context'; import { HandlerAdapter } from './handler'; import { Middleware } from './middleware'; import { compose } from './middleware/compose'; import { convertExpressMiddleware } from './middleware/express-middleware-converter'; import { HttpServerUtil } from './server'; /** * web 的 HTTP 行为约定(阶段 1.E 行为测试):经真实 HTTP 请求断言中间件顺序、会话、健康检查和没有处理器时的 404。 * 配置是 core / web / http 的 cell.yml 合并后的默认值。 */ const DEFAULT_CONFIG = { component: { proxy: false }, aop: { enabled: false }, logger: { level: 'error' }, tenant: { enabled: false }, server: { path: '/', port: 3000, host: '127.0.0.1' }, web: { session: { autoCommit: true, maxAge: 86400000, sessionIdKey: 'cell:sessionId', sessionKey: 'cell:session' }, trace: { requestField: 'X-Cell-Trace-ID', responseField: 'X-Cell-Trace-ID' }, health: { url: '/health', method: 'GET' }, cookies: { keys: ['abcdef'] }, route: { cacheSize: 500 } }, http: { client: { headers: {} } }, }; let server: Server | undefined; let app: Application | undefined; afterEach(async () => { await new Promise(r => (server ? server.close(() => r()) : r())); await app?.stop(); server = undefined; app = undefined; }); /** Starts an application with the components defined before the call; a fetch to it. */ async function serve(): Promise<(path: string, init?: RequestInit) => Promise> { currentThis.cellProps = structuredClone(DEFAULT_CONFIG); const container = new Container(coreCommonStatic, coreNodeStatic, httpCommonModule, webCommonModule, webNodeModule, autoBind()); app = container.get(Application); await app.start(); server = HttpServerUtil.createHttpServer(HttpServerUtil.createHandler(container)); await new Promise(r => server!.listen(0, '127.0.0.1', r)); const base = `http://127.0.0.1:${(server!.address() as AddressInfo).port}`; return (path, init) => fetch(base + path, init); } /** A handler for every request below `prefix`, answering what `answer` returns. */ function handler(prefix: string, answer: (ctx: Context) => unknown) { @Component(HandlerAdapter) class Answering implements HandlerAdapter { readonly priority = 100; async canHandle() { return Context.getRequest().path.startsWith(prefix); } async handle() { const response = Context.getResponse(); response.setHeader('content-type', 'application/json'); response.body = JSON.stringify(await answer(Context.getCurrent())); } } return Answering; } describe('web 中间件', () => { it('按 priority 从高到低进入,出来的顺序相反;处理器在最里层', async () => { const order: string[] = []; for (const [name, priority] of [['low', 10], ['high', 9000], ['mid', 500]] as const) { @Component(Middleware) class Recording implements Middleware { readonly priority = priority; async handle(ctx: Context, next: () => Promise) { order.push(`>${name}`); await next(); order.push(`<${name}`); } } void Recording; } handler('/order', () => order.push('handler')); const f = await serve(); expect((await f('/order')).status).to.equal(200); const mine = order.filter(step => /low|mid|high|handler/.test(step)); expect(mine).to.deep.equal(['>high', '>mid', '>low', 'handler', ' { @Component(Middleware) class Gate implements Middleware { readonly priority = 9000; async handle(ctx: Context, next: () => Promise) { if (ctx.request.headers['x-pass'] !== 'yes') { ctx.response.statusCode = 403; ctx.response.end('closed'); return; } await next(); } } let handled = 0; handler('/gate', () => ++handled); const f = await serve(); const closed = await f('/gate'); expect(closed.status).to.equal(403); expect(await closed.text()).to.equal('closed'); expect(handled).to.equal(0); expect((await f('/gate', { headers: { 'x-pass': 'yes' } })).status).to.equal(200); expect([Gate]).to.have.length(1); }); it('没有处理器的请求回答 404', async () => { const f = await serve(); expect((await f('/nothing-here')).status).to.equal(404); }); }); describe('web 会话', () => { it('会话写入后自动提交,下一次请求带上 cookie 就拿到同一份会话', async () => { handler('/count', () => { const session = Context.getSession(); session.count = (session.count ?? 0) + 1; return { count: session.count }; }); const f = await serve(); const first = await f('/count'); expect(await first.json()).to.deep.equal({ count: 1 }); const cookies = first.headers.getSetCookie().map(c => c.split(';')[0]).join('; '); expect(cookies).to.contain('cell:sessionId='); expect(await (await f('/count', { headers: { cookie: cookies } })).json()).to.deep.equal({ count: 2 }); // 没有 cookie:新会话 expect(await (await f('/count')).json()).to.deep.equal({ count: 1 }); }); it('cookie 被篡改(签名不对)时不认,按新会话处理', async () => { handler('/visit', () => { const session = Context.getSession(); session.visits = (session.visits ?? 0) + 1; return { visits: session.visits }; }); const f = await serve(); const first = await f('/visit'); const cookies = first.headers.getSetCookie().map(c => c.split(';')[0]); expect(cookies.some(c => c.startsWith('cell:session.sig='))).to.equal(true); // The data of the session, with another value and the signature of the old one. const forgedData = Buffer.from(JSON.stringify({ id: 'x', visits: 41 })).toString('base64'); const forged = cookies.map(c => (c.startsWith('cell:session=') ? `cell:session=${forgedData}` : c)).join('; '); expect(await (await f('/visit', { headers: { cookie: forged } })).json()).to.deep.equal({ visits: 1 }); }); }); describe('web 健康检查', () => { it('GET /health 回答 UP 的 JSON', async () => { const f = await serve(); const res = await f('/health'); expect(res.status).to.equal(200); expect(res.headers.get('content-type')).to.contain('application/json'); expect((await res.json()).status).to.equal('UP'); }); }); describe('compose 与 express 中间件', () => { it('compose 按顺序调用,最后调用 next;同一个中间件调用两次 next 会被拒绝', async () => { const steps: string[] = []; const mw = (name: string): Middleware => ({ priority: 0, handle: async (ctx, next) => { steps.push(name); await next(); } }); await compose([mw('a'), mw('b')])({} as Context, { priority: 0, handle: async () => { steps.push('end'); } }); expect(steps).to.deep.equal(['a', 'b', 'end']); const twice: Middleware = { priority: 0, handle: async (ctx, next) => { await next(); await next(); } }; const error = await compose([twice])({} as Context, { priority: 0, handle: async () => undefined }).then(() => undefined, e => e); expect(error?.message).to.equal('next() called multiple times'); }); it('express 风格的中间件:next() 继续,next(err) 让请求失败', async () => { const ctx = new Context({ headers: {} } as any, {} as any); await Context.run(async () => { Context.setCurrent(ctx); const seen: string[] = []; const passing = convertExpressMiddleware((req: unknown, res: unknown, next: (e?: unknown) => void) => next()); await passing.handle(ctx, async () => { seen.push('next'); }); expect(seen).to.deep.equal(['next']); const failing = convertExpressMiddleware((req: unknown, res: unknown, next: (e?: unknown) => void) => next(new Error('denied'))); const error = await failing.handle(ctx, async () => { seen.push('never'); }).then(() => undefined, e => e); expect(error?.message).to.equal('denied'); expect(seen).to.deep.equal(['next']); }); }); });