diff --git a/.apigate.config.example.json b/.apigate.config.example.json index 8ffb29e..965c6e1 100644 --- a/.apigate.config.example.json +++ b/.apigate.config.example.json @@ -29,6 +29,8 @@ "publicAuthPatterns": null, "_publicAuthPatterns": "Override the built-in public-auth heuristic. null (default) uses DEFAULT_PUBLIC_AUTH_PATTERNS from lib/heuristics.mjs — common login/signup/refresh/health paths. Provide an array of { method, path } pairs to replace entirely, or an empty array [] to disable the heuristic. The exact-match list is deterministic: paths are normalized (`/users/:id` ↔ `/users/{id}` ↔ `/users/`) before comparison.", + "publicDecorators": ["Public", "SkipAuth", "AllowAnonymous"], + "_publicDecorators": "NestJS only. Decorator names (no @) that cancel a detected global guard (APP_GUARD provider or useGlobalGuards) for the controller or method carrying them, so the endpoint stays OPEN unless it has its own marker such as @UseGuards. A global guard counts as auth only when its class name is in auth.nest. [] disables this.", "requireSpec": false, "_requireSpec": "When true, exit 1 if no OpenAPI 2/3 spec is detected. Useful when spec drift is part of the contract and a green no-spec run would be misleading.", diff --git a/CHANGELOG.md b/CHANGELOG.md index 916acf6..f88177e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,11 +6,32 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) + [Semantic Ver ## [Unreleased] +### Added +- NestJS global guards: `{ provide: APP_GUARD, useClass|useExisting: X }` + providers and `useGlobalGuards(new X())` calls add the guard class name as + an auth marker to every Nest endpoint in the scan. An endpoint is GUARDED + only when the name is in `auth.nest`; a global guard with another name is + still reported OPEN. +- `publicDecorators` config key (default `Public`, `SkipAuth`, + `AllowAnonymous`): a Nest controller or method with one of these + decorators does not receive the global guard markers. +- NestJS `setGlobalPrefix('literal')` is applied to every Nest endpoint path, + and a literal `exclude` array is honored. A non-literal prefix leaves the + endpoints unresolved with the new reason `global-prefix-not-static-string`. + ### Changed - Dropped Node 18 (end of life). `engines.node` is now `>=20`, and the CI matrix runs Node 20, 22, 24 and 26. - Bumped `acorn` to 8.19 and `yaml` to 2.9.1. Dev tooling moved to ESLint 10, `@eslint/js` 10 and `globals` 17; `npm audit` is clean again. +- `parserCapabilities.nest.globalGuardDetection` is now `true`, with new keys + `globalGuardRules`, `globalPrefix` and `publicDecorators`. The report + limitation about global guards describes what is and is not detected. + +### Fixed +- Nest: decorators on the same line before `@Get(...)` are now read, and a + method declared on the anchor line (`@Get() list() {}`) no longer takes the + decorators of the next method. ## [0.3.4] - 2026-11-14 diff --git a/README.md b/README.md index 77178fd..80a115e 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ The bounded scan builds one sorted candidate-file index and shares it across all |------------|--------------------------------------------------------------------------------------------------------------------------| | **Express** | acorn AST for `.js/.mjs/.cjs`; regex fallback for `.ts/.tsx`. Resolves `app.use('/prefix', router)` mounts in same file. AST files also track any variable assigned from `express()` / `express.Router()` / `Router()` whatever its name, and parse `app.route('/x').get(...).post(...)` chains. Path-less `router.use(requireAuth)` guards routes registered on that router after it only when `router` is a `const/let/var` declared once from a router factory, never reassigned, and the `use()` is a plain statement in the same block as the declaration. These `use()` calls are ignored (routes stay OPEN): `this.router.use(...)`, a router received as a parameter, a `use()` inside `if` or a helper function, `X.use(someCall(), auth)`, and wrappers like `jwt(...).unless(...)`. Not resolved: routers imported from another file, path-less `app.use(auth)` flowing into routers mounted on `app`, `route('/x').all(auth)` guarding the other verbs of the chain, and all of the above in `.ts/.tsx` files. Routers created in factory functions or received as parameters are parsed (routes and mounts), with the `use()` limits above. | | **Fastify** | acorn AST for `.js/.mjs/.cjs`; regex extractor for `.ts/.mts/.cts` (no TypeScript dependency, `fastify.delete<{ Params: ... }>(...)` generics are skipped). Handles `fastify.(...)` and `fastify.route({ method, url, preHandler })`. | -| **NestJS** | Decorator extraction over `.ts/.js`. Pairs `@Controller(...)` with method decorators `@Get / @Post / @Put / @Patch / @Delete / @Options / @Head / @All`. Captures class- and method-level guards (`@UseGuards`, `@Auth`, `@Roles`, `@ApiBearerAuth`). | +| **NestJS** | Decorator extraction over `.ts/.js`. Pairs `@Controller(...)` with method decorators `@Get / @Post / @Put / @Patch / @Delete / @Options / @Head / @All`. Captures class- and method-level guards (`@UseGuards`, `@Auth`, `@Roles`, `@ApiBearerAuth`), global guards (`APP_GUARD` providers, `useGlobalGuards`) and a literal `setGlobalPrefix()`; see [NestJS global guards and prefix](#nestjs-global-guards-and-prefix). | | **OpenAPI** | Parses `*.yaml`/`*.yml`/`*.json` with `swagger:` (2.0) or `openapi:` (3.x) root. Honors operation-level `security` and root inheritance. | Routes that can't be statically resolved (dynamic mount prefixes, computed method names, unparseable files) are emitted as `UNRESOLVED` — never guessed. They count against the **Inventory Resolved** rubric so the report tells you what ApiGate could and couldn't see. @@ -287,6 +287,7 @@ Create `.apigate.config.json` in your scan target directory. All fields optional "drift": false, "intentionalPublic": false }, + "publicDecorators": ["Public", "SkipAuth", "AllowAnonymous"], "requireSpec": false, "strictPublic": false, "excludePaths": ["node_modules/**", "**/node_modules/**", "dist/**", "**/dist/**", "**/*.test.*"], @@ -308,6 +309,7 @@ A fully-commented example config lives at [`.apigate.config.example.json`](.apig | `frameworks` | object | all `true` | Toggle individual parsers | | `auth` | object | per-framework defaults | Identifier names that classify an endpoint as `GUARDED` when present | | `failOn` | object | `{ openWriteMethods: true, unknown: false, drift: false }` | Exit-code policy | +| `publicDecorators` | array | `["Public", "SkipAuth", "AllowAnonymous"]` | NestJS decorator names (no `@`) that cancel the global guard for the controller or method carrying them. `[]` disables it | | `requireSpec` | boolean | `false` | Fail when no OpenAPI 2/3 spec is detected | | `strictPublic`| boolean | `false` | Disable built-in public-auth patterns unless `publicAuthPatterns` is set | | `excludePaths`| array | vendor/build/test dirs | Globs of files to skip during the walk | @@ -331,6 +333,22 @@ ApiGate's classifier reports `GUARDED` when one of the declared auth identifiers ApiGate does **not** inspect what these identifiers do at runtime. Their declared presence is the signal — that's the static-analysis honesty contract. +### NestJS global guards and prefix + +ApiGate reads these forms in any scanned file (comments are ignored): + +- `{ provide: APP_GUARD, useClass: X }` or `{ provide: APP_GUARD, useExisting: X }`, in any key order, with no nested braces inside the literal. +- `app.useGlobalGuards(new A(), new B())`. +- `app.setGlobalPrefix('literal')`, optionally with `{ exclude: [...] }`. + +The rule: the guard class names (`X`, `A`, `B`) are added as markers to **every** Nest endpoint found in the scan, and an endpoint becomes `GUARDED` only if one of those names is in `auth.nest`. `JwtAuthGuard` and `AuthGuard` are in the defaults. A global guard with any other name (say `OrgGuard`) changes nothing: its endpoints stay `OPEN` until you add the name, for example `{ "auth": { "nest": ["UseGuards", "OrgGuard"] } }`. ApiGate does not judge what a guard does. + +A controller or method decorated with a `publicDecorators` name (default `Public`, `SkipAuth`, `AllowAnonymous`) does not receive the global guard markers, so it stays `OPEN`. Decorators are matched by name only. An explicit marker on the same endpoint, such as `@UseGuards(JwtAuthGuard)` next to `@Public()`, is kept and the endpoint is `GUARDED`. + +The prefix applies to every Nest endpoint in the scan. A non-literal argument (`setGlobalPrefix(process.env.PREFIX)`) or two calls with different prefixes leave all Nest endpoints unresolved (`global-prefix-not-static-string`). In `exclude`, string entries and `{ path, method }` entries are matched against the un-prefixed controller plus method path by exact text; the `method` is not checked. A non-literal `exclude`, or a pattern with route parameters, is ignored and the prefix still applies. + +Limits: the scope is the whole scan, not a module or app, so a monorepo with several Nest apps in one scan shares guards and prefix. Not detected: `useFactory` and `useValue` providers, guards passed to `useGlobalGuards` as a variable, `RouterModule` path trees, versioning. + --- ## Dogfood @@ -347,7 +365,7 @@ ApiGate is scanned against four targets each release. The first is the **determi **What the numbers say.** - `nest-realworld` 100/100 doesn't mean ApiGate "passed Nest" — it means we lock byte-equality against that fixture. -- `immich` 64/100 and `ghost` 66/100 are honest scans of real codebases against ApiGate's default policy + lightweight per-repo config. Both have real OPEN findings worth triage; both also exhibit the known parser limits documented in `parserCapabilities` (global-guard pattern, project-specific middleware names). +- `immich` 64/100 and `ghost` 66/100 are honest scans of real codebases against ApiGate's default policy + lightweight per-repo config. Both have real OPEN findings worth triage; both also exhibit the known parser limits documented in `parserCapabilities` (for example project-specific middleware names). - `slstudio` 70/100 internal — surfaced ~39 false-GUARDED endpoints whose only declared marker was `@ApiBearerAuth` (Swagger doc decorator) on first run. Reviewable in 30 seconds via `matchedAuthMarker`. **Reproducing the public scans:** @@ -515,6 +533,7 @@ Each run writes: | 0.3.0 | `parserCapabilities.nest.methodDecoratorsBelowAnchor` | Now `true` — bidirectional decorator scan captures markers above AND below `@Get`/`@Post`. | | 0.3.0 | `parserCapabilities.nest.globalGuardDetection` | Documented as `NOT DETECTED` — NestJS `APP_GUARD` / `useGlobalGuards` providers are invisible. Use `auth.nest` overrides or `severityOverrides`. | | 0.3.0 | LIMITATIONS entry #7 | Global-guard blind spot disclosed in every printed report. | +| Unreleased | `parserCapabilities.nest.globalGuardDetection` | Now `true`. New keys `globalGuardRules`, `globalPrefix`, `publicDecorators`; new unresolved reason `global-prefix-not-static-string`. The LIMITATIONS global-guard entry is rewritten. | | Unreleased | `parserCapabilities.express.routerVariableTracking` / `routeChains` / `routerLevelMiddleware` | Any-name routers, `route()` chains and path-less `X.use(mw)` markers (AST files only). | ### Posture tiers @@ -538,7 +557,7 @@ matchedAuthMarker distribution (GUARDED endpoints): 2 Roles ``` -`@ApiBearerAuth()` is a Swagger documentation decorator, **not** a runtime guard. 313 of the 327 GUARDED endpoints matched on it. Most are still protected by a global `APP_GUARD` registered in `app.module.ts` (invisible to static analysis — see `parserCapabilities.nest`), but 39 had no other guard identifier in their decorator chain at all. Without `matchedAuthMarker` those would have been silent in the report. With it, the reviewer has a 30-second triage path. +`@ApiBearerAuth()` is a Swagger documentation decorator, **not** a runtime guard. 313 of the 327 GUARDED endpoints matched on it. Most are still protected by a global `APP_GUARD` registered in `app.module.ts` (that scan predates global guard detection, see `parserCapabilities.nest`), but 39 had no other guard identifier in their decorator chain at all. Without `matchedAuthMarker` those would have been silent in the report. With it, the reviewer has a 30-second triage path. If your codebase wants to drop the false signal entirely, remove `ApiBearerAuth` from `auth.nest` in `.apigate.config.json`. ApiGate's defaults are intentionally permissive (the cost of missing a real guard outweighs the cost of a false GUARDED that `matchedAuthMarker` makes visible). diff --git a/lib/capabilities.mjs b/lib/capabilities.mjs index c28e305..feb8f5f 100644 --- a/lib/capabilities.mjs +++ b/lib/capabilities.mjs @@ -43,7 +43,10 @@ export const PARSER_CAPABILITIES = Object.freeze({ methodLevelGuards: true, methodDecoratorsBelowAnchor: true, multilineControllerArg: "PARTIAL — single-line and { path: '...' } object form resolve; complex multi-line @Controller args may block the upward scan above @Controller (deferred to v0.4)", - globalGuardDetection: "NOT DETECTED — useGlobalGuards(...) / { provide: APP_GUARD } providers in main.ts / app.module.ts are invisible to per-controller parsing. Endpoints protected ONLY by a global guard will be reported OPEN. Workaround: extend auth.nest with your custom marker, or use config.severityOverrides to pin specific endpoints.", + globalGuardDetection: true, + globalGuardRules: "Detected in any scanned file: a provider object literal { provide: APP_GUARD, useClass: X } or { provide: APP_GUARD, useExisting: X } (any key order, no nested braces), and X.useGlobalGuards(new A(), new B()). Comments are ignored. The guard class names become auth markers of EVERY Nest endpoint in the scan (no per-module or per-app resolution), and an endpoint is GUARDED only if a class name matches auth.nest (JwtAuthGuard and AuthGuard by default); add your own guard name to auth.nest otherwise. Not detected: useFactory/useValue providers, guards passed as a variable to useGlobalGuards, RouterModule, versioning. ApiGate does not judge what a guard does.", + globalPrefix: "X.setGlobalPrefix('literal') is applied to every Nest endpoint in the scan (quotes or a backtick string without interpolation). A non-literal argument, or two calls with different prefixes, makes all Nest endpoints unresolved (global-prefix-not-static-string). The literal exclude array is honored by exact match of the un-prefixed controller+method path, for strings and { path, method } entries (the method is not checked); a non-literal exclude, or a route pattern with parameters, is ignored and the prefix still applies.", + publicDecorators: "config.publicDecorators (default Public, SkipAuth, AllowAnonymous), matched by name on the controller class or the method: the endpoint does not receive the global guard markers. Explicit markers on the same endpoint (for example @UseGuards) are kept.", dynamicDecoratorArg: "UNRESOLVED" }), openapi: Object.freeze({ @@ -76,6 +79,7 @@ export const RISK_TIER_INFO = Object.freeze({ */ export const KNOWN_UNRESOLVED_REASONS = Object.freeze([ "controller-path-not-static-string", + "global-prefix-not-static-string", "method-or-url-missing", "method-path-not-static-string", "mount-prefix-not-static", diff --git a/lib/config.mjs b/lib/config.mjs index 134c984..d3bdf5e 100644 --- a/lib/config.mjs +++ b/lib/config.mjs @@ -65,7 +65,10 @@ export const CONFIG_DEFAULTS = Object.freeze({ "tests/**", "__tests__/**" ]), - severityOverrides: Object.freeze([]) + severityOverrides: Object.freeze([]), + // NestJS: decorator names (no "@") that cancel a global guard for the + // controller or method carrying them. See lib/parsers/nest.mjs. + publicDecorators: Object.freeze(["Public", "SkipAuth", "AllowAnonymous"]) }); function mergeAuth(rawAuth) { @@ -113,6 +116,13 @@ function mergeSeverityOverrides(raw) { return ok; } +function mergePublicDecorators(raw) { + if (!Array.isArray(raw)) return [...CONFIG_DEFAULTS.publicDecorators]; + return raw + .filter(n => typeof n === "string") + .map(n => n.trim().replace(/^@/, "")) + .filter(n => n !== ""); +} function mergePatterns(raw) { if (raw === null || raw === undefined) return null; if (!Array.isArray(raw)) return null; @@ -139,6 +149,7 @@ export function defaultConfig() { excludePaths: [...CONFIG_DEFAULTS.excludePaths], severityOverrides: [], publicAuthPatterns: null, + publicDecorators: [...CONFIG_DEFAULTS.publicDecorators], requireSpec: false, strictPublic: false, scan: { @@ -184,6 +195,7 @@ export function loadConfig(targetDir) { excludePaths: Array.isArray(raw.excludePaths) ? raw.excludePaths.map(String) : [...CONFIG_DEFAULTS.excludePaths], severityOverrides: mergeSeverityOverrides(raw.severityOverrides), publicAuthPatterns: mergePatterns(raw.publicAuthPatterns), + publicDecorators: mergePublicDecorators(raw.publicDecorators), requireSpec: typeof raw.requireSpec === "boolean" ? raw.requireSpec : CONFIG_DEFAULTS.requireSpec, strictPublic: typeof raw.strictPublic === "boolean" ? raw.strictPublic : CONFIG_DEFAULTS.strictPublic, scan: mergeScan(raw.scan) diff --git a/lib/inventory.mjs b/lib/inventory.mjs index a132543..14cc2c9 100644 --- a/lib/inventory.mjs +++ b/lib/inventory.mjs @@ -44,7 +44,7 @@ export function buildInventory(targetDir, config) { warnings.push(...r.warnings); } if (fw.nest) { - const r = parseNest(targetDir, excl, scan, candidateFiles); + const r = parseNest(targetDir, excl, scan, candidateFiles, { publicDecorators: config.publicDecorators }); if (r.endpoints.length) frameworksDetected.add("nest"); code.push(...r.endpoints); warnings.push(...r.warnings); diff --git a/lib/parsers/nest.mjs b/lib/parsers/nest.mjs index a062c35..ae6ad91 100644 --- a/lib/parsers/nest.mjs +++ b/lib/parsers/nest.mjs @@ -1,3 +1,4 @@ +import { CONFIG_DEFAULTS } from "../config.mjs"; import { readTextFile, walkFiles, filterFilesByExtension, relPath } from "../utils.mjs"; const EXTS = [".ts", ".js", ".mjs", ".tsx"]; @@ -5,6 +6,10 @@ const EXTS = [".ts", ".js", ".mjs", ".tsx"]; const METHOD_DECORATORS = [ "Get", "Post", "Put", "Patch", "Delete", "Options", "Head", "All" ]; +// A line holding another method anchor belongs to a different method: the +// decorator scans stop there so one-line methods do not borrow each other's +// decorators. +const METHOD_ANCHOR_LINE = new RegExp(`@(?:${METHOD_DECORATORS.join("|")})\\s*\\(`); /** * Parse NestJS routes statically. @@ -29,16 +34,30 @@ const METHOD_DECORATORS = [ * 3. Combine class-level + method-level markers as the endpoint's * authMarkers list. * + * Global guards and prefix (pre-pass over every scanned file, comments + * stripped): `{ provide: APP_GUARD, useClass|useExisting: X }` and + * `X.useGlobalGuards(new A(), ...)` add the guard class names as markers of + * every Nest endpoint in the scan, unless the controller or method carries + * a public decorator (options.publicDecorators). `X.setGlobalPrefix('lit')` + * prefixes every endpoint (a literal `exclude` array is honored; a + * non-literal prefix leaves them unresolved). + * * Unresolvable cases (controller path is a variable, dynamic decorator * argument, missing class body): record with resolved: false. */ -export function parseNest(targetDir, excludePaths = [], scanOptions = {}, candidateFiles = null) { +export function parseNest(targetDir, excludePaths = [], scanOptions = {}, candidateFiles = null, options = {}) { + const publicDecorators = new Set( + Array.isArray(options.publicDecorators) ? options.publicDecorators : CONFIG_DEFAULTS.publicDecorators + ); const files = candidateFiles === null ? walkFiles(targetDir, EXTS, excludePaths, scanOptions) : filterFilesByExtension(candidateFiles, EXTS); const endpoints = []; const warnings = []; + const controllerFiles = []; + const globalGuards = new Set(); + const prefixes = []; for (const file of files) { const rel = relPath(targetDir, file); const read = readTextFile(file, scanOptions.maxFileBytes); @@ -47,8 +66,14 @@ export function parseNest(targetDir, excludePaths = [], scanOptions = {}, candid continue; } const src = read.text; - if (!/@Controller\s*\(/.test(src)) continue; - + const stripped = stripComments(src); + for (const g of findGlobalGuards(stripped)) globalGuards.add(g); + prefixes.push(...findGlobalPrefixes(stripped)); + if (/@Controller\s*\(/.test(src)) controllerFiles.push({ rel, src }); + } + const globalMarkers = [...globalGuards]; + const prefixInfo = resolvePrefix(prefixes); + for (const { rel, src } of controllerFiles) { const controllers = findControllers(src); for (const ctrl of controllers) { const ctrlPath = ctrl.path; @@ -59,20 +84,24 @@ export function parseNest(targetDir, excludePaths = [], scanOptions = {}, candid for (const m of methods) { const subPath = m.path; const fullPath = combine(ctrlPath, subPath); - const resolved = ctrl.resolved && m.resolved; + const resolved = ctrl.resolved && m.resolved && !prefixInfo.dynamic; + const isPublic = [...ctrlMarkers, ...m.markers].some(n => publicDecorators.has(n)); + const inherited = isPublic ? [] : globalMarkers; endpoints.push({ method: m.verb.toUpperCase(), - path: resolved ? fullPath : null, + path: resolved ? applyPrefix(fullPath, prefixInfo) : null, file: rel, line: m.line, framework: "nest", resolved, - authMarkers: dedupSorted([...ctrlMarkers, ...m.markers]), + authMarkers: dedupSorted([...ctrlMarkers, ...m.markers, ...inherited]), unresolvedReason: resolved ? null : !ctrl.resolved ? "controller-path-not-static-string" - : "method-path-not-static-string" + : !m.resolved + ? "method-path-not-static-string" + : "global-prefix-not-static-string" }); } } @@ -81,6 +110,95 @@ export function parseNest(targetDir, excludePaths = [], scanOptions = {}, candid return { endpoints, warnings }; } +function stripComments(src) { + // Keep string literals intact so "//" inside a URL string is not a comment. + return src.replace(/("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? " "); +} +function findGlobalGuards(src) { + const out = []; + const providerRe = /\{[^{}]*\bprovide\s*:\s*APP_GUARD\b[^{}]*\}/g; + let m; + while ((m = providerRe.exec(src)) !== null) { + const g = m[0].match(/\b(?:useClass|useExisting)\s*:\s*([A-Za-z_$][\w$]*)/); + if (g) out.push(g[1]); + } + const callRe = /\.useGlobalGuards\s*\(/g; + while ((m = callRe.exec(src)) !== null) { + const args = balancedArgs(src, m.index + m[0].length); + for (const n of args.matchAll(/\bnew\s+([A-Za-z_$][\w$]*)\s*\(/g)) out.push(n[1]); + } + return out; +} +// Text between the "(" already consumed (openIdx is the index after it) and its matching ")". +function balancedArgs(src, openIdx) { + let depth = 1; + let i = openIdx; + while (i < src.length && depth > 0) { + if (src[i] === "(") depth++; + else if (src[i] === ")") depth--; + i++; + } + return src.slice(openIdx, depth === 0 ? i - 1 : i); +} +function splitTopLevel(raw) { + const parts = []; + let depth = 0; + let quote = null; + let cur = ""; + for (const c of raw) { + if (quote) { + if (c === quote) quote = null; + } else if (c === "'" || c === '"' || c === "`") quote = c; + else if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") depth--; + else if (c === "," && depth === 0) { + parts.push(cur); + cur = ""; + continue; + } + cur += c; + } + if (cur.trim() !== "") parts.push(cur); + return parts; +} +function findGlobalPrefixes(src) { + const out = []; + const re = /\.setGlobalPrefix\s*\(/g; + let m; + while ((m = re.exec(src)) !== null) { + const [first, second] = splitTopLevel(balancedArgs(src, m.index + m[0].length)); + const lit = first === undefined ? null : parseStringArg(first); + const isLiteral = lit !== null && !first.trim().startsWith("{") && !first.trim().startsWith("["); + out.push({ literal: isLiteral ? lit : null, exclude: isLiteral ? parseExclude(second) : [] }); + } + return out; +} +function parseExclude(raw) { + if (raw === undefined) return []; + const arr = raw.match(/\bexclude\s*:\s*(\[[\s\S]*\])/); + if (!arr) return []; + const out = []; + for (const item of splitTopLevel(arr[1].trim().slice(1, -1))) { + const t = item.trim(); + const lit = t.startsWith("{") ? t.match(/\bpath\s*:\s*(['"`])([^'"`$]*)\1/)?.[2] ?? null : parseStringArg(t); + if (lit !== null) out.push(trimSlashes(lit)); + } + return out; +} +function trimSlashes(s) { + return s.replace(/^\/+|\/+$/g, ""); +} +function resolvePrefix(found) { + if (found.length === 0) return { dynamic: false, prefix: "", exclude: [] }; + const distinct = new Set(found.map(f => (f.literal === null ? null : trimSlashes(f.literal)))); + if (distinct.has(null) || distinct.size > 1) return { dynamic: true, prefix: "", exclude: [] }; + return { dynamic: false, prefix: [...distinct][0], exclude: found.flatMap(f => f.exclude) }; +} +function applyPrefix(fullPath, info) { + if (info.prefix === "") return fullPath; + if (info.exclude.includes(trimSlashes(fullPath))) return fullPath; + return combine(info.prefix, fullPath); +} function findControllers(src) { const out = []; const ctrlRe = /@Controller\s*\(([\s\S]*?)\)/g; @@ -121,11 +239,17 @@ function collectAdjacentDecorators(src, controllerIdx) { const before = src.slice(0, controllerIdx); const lines = before.split(/\n/); const markers = []; + // Decorators on the same line, before the anchor: `@Public() @Get('x') m() {}`. + const sameLine = lines[lines.length - 1].trim(); + if (sameLine.startsWith("@")) { + for (const n of sameLine.matchAll(/@([A-Za-z_$][\w$]*)/g)) markers.push(n[1]); + } for (let i = lines.length - 2; i >= 0; i--) { const line = lines[i].trim(); if (line === "") continue; if (line.startsWith("//") || line.startsWith("*")) continue; if (!line.startsWith("@")) break; + if (METHOD_ANCHOR_LINE.test(line)) break; const name = line.match(/^@([A-Za-z_$][\w$]*)/); if (name) markers.push(name[1]); } @@ -147,6 +271,10 @@ function collectAdjacentDecorators(src, controllerIdx) { function collectDownwardDecorators(src, fromIdx) { const newlineIdx = src.indexOf("\n", fromIdx); if (newlineIdx === -1) return []; + // The method signature is on the anchor line (`@Get() list() {}`): the + // decorators on the following lines belong to the next method. + const restOfLine = src.slice(fromIdx, newlineIdx).replace(/\/\*.*?\*\/|\/\/.*$/g, "").trim(); + if (restOfLine !== "" && !restOfLine.startsWith("@")) return []; const after = src.slice(newlineIdx + 1); const lines = after.split(/\n/); const markers = []; @@ -155,6 +283,7 @@ function collectDownwardDecorators(src, fromIdx) { if (line === "") continue; if (line.startsWith("//") || line.startsWith("*")) continue; if (!line.startsWith("@")) break; + if (METHOD_ANCHOR_LINE.test(line)) break; const name = line.match(/^@([A-Za-z_$][\w$]*)/); if (name) markers.push(name[1]); } diff --git a/lib/report.mjs b/lib/report.mjs index 734f103..648d433 100644 --- a/lib/report.mjs +++ b/lib/report.mjs @@ -19,7 +19,7 @@ export const LIMITATIONS = Object.freeze([ "Routes mounted via dynamic strings (computed prefixes, runtime registration, factory functions) are reported as UNRESOLVED rather than guessed.", "ApiGate uses a built-in heuristic pattern list to mark common public-auth paths (login / signup / refresh / health / OAuth callbacks) as INTENTIONAL-PUBLIC. The heuristic is deterministic and configurable but can be wrong both ways — review the marked endpoints and override `publicAuthPatterns` in `.apigate.config.json` if your project disagrees.", "The per-endpoint `risk` tier (HIGH / MED / LOW) is a heuristic — pattern-based, frozen at `riskTier.version`. Use `severityOverrides` to pin specific endpoints. Risk is a triage aid, not a runtime exploitability claim.", - "NestJS global guards registered via `app.useGlobalGuards()` or `{ provide: APP_GUARD }` providers are INVISIBLE to ApiGate's per-controller parser. An endpoint protected ONLY by a global guard will be reported OPEN. If your project uses this pattern, extend `auth.nest` with your custom marker, or pin specific endpoints in `severityOverrides`. See `parserCapabilities.nest.globalGuardDetection`.", + "NestJS global guards are read from `{ provide: APP_GUARD, useClass|useExisting: X }` provider literals and `useGlobalGuards(new X())` calls, and apply to every Nest endpoint in the scan (no per-module or per-app resolution). An endpoint is GUARDED only if the guard class name is in `auth.nest`; add your custom guard name there. Controllers or methods with a `publicDecorators` decorator (default Public, SkipAuth, AllowAnonymous) do not receive the global guard. Not detected: `useFactory`/`useValue` providers, guards passed as a variable, RouterModule, versioning. A literal `setGlobalPrefix()` is applied to every Nest endpoint; a non-literal prefix leaves them unresolved, and only a literal `exclude` array is honored. See `parserCapabilities.nest`.", "ApiGate makes ZERO network calls. It does not send code, telemetry, or scan artifacts anywhere. Reports are written to local files only." ]); diff --git a/test/capabilities.mjs b/test/capabilities.mjs index c945ccf..2295d2e 100644 --- a/test/capabilities.mjs +++ b/test/capabilities.mjs @@ -42,6 +42,14 @@ t.test("NestJS: controller object/array arg handling is documented", () => { assertEq(n.classLevelGuards, true); assertEq(n.dynamicDecoratorArg, "UNRESOLVED"); }); +t.test("NestJS: global guard detection is true and its rules are documented", () => { + const n = PARSER_CAPABILITIES.nest; + assertEq(n.globalGuardDetection, true); + for (const k of ["globalGuardRules", "globalPrefix", "publicDecorators"]) { + if (typeof n[k] !== "string" || n[k] === "") throw new Error(`nest.${k} missing`); + } + if (!KNOWN_UNRESOLVED_REASONS.includes("global-prefix-not-static-string")) throw new Error("reason missing"); +}); t.test("OpenAPI: missing security is conservative UNKNOWN", () => { const o = PARSER_CAPABILITIES.openapi; diff --git a/test/config.mjs b/test/config.mjs index 57ead51..34e27bb 100644 --- a/test/config.mjs +++ b/test/config.mjs @@ -53,6 +53,20 @@ t.test("defaultConfig() returns plain object suitable for mutation", () => { assertEq(cfg2.frameworks.express, true); }); +t.test("publicDecorators: default, custom list with @ stripped, [] and invalid value", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "apigate-cfg-")); + const cfgFile = path.join(dir, ".apigate.config.json"); + const def = ["Public", "SkipAuth", "AllowAnonymous"]; + assertEq(JSON.stringify(defaultConfig().publicDecorators), JSON.stringify(def)); + fs.writeFileSync(cfgFile, "{}"); + assertEq(JSON.stringify(loadConfig(dir).publicDecorators), JSON.stringify(def)); + fs.writeFileSync(cfgFile, JSON.stringify({ publicDecorators: ["@Open", " NoAuth ", 3, ""] })); + assertEq(JSON.stringify(loadConfig(dir).publicDecorators), JSON.stringify(["Open", "NoAuth"])); + fs.writeFileSync(cfgFile, JSON.stringify({ publicDecorators: [] })); + assertEq(loadConfig(dir).publicDecorators.length, 0); + fs.writeFileSync(cfgFile, JSON.stringify({ publicDecorators: "Public" })); + assertEq(JSON.stringify(loadConfig(dir).publicDecorators), JSON.stringify(def)); +}); t.test(".apigate.config.example.json is valid JSON", () => { const root = path.resolve(__dirname, ".."); const raw = fs.readFileSync(path.join(root, ".apigate.config.example.json"), "utf-8"); diff --git a/test/fixtures/nest-global-edge/app.module.ts b/test/fixtures/nest-global-edge/app.module.ts new file mode 100644 index 0000000..9def05f --- /dev/null +++ b/test/fixtures/nest-global-edge/app.module.ts @@ -0,0 +1,10 @@ +import { Module } from "@nestjs/common"; +import { APP_GUARD } from "@nestjs/core"; + +// { provide: APP_GUARD, useClass: CommentedGuard } +/* { provide: APP_GUARD, useClass: BlockCommentedGuard } */ +@Module({ + controllers: [ItemsController, OpenController], + providers: [{ useExisting: OrgGuard, provide: APP_GUARD }] +}) +export class AppModule {} diff --git a/test/fixtures/nest-global-edge/items.controller.ts b/test/fixtures/nest-global-edge/items.controller.ts new file mode 100644 index 0000000..e124a5c --- /dev/null +++ b/test/fixtures/nest-global-edge/items.controller.ts @@ -0,0 +1,31 @@ +import { Controller, Get, Post } from "@nestjs/common"; + +@Controller("items") +export class ItemsController { + @Get() list() {} + @Public() + @UseGuards(RolesGuard) + @Post() create() {} +} + +@SkipAuth() +@Controller("open") +export class OpenController { + @Get("info") info() {} +} + +@Controller("status") +export class StatusController { + @Get() status() {} +} + +@Controller("ping") +export class PingController { + @Get() ping() {} +} +@Controller("notes") +export class NotesController { + @Get(":id") // fetch one + @UseGuards(RolesGuard) + findOne() {} +} diff --git a/test/fixtures/nest-global-edge/main.ts b/test/fixtures/nest-global-edge/main.ts new file mode 100644 index 0000000..d8e6902 --- /dev/null +++ b/test/fixtures/nest-global-edge/main.ts @@ -0,0 +1,8 @@ +import { NestFactory } from "@nestjs/core"; + +async function bootstrap() { + const app = await NestFactory.create(AppModule); + app.useGlobalGuards(new JwtAuthGuard(reflector)); + app.setGlobalPrefix("/v1/", { exclude: ["status", { path: "ping", method: RequestMethod.GET }] }); +} +bootstrap(); diff --git a/test/fixtures/nest-global-nonliteral/main.ts b/test/fixtures/nest-global-nonliteral/main.ts new file mode 100644 index 0000000..4f0b174 --- /dev/null +++ b/test/fixtures/nest-global-nonliteral/main.ts @@ -0,0 +1,4 @@ +async function bootstrap() { + const app = await NestFactory.create(AppModule); + app.setGlobalPrefix(process.env.PREFIX); +} diff --git a/test/fixtures/nest-global-nonliteral/things.controller.ts b/test/fixtures/nest-global-nonliteral/things.controller.ts new file mode 100644 index 0000000..1b5d1c5 --- /dev/null +++ b/test/fixtures/nest-global-nonliteral/things.controller.ts @@ -0,0 +1,4 @@ +@Controller("things") +export class ThingsController { + @Get() list() {} +} diff --git a/test/fixtures/nest-global-orgonly/accounts.controller.ts b/test/fixtures/nest-global-orgonly/accounts.controller.ts new file mode 100644 index 0000000..8373de7 --- /dev/null +++ b/test/fixtures/nest-global-orgonly/accounts.controller.ts @@ -0,0 +1,4 @@ +@Controller("accounts") +export class AccountsController { + @Get() list() {} +} diff --git a/test/fixtures/nest-global-orgonly/app.module.ts b/test/fixtures/nest-global-orgonly/app.module.ts new file mode 100644 index 0000000..b5b2318 --- /dev/null +++ b/test/fixtures/nest-global-orgonly/app.module.ts @@ -0,0 +1,2 @@ +@Module({ controllers: [AccountsController], providers: [{ provide: APP_GUARD, useClass: OrgGuard }] }) +export class AppModule {} diff --git a/test/fixtures/nest-global/app.module.ts b/test/fixtures/nest-global/app.module.ts new file mode 100644 index 0000000..48a2c69 --- /dev/null +++ b/test/fixtures/nest-global/app.module.ts @@ -0,0 +1,7 @@ +import { Module } from "@nestjs/common"; +import { APP_GUARD } from "@nestjs/core"; +import { UsersController } from "./users.controller"; +import { JwtAuthGuard } from "./jwt-auth.guard"; + +@Module({ controllers: [UsersController], providers: [{ provide: APP_GUARD, useClass: JwtAuthGuard }] }) +export class AppModule {} diff --git a/test/fixtures/nest-global/main.ts b/test/fixtures/nest-global/main.ts new file mode 100644 index 0000000..f02da41 --- /dev/null +++ b/test/fixtures/nest-global/main.ts @@ -0,0 +1,9 @@ +import { NestFactory } from "@nestjs/core"; +import { AppModule } from "./app.module"; + +async function bootstrap() { + const app = await NestFactory.create(AppModule); + app.setGlobalPrefix("api"); + await app.listen(3000); +} +bootstrap(); diff --git a/test/fixtures/nest-global/users.controller.ts b/test/fixtures/nest-global/users.controller.ts new file mode 100644 index 0000000..6c58539 --- /dev/null +++ b/test/fixtures/nest-global/users.controller.ts @@ -0,0 +1,9 @@ +import { Controller, Get, Post } from "@nestjs/common"; +import { Public } from "./public.decorator"; + +@Controller("users") +export class UsersController { + @Get() list() {} + @Post() create() {} + @Public() @Get("health") health() {} +} diff --git a/test/parser-nest.mjs b/test/parser-nest.mjs index 1a297b5..c8b1d7a 100644 --- a/test/parser-nest.mjs +++ b/test/parser-nest.mjs @@ -1,6 +1,9 @@ import path from "path"; import { fileURLToPath } from "url"; import { parseNest } from "../lib/parsers/nest.mjs"; +import { loadConfig, defaultConfig } from "../lib/config.mjs"; +import { buildInventory } from "../lib/inventory.mjs"; +import { classifyAll } from "../lib/auth.mjs"; import { runner, assertEq } from "./_runner.mjs"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -80,4 +83,70 @@ t.test("v0.3 bidirectional: markers stay sorted + deduped", () => { } }); +// Global guards, setGlobalPrefix and publicDecorators. +const fx = name => path.join(__dirname, "fixtures", name); +const find = (eps, method, p) => eps.find(x => x.method === method && x.path === p); +const globalEps = parseNest(fx("nest-global"), []).endpoints; +const edgeEps = parseNest(fx("nest-global-edge"), []).endpoints; +t.test("global: APP_GUARD useClass adds the guard marker and setGlobalPrefix applies", () => { + const e = find(globalEps, "GET", "/api/users"); + if (!e) throw new Error(`GET /api/users missing: ${JSON.stringify(globalEps.map(x => x.path))}`); + if (!e.authMarkers.includes("JwtAuthGuard")) throw new Error("JwtAuthGuard marker missing"); + if (!find(globalEps, "POST", "/api/users")) throw new Error("POST /api/users missing"); +}); +t.test("global: @Public method does not receive the global guard marker", () => { + const e = find(globalEps, "GET", "/api/users/health"); + if (!e) throw new Error("GET /api/users/health missing"); + assertEq(e.authMarkers.includes("JwtAuthGuard"), false); +}); +t.test("global: useExisting (any key order) and useGlobalGuards(new X()) both detected, comments ignored", () => { + const e = find(edgeEps, "GET", "/v1/items"); + if (!e) throw new Error(`GET /v1/items missing: ${JSON.stringify(edgeEps.map(x => x.path))}`); + assertEq(JSON.stringify(e.authMarkers), JSON.stringify(["JwtAuthGuard", "OrgGuard"])); +}); +t.test("global: class-level public decorator cancels the global guard for the whole controller", () => { + const e = find(edgeEps, "GET", "/v1/open/info"); + if (!e) throw new Error("GET /v1/open/info missing"); + assertEq(JSON.stringify(e.authMarkers), JSON.stringify(["SkipAuth"])); +}); +t.test("global: explicit @UseGuards next to @Public is kept, global markers are not added", () => { + const e = find(edgeEps, "POST", "/v1/items"); + if (!e) throw new Error("POST /v1/items missing"); + assertEq(JSON.stringify(e.authMarkers), JSON.stringify(["Public", "UseGuards"])); +}); +t.test("global: literal exclude array skips the prefix (string and { path } forms)", () => { + if (!find(edgeEps, "GET", "/status")) throw new Error("/status should not be prefixed"); + if (!find(edgeEps, "GET", "/ping")) throw new Error("/ping should not be prefixed"); +}); +t.test("global: publicDecorators option overrides the default list", () => { + const eps = parseNest(fx("nest-global"), [], {}, null, { publicDecorators: [] }).endpoints; + const e = find(eps, "GET", "/api/users/health"); + assertEq(e.authMarkers.includes("JwtAuthGuard"), true); +}); +t.test("global: non-literal setGlobalPrefix leaves endpoints unresolved with a known reason", () => { + const eps = parseNest(fx("nest-global-nonliteral"), []).endpoints; + assertEq(eps.length, 1); + assertEq(eps[0].resolved, false); + assertEq(eps[0].path, null); + assertEq(eps[0].unresolvedReason, "global-prefix-not-static-string"); +}); +t.test("global: end to end, acceptance postures with default config", () => { + const dir = fx("nest-global"); + const cls = classifyAll(buildInventory(dir, loadConfig(dir)).code, loadConfig(dir)); + const post = (m, p) => cls.find(x => x.method === m && x.path === p)?.posture; + assertEq(post("GET", "/api/users"), "GUARDED"); + assertEq(post("POST", "/api/users"), "GUARDED"); + assertEq(post("GET", "/api/users/health"), "OPEN"); +}); +t.test("global: a guard whose name matches no auth.nest marker stays OPEN", () => { + const dir = fx("nest-global-orgonly"); + const cfg = defaultConfig(); + const cls = classifyAll(buildInventory(dir, cfg).code, cfg); + assertEq(cls[0].posture, "OPEN"); +}); +t.test("nest: trailing comment on the anchor line keeps the decorators below it", () => { + const e = find(edgeEps, "GET", "/v1/notes/:id"); + if (!e) throw new Error("GET /v1/notes/:id missing"); + assertEq(e.authMarkers.includes("UseGuards"), true); +}); t.finish();