Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .apigate.config.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -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/<id>`) 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.",

Expand Down
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
25 changes: 22 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<method>(...)` 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.
Expand Down Expand Up @@ -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.*"],
Expand All @@ -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 |
Expand All @@ -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
Expand All @@ -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:**
Expand Down Expand Up @@ -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
Expand All @@ -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).

Expand Down
6 changes: 5 additions & 1 deletion lib/capabilities.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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",
Expand Down
14 changes: 13 additions & 1 deletion lib/config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
Expand All @@ -139,6 +149,7 @@ export function defaultConfig() {
excludePaths: [...CONFIG_DEFAULTS.excludePaths],
severityOverrides: [],
publicAuthPatterns: null,
publicDecorators: [...CONFIG_DEFAULTS.publicDecorators],
requireSpec: false,
strictPublic: false,
scan: {
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion lib/inventory.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading