import assert from "node:assert/strict"; import { readFileSync, readdirSync, statSync } from "node:fs"; import { fileURLToPath, pathToFileURL } from "node:url"; import path from "node:path"; import { test } from "node:test"; import "reflect-metadata"; import { RequestMethod } from "@nestjs/common"; import { ADMIN_AUTH_METADATA, type AdminAuthMetadata } from "../src/admin-auth.decorators.js"; import { ROUTE_COVERAGE, type HttpMethod, type RouteAuth } from "./route-coverage.matrix.js"; type DiscoveredRoute = { method: HttpMethod; path: string; auth: RouteAuth; roles?: string[]; controller: string; handler: string; }; type RequestEvidence = { kind: "request" | "authorization-boundary"; method: HttpMethod | null; path: string | null; start: number; end: number; }; const TEST_DIRECTORY = path.dirname(fileURLToPath(import.meta.url)); const API_ROOT = path.resolve(TEST_DIRECTORY, ".."); const CONTROLLER_ROOT = path.join(API_ROOT, "src/modules"); const INTEGRATION_TEST_PATH = path.join(TEST_DIRECTORY, "http.integration.test.js"); const REQUIRED_PROTECTED_REJECTIONS = [401, 403] as const; function routeKey(route: Pick): string { return `${route.method} ${route.path}`; } function walk(directory: string): string[] { return readdirSync(directory).flatMap((entry) => { const fullPath = path.join(directory, entry); return statSync(fullPath).isDirectory() ? walk(fullPath) : [fullPath]; }); } function classifyUnauthenticatedRoute(method: HttpMethod, routePath: string): RouteAuth { if ( routePath === "/health" || routePath.startsWith("/public/") || (method === "POST" && routePath === "/admin/session/login") || (method === "POST" && routePath === "/customer/session/wechat") ) { return "public"; } if (routePath.startsWith("/customer/")) return "customer"; throw new Error(`Route ${method} ${routePath} has no recognizable authorization contract`); } function readAuthMetadata( controller: object, handler: (...args: unknown[]) => unknown, ): AdminAuthMetadata | undefined { return ( (Reflect.getMetadata(ADMIN_AUTH_METADATA, handler) as AdminAuthMetadata | undefined) ?? (Reflect.getMetadata(ADMIN_AUTH_METADATA, controller) as AdminAuthMetadata | undefined) ); } async function discoverRoutes(): Promise { // 以内容标识发现 Controller,避免新增文件未遵循 *controller.ts 命名时被静默漏测。 const controllerFiles = walk(CONTROLLER_ROOT).filter( (file) => file.endsWith(".ts") && !file.endsWith(".d.ts") && /@Controller\s*\(/.test(readFileSync(file, "utf8")), ); const discovered: DiscoveredRoute[] = []; for (const file of controllerFiles) { const module = await import(pathToFileURL(file).href); for (const value of Object.values(module)) { if (typeof value !== "function" || !Reflect.hasMetadata("path", value)) continue; const controllerPath = Reflect.getMetadata("path", value) as string; for (const handlerName of Object.getOwnPropertyNames(value.prototype)) { if (handlerName === "constructor") continue; const handler = value.prototype[handlerName] as (...args: unknown[]) => unknown; const method = Reflect.getMetadata("method", handler) as RequestMethod | undefined; if (method === undefined) continue; const methodName = RequestMethod[method] as HttpMethod; const handlerPath = (Reflect.getMetadata("path", handler) as string | undefined) ?? ""; const routePath = `/${controllerPath}/${handlerPath}`.replace(/\/+/g, "/").replace(/\/$/, "") || "/"; const metadata = readAuthMetadata(value, handler); const auth = metadata?.type ?? classifyUnauthenticatedRoute(methodName, routePath); discovered.push({ method: methodName, path: routePath, auth, roles: metadata?.type === "roles" ? metadata.roles : undefined, controller: value.name, handler: handlerName, }); } } } return discovered.sort((left, right) => routeKey(left).localeCompare(routeKey(right))); } function readIntegrationTests(): Map { const source = readFileSync(INTEGRATION_TEST_PATH, "utf8"); const starts = [...source.matchAll(/^test\("([^"]+)"/gm)].map((match) => ({ name: match[1], index: match.index, })); return new Map( starts.map((entry, index) => [ entry.name, source.slice(entry.index, starts[index + 1]?.index ?? source.length), ]), ); } function findClosingParen(source: string, openIndex: number): number { let depth = 0; let quote: '"' | "'" | "`" | null = null; let escaped = false; for (let index = openIndex; index < source.length; index += 1) { const character = source[index]; if (quote) { if (escaped) { escaped = false; } else if (character === "\\") { escaped = true; } else if (character === quote) { quote = null; } continue; } if (character === '"' || character === "'" || character === "`") { quote = character; } else if (character === "(") { depth += 1; } else if (character === ")") { depth -= 1; if (depth === 0) return index; } } return -1; } function readFirstStringArgument(callText: string): string | null { const prefix = callText.match(/^\s*(?:request|json|assertProtectedRouteBoundary)\s*\(\s*/)?.[0]; if (!prefix) return null; const quote = callText[prefix.length]; if (quote !== '"' && quote !== "'" && quote !== "`") return null; let escaped = false; for (let index = prefix.length + 1; index < callText.length; index += 1) { const character = callText[index]; if (escaped) { escaped = false; } else if (character === "\\") { escaped = true; } else if (character === quote) { return callText.slice(prefix.length + 1, index); } } return null; } function normalizeEvidencePath(value: string): string { const pathname = value.split(/[?#]/, 1)[0].replace(/\$\{[^}]+\}/g, ":param"); const normalized = pathname.replace(/\/+$/, ""); return normalized || "/"; } function findRequestEvidence(source: string): RequestEvidence[] { const evidence: RequestEvidence[] = []; for (const match of source.matchAll(/\b(?:request|json|assertProtectedRouteBoundary)\s*\(/g)) { const openIndex = match.index + match[0].lastIndexOf("("); const closeIndex = findClosingParen(source, openIndex); if (closeIndex < 0) continue; const callText = source.slice(match.index, closeIndex + 1); const literalPath = readFirstStringArgument(callText); const explicitMethod = callText.match( /\bmethod\s*:\s*["'](DELETE|GET|PATCH|POST|PUT)["']/, )?.[1] as HttpMethod | undefined; const hasDynamicMethod = /\bmethod\s*:\s*[A-Za-z_$]/.test(callText); const method = explicitMethod ?? (hasDynamicMethod ? null : "GET"); evidence.push({ kind: match[0].includes("assertProtectedRouteBoundary") ? "authorization-boundary" : "request", method, path: literalPath === null ? null : normalizeEvidencePath(literalPath), start: match.index, end: closeIndex + 1, }); } return evidence; } function routePathMatches(routePath: string, evidencePath: string): boolean { const expectedSegments = routePath.split("/"); const actualSegments = evidencePath.split("/"); if (expectedSegments.length !== actualSegments.length) return false; return expectedSegments.every((segment, index) => { if (segment.startsWith(":")) return actualSegments[index].length > 0; return segment === actualSegments[index]; }); } function findRouteEvidence( source: string, route: Pick, ): RequestEvidence[] { return findRequestEvidence(source).filter( (evidence) => evidence.method === route.method && evidence.path !== null && routePathMatches(route.path, evidence.path), ); } function rejectionStatusesForRoute( source: string, route: Pick, ): Set { const allEvidence = findRequestEvidence(source); const statuses = new Set(); for (const [index, evidence] of allEvidence.entries()) { if ( evidence.method !== route.method || evidence.path === null || !routePathMatches(route.path, evidence.path) ) { continue; } if (evidence.kind === "authorization-boundary") { statuses.add(401); statuses.add(403); continue; } const contextEnd = allEvidence[index + 1]?.start ?? source.length; const context = source.slice(evidence.start, contextEnd); for (const statusMatch of context.matchAll(/statusCode,\s*(401|403)\b/g)) { statuses.add(Number(statusMatch[1])); } } return statuses; } test("every API route has an explicit authorization and success coverage contract", async () => { const matrix = new Map(); for (const route of ROUTE_COVERAGE) { const key = routeKey(route); assert.equal(matrix.has(key), false, `Route coverage matrix contains duplicate ${key}`); matrix.set(key, route); } const discovered = await discoverRoutes(); const discoveredKeys = new Set(discovered.map(routeKey)); assert.equal( discoveredKeys.size, discovered.length, "NestJS controllers expose duplicate HTTP method and path pairs", ); const missingCoverage = discovered.filter((route) => !matrix.has(routeKey(route))); const staleCoverage = [...matrix.keys()].filter((key) => !discoveredKeys.has(key)); assert.deepEqual( missingCoverage.map(routeKey), [], "API routes missing from test/route-coverage.matrix.ts", ); assert.deepEqual(staleCoverage, [], "Route coverage matrix contains routes that no longer exist"); for (const route of discovered) { const coverage = matrix.get(routeKey(route)); assert.ok(coverage, `Missing coverage entry for ${routeKey(route)}`); assert.equal( coverage.auth, route.auth, `${routeKey(route)} authorization mismatch (${route.controller}.${route.handler})`, ); if (route.auth === "roles") { assert.deepEqual( coverage.roles, route.roles, `${routeKey(route)} role allow-list mismatch (${route.controller}.${route.handler})`, ); } else { assert.equal(coverage.roles, undefined, `${routeKey(route)} must not declare roles`); } } const integrationTests = readIntegrationTests(); const coverageFailures: string[] = []; for (const route of ROUTE_COVERAGE) { const successBlock = integrationTests.get(route.successTest); if (!successBlock) { coverageFailures.push(`${routeKey(route)} successTest does not exist: ${route.successTest}`); continue; } if (findRouteEvidence(successBlock, route).length === 0) { coverageFailures.push( `${routeKey(route)} successTest does not call the exact method and path: ${route.successTest}`, ); } if (!/statusCode,\s*(200|201)\b/.test(successBlock)) { coverageFailures.push( `${routeKey(route)} successTest has no successful response assertion: ${route.successTest}`, ); } if (route.auth === "public") { if (route.authorizationTest !== null) { coverageFailures.push( `${routeKey(route)} is public and must not claim an authorization test`, ); } continue; } if (!route.authorizationTest) { coverageFailures.push(`${routeKey(route)} is protected and requires authorizationTest`); continue; } const authorizationBlock = integrationTests.get(route.authorizationTest); if (!authorizationBlock) { coverageFailures.push( `${routeKey(route)} authorizationTest does not exist: ${route.authorizationTest}`, ); continue; } if (findRouteEvidence(authorizationBlock, route).length === 0) { coverageFailures.push( `${routeKey(route)} authorizationTest does not call the exact method and path: ${route.authorizationTest}`, ); } const rejectionStatuses = [...rejectionStatusesForRoute(authorizationBlock, route)].sort(); if ( rejectionStatuses.length !== REQUIRED_PROTECTED_REJECTIONS.length || rejectionStatuses.some((status, index) => status !== REQUIRED_PROTECTED_REJECTIONS[index]) ) { coverageFailures.push( `${routeKey(route)} authorizationTest must associate missing-credential 401 and wrong-role 403 with the exact route; found [${rejectionStatuses.join(", ")}]: ${route.authorizationTest}`, ); } } assert.deepEqual( coverageFailures, [], `Route coverage contract failures:\n${coverageFailures.join("\n")}`, ); });