192 lines
10 KiB
TypeScript
192 lines
10 KiB
TypeScript
import { beforeAll, describe, expect, test } from "vitest";
|
|
import { dirname, join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { scanApiRoutesFromFile, type ApiRoute } from "../../../tools/api-inventory/scan-api-routes.js";
|
|
import { openApiDocument } from "./openapi.js";
|
|
import { routeAccessClasses, routeAccessInventory, routeAccessKey, type RouteAccessInventoryEntry } from "./route-access-inventory.js";
|
|
|
|
type OpenApiOperation = {
|
|
security?: unknown;
|
|
"x-api-key-permissions"?: unknown;
|
|
};
|
|
|
|
const appSourcePath = join(dirname(fileURLToPath(import.meta.url)), "app.ts");
|
|
const allowedAccessClasses = new Set<string>(routeAccessClasses);
|
|
const documentedOpenApiPaths = new Set(["/healthz", "/readyz", "/status", "/metrics", ...Object.keys(openApiDocument.paths).filter((path) => path.startsWith("/v1/"))]);
|
|
const sensitiveTextPattern = /\b(secret|password|token|api[-_ ]?key|bearer|credential|jwt|email|user id|userid)\s*[:=]\s*[^\s,;]+/i;
|
|
|
|
function toOpenApiPath(path: string) {
|
|
return path.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
|
|
}
|
|
|
|
function getOpenApiOperation(route: Pick<RouteAccessInventoryEntry, "method" | "path">): OpenApiOperation | undefined {
|
|
const pathItem = openApiDocument.paths[toOpenApiPath(route.path) as keyof typeof openApiDocument.paths];
|
|
if (!pathItem) {
|
|
return undefined;
|
|
}
|
|
return (pathItem as Record<string, OpenApiOperation | undefined>)[route.method.toLowerCase()];
|
|
}
|
|
|
|
function expectedSecurityFor(entry: RouteAccessInventoryEntry) {
|
|
if (
|
|
[
|
|
"/v1/session/current-user",
|
|
"/v1/notifications/stream",
|
|
"/v1/workspaces/:tenantId/auth/providers",
|
|
"/v1/workspaces/:tenantId/context/revalidate",
|
|
"/v1/workspaces/:tenantId/invites",
|
|
"/v1/workspaces/:tenantId/invites/:inviteId/accept",
|
|
"/v1/workspaces/:tenantId/invites/:inviteId/revoke",
|
|
].includes(entry.path)
|
|
) {
|
|
return [{ bearerAuth: [] }];
|
|
}
|
|
switch (entry.accessClass) {
|
|
case "public-health":
|
|
return [];
|
|
case "public-docs":
|
|
case "auth-credential-exchange":
|
|
return undefined;
|
|
case "public-analytics-token":
|
|
return [{ analyticsTokenHeader: [] }];
|
|
case "canonical-redirect":
|
|
return undefined;
|
|
case "webhook-signature":
|
|
return [{ mailjetWebhookAuth: [] }];
|
|
case "provider-refetch-webhook":
|
|
return [];
|
|
case "jwt-auth":
|
|
return [{ apiSessionBearer: [] }];
|
|
case "service-token":
|
|
return [{ bearerAuth: [] }];
|
|
case "service-or-tenant-api-key":
|
|
return [{ bearerAuth: [] }, { apiKeyHeader: [] }];
|
|
case "optional-api-key-validation":
|
|
return [{ bearerAuth: [] }, { apiKeyHeader: [] }, {}];
|
|
case "tenant-api-key":
|
|
return [{ apiKeyHeader: [] }];
|
|
case "tenant-webhook-credential":
|
|
return [{ apiKeyHeader: [] }, { webhookTokenHeader: [] }, { webhookHmac: [] }];
|
|
}
|
|
}
|
|
|
|
function routeDiagnostics(routes: Array<Pick<RouteAccessInventoryEntry, "method" | "path">>) {
|
|
return routes.map(routeAccessKey).sort();
|
|
}
|
|
|
|
function discoveredRouteDiagnostics(routes: readonly ApiRoute[]) {
|
|
return routes.map((route) => route.key).sort();
|
|
}
|
|
|
|
describe("route access inventory", () => {
|
|
let scanResult: Awaited<ReturnType<typeof scanApiRoutesFromFile>>;
|
|
let discoveredRoutes: ApiRoute[];
|
|
|
|
beforeAll(async () => {
|
|
scanResult = await scanApiRoutesFromFile(appSourcePath);
|
|
discoveredRoutes = scanResult.routes;
|
|
});
|
|
|
|
test("classifies every scanner-discovered Hono route exactly once and has no stale route entries", () => {
|
|
const discoveredKeys = new Set(discoveredRoutes.map((route) => route.key));
|
|
const inventoryKeys = new Set(routeAccessInventory.map(routeAccessKey));
|
|
|
|
const duplicateEntries = routeAccessInventory
|
|
.map(routeAccessKey)
|
|
.filter((key, index, keys) => keys.indexOf(key) !== index)
|
|
.sort();
|
|
const duplicateDiscoveredRoutes = scanResult.duplicateRoutes.map((duplicate) => duplicate.key).sort();
|
|
const unresolvedMountedRouters = scanResult.unresolvedMountedRouters.map(
|
|
(router) => `${router.prefix} -> ${router.receiver} (${router.location.line}:${router.location.column})`
|
|
);
|
|
const missingFromInventory = discoveredRouteDiagnostics(discoveredRoutes.filter((route) => !inventoryKeys.has(route.key)));
|
|
const staleInventoryEntries = routeDiagnostics(routeAccessInventory.filter((entry) => !discoveredKeys.has(routeAccessKey(entry))));
|
|
|
|
expect(unresolvedMountedRouters, `Unresolved mounted API routers:\n${unresolvedMountedRouters.join("\n")}`).toEqual([]);
|
|
expect(duplicateDiscoveredRoutes, `Duplicate scanner-discovered API routes:\n${duplicateDiscoveredRoutes.join("\n")}`).toEqual([]);
|
|
expect(duplicateEntries, `Duplicate route access inventory entries:\n${duplicateEntries.join("\n")}`).toEqual([]);
|
|
expect(missingFromInventory, `Missing route access inventory entries:\n${missingFromInventory.join("\n")}`).toEqual([]);
|
|
expect(staleInventoryEntries, `Stale route access inventory entries:\n${staleInventoryEntries.join("\n")}`).toEqual([]);
|
|
});
|
|
|
|
test("uses supported classes, non-empty rationales, and redacted sensitive-data descriptions", () => {
|
|
const malformedEntries = routeAccessInventory
|
|
.filter((entry) => !allowedAccessClasses.has(entry.accessClass) || entry.rationale.trim().length === 0 || (typeof entry.sensitiveData === "string" && entry.sensitiveData.trim().length === 0) || sensitiveTextPattern.test(entry.rationale) || (typeof entry.sensitiveData === "string" && sensitiveTextPattern.test(entry.sensitiveData)))
|
|
.map((entry) => `${routeAccessKey(entry)} class=${entry.accessClass} rationale=${JSON.stringify(entry.rationale)} sensitiveData=${JSON.stringify(entry.sensitiveData)}`);
|
|
|
|
expect(malformedEntries, `Invalid route access inventory fields:\n${malformedEntries.join("\n")}`).toEqual([]);
|
|
});
|
|
|
|
test("inventories workspace auth boundary endpoints with redacted service-token contracts", () => {
|
|
const authBoundaryEntries = routeAccessInventory.filter((entry) =>
|
|
["/v1/workspaces/:tenantId/auth/providers", "/v1/workspaces/:tenantId/context/revalidate"].includes(entry.path)
|
|
);
|
|
|
|
expect(authBoundaryEntries.map(routeAccessKey).sort()).toEqual([
|
|
"GET /v1/workspaces/:tenantId/auth/providers",
|
|
"POST /v1/workspaces/:tenantId/context/revalidate",
|
|
]);
|
|
for (const entry of authBoundaryEntries) {
|
|
expect(entry.accessClass).toBe("service-token");
|
|
expect(entry.rationale).toContain("service token");
|
|
expect(entry.sensitiveData).toEqual(expect.stringMatching(/redacted|omitted/i));
|
|
expect(`${entry.rationale} ${entry.sensitiveData}`).toMatch(/provider secrets|client secrets|SSO secret|SAML certificate/i);
|
|
expect(getOpenApiOperation(entry)?.security).toEqual([{ bearerAuth: [] }]);
|
|
}
|
|
});
|
|
|
|
test("documents matching OpenAPI security metadata for represented OpenAPI routes", () => {
|
|
const missingOpenApiOperations = routeAccessInventory
|
|
.filter((entry) => documentedOpenApiPaths.has(toOpenApiPath(entry.path)) && !getOpenApiOperation(entry))
|
|
.map(routeAccessKey);
|
|
|
|
const securityDrift = routeAccessInventory
|
|
.filter((entry) => documentedOpenApiPaths.has(toOpenApiPath(entry.path)))
|
|
.flatMap((entry) => {
|
|
const operation = getOpenApiOperation(entry);
|
|
const expectedSecurity = expectedSecurityFor(entry);
|
|
return JSON.stringify(operation?.security) === JSON.stringify(expectedSecurity)
|
|
? []
|
|
: [`${routeAccessKey(entry)} expected security ${JSON.stringify(expectedSecurity)} but found ${JSON.stringify(operation?.security)}`];
|
|
});
|
|
|
|
expect(missingOpenApiOperations, `Missing OpenAPI operations for inventory routes:\n${missingOpenApiOperations.join("\n")}`).toEqual([]);
|
|
expect(securityDrift, `OpenAPI security drift:\n${securityDrift.join("\n")}`).toEqual([]);
|
|
});
|
|
|
|
test("keeps OpenAPI path coverage aligned with route inventory", () => {
|
|
const inventoryOpenApiKeys = new Set(routeAccessInventory.map((entry) => `${entry.method} ${toOpenApiPath(entry.path)}`));
|
|
const documentedRouteKeys = Object.entries(openApiDocument.paths)
|
|
.flatMap(([path, pathItem]) =>
|
|
Object.keys(pathItem)
|
|
.filter((method) => ["get", "post", "put", "patch", "delete", "options"].includes(method))
|
|
.map((method) => `${method.toUpperCase()} ${path}`)
|
|
)
|
|
.filter((key) => key !== "GET /v1/openapi.json")
|
|
.sort();
|
|
|
|
const undocumentedInventoryKeys = routeAccessInventory
|
|
.filter((entry) => !documentedOpenApiPaths.has(toOpenApiPath(entry.path)))
|
|
.map((entry) => `${routeAccessKey(entry)} is intentionally runtime-only`)
|
|
.sort();
|
|
const staleDocumentedKeys = documentedRouteKeys.filter((key) => !inventoryOpenApiKeys.has(key));
|
|
|
|
expect(undocumentedInventoryKeys, `Runtime routes without OpenAPI docs:\n${undocumentedInventoryKeys.join("\n")}`).toEqual([]);
|
|
expect(staleDocumentedKeys, `OpenAPI operations missing from route access inventory:\n${staleDocumentedKeys.join("\n")}`).toEqual([]);
|
|
});
|
|
|
|
test("negative diagnostics remain empty for scanner missing/stale entries and invalid classifications", () => {
|
|
const discoveredKeys = new Set(discoveredRoutes.map((route) => route.key));
|
|
const inventoryKeys = new Set(routeAccessInventory.map(routeAccessKey));
|
|
const missingEntries = discoveredRoutes.filter((route) => !inventoryKeys.has(route.key));
|
|
const staleEntries = routeAccessInventory.filter((entry) => !discoveredKeys.has(routeAccessKey(entry)));
|
|
const invalidClassEntries = routeAccessInventory.filter((entry) => !allowedAccessClasses.has(entry.accessClass));
|
|
const emptyRationaleEntries = routeAccessInventory.filter((entry) => entry.rationale.trim().length === 0);
|
|
|
|
expect(discoveredRouteDiagnostics(missingEntries), `Missing entries:\n${discoveredRouteDiagnostics(missingEntries).join("\n")}`).toEqual([]);
|
|
expect(routeDiagnostics(staleEntries), `Stale entries:\n${routeDiagnostics(staleEntries).join("\n")}`).toEqual([]);
|
|
expect(routeDiagnostics(invalidClassEntries), `Unsupported classes:\n${routeDiagnostics(invalidClassEntries).join("\n")}`).toEqual([]);
|
|
expect(routeDiagnostics(emptyRationaleEntries), `Empty rationales:\n${routeDiagnostics(emptyRationaleEntries).join("\n")}`).toEqual([]);
|
|
});
|
|
});
|