鉴权中间件:HEAD 按 GET 判 —— 不归一等于「只要登录就能跑任何 GET 处理器」

Hono 在 #dispatch 里把 HEAD 改写成 GET 再分发,而 `c.req.method` 读的是请求行上的
原始方法,仍是 'HEAD';路由注册表只装 HTTP_METHODS 那五个,于是 lookup('HEAD', …)
**必然 miss** → 落进 `?? 'any'` 兜底 → 一个 `ends: []` 的人(Keycloak 里还没配角色的
新员工)照样能执行三个端的全部 GET 处理器。不绕过认证(无凭据仍 401),够不到
POST/PUT/DELETE,响应体被框架丢掉 —— 但它绕过**端授权**:响应头照抄过去
(desk 那两处 content-disposition 带着资料文件名),而 GET 处理器不是都没副作用
(`GET /api/reports/:period` 一路走到 report-service 的 store.save)。

改:查表之前先归一方法;**票据那一路的 GET 判断用同一个归一后的 method**,
否则 HEAD 拿不到票据那条路,两条路行为不一致。

测(auth-middleware.test.ts +3):HEAD 到 ops 路由持只有 workbench 的 token → 403
(与 GET 同款)· HEAD 到自己端内的路由 → 200 · HEAD 上的票据与 GET 同款。
反向验证:撤掉归一那一行,前两条当场红(200 / 401),装回即绿。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015kAzS35kMnZNt4YGgJXtfw
This commit is contained in:
xcs
2026-08-25 19:41:43 +08:00
co-authored by Claude Opus 5
parent 253c6c3afa
commit 5964a80b28
2 changed files with 26 additions and 2 deletions
@@ -66,6 +66,8 @@ const get = (path: string, headers: Record<string, string> = {}): Promise<Respon
Promise.resolve(app.request(path, { headers }));
const post = (path: string, headers: Record<string, string> = {}): Promise<Response> =>
Promise.resolve(app.request(path, { method: 'POST', headers }));
const head = (path: string, headers: Record<string, string> = {}): Promise<Response> =>
Promise.resolve(app.request(path, { method: 'HEAD', headers }));
type Body = { code: string; message: string; detail?: { need: string[]; ends: string[] } };
describe('鉴权中间件', () => {
@@ -122,6 +124,20 @@ describe('鉴权中间件', () => {
const { ticket } = tickets.issue('sub-1', now);
expect((await get(`/api/gov/tasks?ticket=${encodeURIComponent(ticket)}`, { authorization: 'Bearer admin' })).status).toBe(200);
});
it('HEAD 按 GET 判:端不够 → 403,与 GET 同款', async () => {
// Hono 在 #dispatch 里把 HEAD 改写成 GET 再分发,而 c.req.method 仍是 'HEAD' ——
// 不归一的话查表必然 miss、落进「any」兜底,于是「只要登录就能跑任何 GET 处理器」。
expect((await get('/api/gov/tasks', { authorization: 'Bearer user' })).status).toBe(403);
expect((await head('/api/gov/tasks', { authorization: 'Bearer user' })).status).toBe(403);
});
it('HEAD 该进的还得进:端够了 → 200', async () => {
expect((await head('/api/desk/tasks', { authorization: 'Bearer user' })).status).toBe(200);
});
it('HEAD 上的票据与 GET 同款(归一之后两条路一致)', async () => {
const { ticket } = tickets.issue('sub-1', now);
expect((await head(`/api/desk/tasks?ticket=${encodeURIComponent(ticket)}`)).status).toBe(200);
expect((await head('/api/gov/tasks', {})).status).toBe(401);
});
it('未知路由:没凭据先 401,有凭据再 404', async () => {
expect((await get('/api/nope')).status).toBe(401);
expect((await get('/api/nope', { authorization: 'Bearer user' })).status).toBe(404);