fix: 恢复缓存按账号隔离并拒绝未认证登记

- Entry 记录发起请求的登录账号,GET /api/requests/:id 仅返回本人响应,他人编号返回 404
- 未认证请求即使带 X-Request-Id 也不登记;401/403 响应即时释放缓存名额
- 已存在的请求编号不被新请求覆盖,避免不同请求响应串换
- 补充未认证、跨账号、401/403 与覆盖保护的集成测试

Fixes #171
This commit is contained in:
margrop
2026-12-04 09:25:51 +08:00
parent 794d86e171
commit c4fb817271
4 changed files with 95 additions and 10 deletions

View File

@@ -6,7 +6,7 @@ import { NextResponse } from 'next/server';
const mocks = vi.hoisted(() => ({
user: { findUnique: vi.fn() },
session: { user: { email: 'user@example.com' }, expires: '2099-01-01' } as { user: { email: string }; expires: string } | null,
session: { user: { id: 'user-1', email: 'user@example.com' }, expires: '2099-01-01' } as { user: { id: string; email: string }; expires: string } | null,
}));
vi.mock('@/lib/prisma', () => ({ prisma: { user: mocks.user } }));
@@ -20,12 +20,19 @@ const id = 'a'.repeat(32);
const lookup = (requestId = id) => GET(new Request('http://localhost'), { params: Promise.resolve({ id: requestId }) });
const call = (handler: (req: Request) => Promise<Response>, headers: Record<string, string> = { 'X-Request-Id': id }) =>
withRecoverableResponse(handler)(new Request('http://localhost', { method: 'POST', headers }));
const sessionFor = (userId: string) => ({
user: { id: userId, email: `${userId}@example.com` },
expires: '2099-01-01',
});
describe('耗时请求响应暂存', () => {
beforeEach(() => {
resetRecoverableResponsesForTest();
mocks.session = { user: { email: 'user@example.com' }, expires: '2099-01-01' };
mocks.user.findUnique.mockResolvedValue({ id: 'user-1' });
mocks.session = sessionFor('user-1');
mocks.user.findUnique.mockImplementation(async (args: { where?: { id?: string; email?: string } }) => {
const idValue = args.where?.id ?? args.where?.email?.split('@')[0];
return idValue ? { id: idValue, email: `${idValue}@example.com` } : null;
});
});
it('处理中返回 running,结束后返回原响应的状态码与内容,原响应不受影响', async () => {
@@ -60,4 +67,44 @@ describe('耗时请求响应暂存', () => {
mocks.session = null;
expect((await lookup()).status).toBe(401);
});
it('未认证请求带请求编号时不占用恢复缓存', async () => {
mocks.session = null;
await call(async () => NextResponse.json({ ok: true }));
mocks.session = sessionFor('user-1');
expect((await lookup()).status).toBe(404);
});
it('401/403 响应不保留,不占用 15 分钟缓存名额', async () => {
await call(async () => NextResponse.json({ message: 'Authentication required' }, { status: 401 }));
expect((await lookup()).status).toBe(404);
await call(async () => NextResponse.json({ message: 'Admin access required' }, { status: 403 }));
expect((await lookup()).status).toBe(404);
});
it('其他账号使用同一请求编号查询返回 404', async () => {
await call(async () => NextResponse.json({ secret: 'A 的答案' }));
mocks.session = sessionFor('user-2');
expect((await lookup()).status).toBe(404);
mocks.session = sessionFor('user-1');
expect(await (await lookup()).json()).toEqual({ state: 'done', status: 200, body: { secret: 'A 的答案' } });
});
it('已存在的请求编号不被新请求覆盖', async () => {
await call(async () => NextResponse.json({ owner: 'A' }));
mocks.session = sessionFor('user-2');
await call(async () => NextResponse.json({ owner: 'B' }));
mocks.session = sessionFor('user-1');
expect(await (await lookup()).json()).toEqual({ state: 'done', status: 200, body: { owner: 'A' } });
// 新请求没有覆盖原登记,B 用同一编号查不到自己的响应
mocks.session = sessionFor('user-2');
expect((await lookup()).status).toBe(404);
});
});

View File

@@ -291,15 +291,18 @@ describe('withUser 与 withRecoverableResponse 组合', () => {
// 组合顺序:withRecoverableResponse(withUser(handler))
const wrapped = withRecoverableResponse(handler);
const requestId = 'a'.repeat(32);
// 未登录时不暂存
// 未登录时即使带请求编号也不暂存
mocks.getServerSession.mockResolvedValue(null);
const unauthResponse = await wrapped(new Request('http://localhost/api/test'));
const unauthResponse = await wrapped(new Request('http://localhost/api/test', {
headers: { 'x-request-id': requestId },
}));
expect(unauthResponse.status).toBe(401);
expect(getStoredResponse(requestId)).toBeNull();
// 已登录时暂存响应
mocks.getServerSession.mockResolvedValue(loggedInSession);
const requestId = 'a'.repeat(32);
const okResponse = await wrapped(new Request('http://localhost/api/test', {
headers: { 'x-request-id': requestId },
}));

View File

@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { notFound } from "@/lib/api-errors";
import { getStoredResponse, parseRequestId } from "@/lib/recoverable-response";
import { getStoredResponseForUser, parseRequestId } from "@/lib/recoverable-response";
import { withUser } from "@/lib/api-handler";
import type { AuthenticatedContext } from "@/lib/api-handler";
@@ -11,9 +11,10 @@ type RouteContext = { params: Promise<{ id: string }> };
* 取回被浏览器中断的耗时请求的结果:{ state: 'running' } 或 { state: 'done', status, body };
* 请求没有到达服务端或结果已过期时返回 404
*/
export const GET = withUser(async (_req: Request, { params }: AuthenticatedContext & RouteContext) => {
export const GET = withUser(async (_req: Request, { params, session }: AuthenticatedContext & RouteContext) => {
const id = parseRequestId((await params).id);
const stored = id ? getStoredResponse(id) : null;
const owner = session.user.id ?? session.user.email ?? null;
const stored = id && owner ? getStoredResponseForUser(id, owner) : null;
if (!stored) {
return notFound("Request not found");
}

View File

@@ -9,6 +9,8 @@ import "server-only";
*
* 只保存在当前进程内存中(生产环境为单个容器),服务重启后清空;请求编号由前端随机生成,只有发起请求的页面知道。
*/
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { createLogger } from "@/lib/logger";
const logger = createLogger('recoverable-response');
@@ -30,6 +32,8 @@ export type StoredResponse =
| { state: 'done'; status: number; body: unknown };
interface Entry {
/** 发起请求的登录账号(管理员 view-as 时为管理员本人) */
userId: string;
startedAt: number;
finishedAt: number | null;
status: number;
@@ -59,6 +63,16 @@ export function parseRequestId(value: string | null | undefined): string | null
return id && REQUEST_ID_PATTERN.test(id) ? id : null;
}
/** 请求归属账号;未登录时返回 null,不占用恢复缓存配额 */
async function resolveRequestOwner(): Promise<string | null> {
try {
const session = await getServerSession(authOptions);
return session?.user?.id ?? session?.user?.email ?? null;
} catch {
return null;
}
}
async function readBody(response: Response): Promise<unknown> {
const text = await response.text();
if (text.length > MAX_BODY_LENGTH) throw new Error('RESPONSE_TOO_LARGE');
@@ -75,12 +89,24 @@ export function withRecoverableResponse<R extends Request, A extends unknown[]>(
const id = parseRequestId(req.headers.get(REQUEST_ID_HEADER));
if (!id) return handler(req, ...args);
// 未认证请求不登记,避免匿名请求刷满 200 条上限并驱逐在线用户的缓存
const owner = await resolveRequestOwner();
if (!owner) return handler(req, ...args);
const now = Date.now();
prune(now);
const entry: Entry = { startedAt: now, finishedAt: null, status: 0, body: null };
// 已存在的编号不被新请求覆盖,避免不同请求的响应互相串换
if (entries.has(id)) return handler(req, ...args);
const entry: Entry = { userId: owner, startedAt: now, finishedAt: null, status: 0, body: null };
entries.set(id, entry);
try {
const response = await handler(req, ...args);
// 鉴权失败不保留,前端按原状态处理,也不占用 15 分钟的缓存名额
if (response.status === 401 || response.status === 403) {
entries.delete(id);
return response;
}
try {
entry.body = await readBody(response.clone());
entry.status = response.status;
@@ -105,6 +131,14 @@ export function getStoredResponse(id: string): StoredResponse | null {
return entry.finishedAt === null ? { state: 'running' } : { state: 'done', status: entry.status, body: entry.body };
}
/** 按请求编号与归属账号查询;其他账号使用同一编号时返回 null(404),防止读取他人的响应 */
export function getStoredResponseForUser(id: string, userId: string): StoredResponse | null {
prune(Date.now());
const entry = entries.get(id);
if (!entry || entry.userId !== userId) return null;
return entry.finishedAt === null ? { state: 'running' } : { state: 'done', status: entry.status, body: entry.body };
}
/** 仅供测试:清空暂存 */
export function resetRecoverableResponsesForTest(): void {
entries.clear();