npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

guardrail-api

v2.1.1

Published

API Security CLI for static OpenAPI analysis and dynamic security testing

Readme

Guardrail API

CI npm version License: MIT Node.js SARIF 2.1.0

English · Español

Security checks for your API, driven by its OpenAPI contract. Guardrail API reads your OpenAPI/Swagger spec, flags risky design decisions (missing auth, unvalidated input, exposed admin endpoints) and, optionally, probes the running API to verify that what the contract promises is actually enforced. It is built for CI: stable exit codes, baselines for existing projects and SARIF output for GitHub Code Scanning.

  • Static analysis of OpenAPI 2.0 / 3.0 / 3.1 (JSON or YAML), with findings pinned to the exact line of the spec.
  • Contract-driven dynamic probes (lightweight DAST): unauthenticated access to secured endpoints, security headers, CORS and error handling under malformed input.
  • Safe by default: dynamic probes only send GET, HEAD and OPTIONS unless you explicitly opt in.
  • CI-ready: --fail-on thresholds, a baseline so only new findings break the build, and reports in console, JSON, Markdown, HTML and SARIF.

Quick start

No installation needed:

npx guardrail-api audit --spec ./openapi.yaml --static-only
🛡️  GUARDRAIL API SECURITY AUDIT
Specification:  Vulnerable Demo Petstore API (openapi.yaml)
Operations:     6 endpoints analyzed

┌────────────┬──────────┬───────────┬──────────┬──────────┬──────────┐
│ CRITICAL   │ HIGH     │ MEDIUM    │ LOW      │ INFO     │ TOTAL    │
├────────────┼──────────┼───────────┼──────────┼──────────┼──────────┤
│ 2          │ 4        │ 2         │ 2        │ 0        │ 10       │
└────────────┴──────────┴───────────┴──────────┴──────────┴──────────┘

 CRITICAL  [ST-003] Sensitive Endpoint Exposed Without Security Constraints
   Location:     DELETE /admin/users (line 119, col 7)
   Description:  Endpoint DELETE /admin/users handles sensitive resources (matches keyword 'admin')
                 but has no authentication or authorization constraints declared.
   Remediation:  Protect DELETE /admin/users with strong authentication and role-based access control (RBAC).
...
❌ AUDIT FAILED: Security findings equal or exceed threshold 'CRITICAL'.

Add the running API to also verify what the contract declares:

npx guardrail-api audit \
  --spec ./openapi.yaml \
  --target http://localhost:3000 \
  -H "Authorization: Bearer $API_TOKEN"

To pin the version in a project:

npm install --save-dev guardrail-api   # or: pnpm add -D guardrail-api

Requires Node.js 20 or later.


Usage

Static analysis

Analyzes the contract only. No running API required, so it is fast and safe to run on every pull request.

guardrail-api audit --spec ./openapi.yaml --static-only

--spec accepts a local file or a URL (--spec https://api.example.com/openapi.json).

Dynamic probes

When a target is available (from --target, the config file or servers[0] in the spec), Guardrail API also sends real requests to it:

guardrail-api audit --spec ./openapi.yaml --target https://staging.example.com --fail-on high

What you should know before pointing it at an environment:

  • Safe mode is the default. Only GET, HEAD and OPTIONS are sent. Operations that change state are skipped and listed in the report (dynamicScope.skippedOperations). Use --allow-destructive to include POST/PUT/PATCH/DELETE, only against a disposable environment: probes may create, modify or delete data.
  • Credentials. Headers passed with -H are used on normal requests, but credential headers (Authorization, Cookie, Proxy-Authorization, X-API-Key, any apiKey header declared in securitySchemes, and those listed in credentialHeaders) are stripped from the unauthenticated probes of DY-001. A correctly protected endpoint is therefore never reported as a bypass.
  • Two identities for BOLA. Pass a second user's credentials with --auth-b "Authorization: Bearer <token of user B>" (or secondaryHeaders in the config) and DY-005 checks whether user B can read objects of user A (the -H identity). Without it, DY-005 is skipped and listed in coverage.skippedRules. The pathParams/example IDs must belong to user A.
  • Real IDs. Path parameters are filled from pathParams in the config, then from the spec's example/default/enum, then from a value based on the type. If a secured endpoint answers 404 because the ID does not exist, it is reported as inconclusive, never as passed. Set pathParams to IDs that exist in that environment for full coverage.
  • Coverage is reported. The report lists requests sent, failures and status codes. If the target is unreachable, the audit exits with code 2, not a false pass.

Use --dynamic-only to skip the static rules.

Reports

guardrail-api audit --spec ./openapi.yaml --format sarif    --output results.sarif  # GitHub Code Scanning
guardrail-api audit --spec ./openapi.yaml --format markdown --output report.md      # PR comments / job summaries
guardrail-api audit --spec ./openapi.yaml --format html     --output report.html    # self-contained page
guardrail-api audit --spec ./openapi.yaml --format json     --output report.json    # further processing

Without --output, JSON, Markdown, HTML and SARIF are printed to stdout. With the default console format and an --output path, the file format is inferred from the extension (.html, .md, .sarif, otherwise JSON).


Using it in CI

GitHub Action

The official action runs the audit, uploads the SARIF report to GitHub Code Scanning and fails the job with the CLI's exit code:

name: API Security

on:
  pull_request:
  push:
    branches: [main]

jobs:
  guardrail:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write # required to upload SARIF to Code Scanning
    steps:
      - uses: actions/checkout@v4

      - uses: CodeJairo/guardrail-api@v2
        with:
          spec: ./docs/openapi.yaml
          fail-on: high

To add dynamic probes against a staging environment, pass the target and the credentials from secrets (one Key: Value per line; values are masked in the log):

      - uses: CodeJairo/guardrail-api@v2
        with:
          spec: ./docs/openapi.yaml
          target: https://staging.example.com
          fail-on: high
          headers: |
            Authorization: Bearer ${{ secrets.STAGING_API_TOKEN }}

| Input | Default | Description | | :--- | :--- | :--- | | spec | (required) | OpenAPI/Swagger spec, local path or URL. | | target | | Base URL of the running API for dynamic probes. | | fail-on | CLI default (critical) | critical | high | medium | low | info. | | format | sarif | sarif | json | markdown | html | console. | | output | guardrail.<ext> | Report file (guardrail.sarif for SARIF). | | config | | Config file (.guardrailrc.json is picked up automatically). | | baseline | | Baseline file: only new findings count toward fail-on. | | static-only | false | Run only the static rules. | | headers | | Extra headers for dynamic probes, one Key: Value per line. | | allow-destructive | false | Also send POST/PUT/PATCH/DELETE probes (disposable environments only). | | timeout | | Per-request timeout in ms. | | version | 2 | npm version or range of guardrail-api to run. | | upload-sarif | true | Upload the report to Code Scanning when format is sarif. | | working-directory | . | Where to run. Keep the repository root so SARIF locations resolve. |

| Output | Description | | :--- | :--- | | exit-code | 0 passed, 1 findings at or above fail-on, 2 the scan could not be trusted. | | report-path | Absolute path of the report file. | | total, critical, high, medium, low | Finding counts (SARIF and JSON formats). |

  • The action runs npx guardrail-api@<version> and needs no build step. If the runner has no Node.js 20+, it installs Node 22 with actions/setup-node.
  • The SARIF report is uploaded even when the audit fails; the job then fails with the CLI's exit code. Use continue-on-error: true and the exit-code output to decide yourself.
  • @v2 follows the latest 2.x release. Pin a full tag (@v2.1.0) or a commit SHA for fully reproducible builds.

Other CI systems

Any CI with Node.js 20+ can run the CLI directly:

npx --yes guardrail-api@2 audit \
  --spec ./docs/openapi.yaml \
  --fail-on high \
  --format sarif \
  --output results.sarif
  • Pin the major version (guardrail-api@2) so a future major release cannot break your pipeline unexpectedly.
  • Run it from the repository root: SARIF paths are relative to it, which lets code scanning tools link each alert to the right line of your spec.
  • To add dynamic probes, add --target and pass the token from a secret: -H "Authorization: Bearer $STAGING_API_TOKEN".

Adopting it on an existing API

The first audit of a mature API usually reports dozens of findings. Instead of fixing everything before enabling CI, record the current state in a baseline and fail only on new findings:

# 1. Record today's findings (creates .guardrail-baseline.json)
npx guardrail-api audit --spec ./openapi.yaml --static-only --update-baseline

# 2. Commit the baseline next to the code
git add .guardrail-baseline.json

# 3. In CI, only findings that are not in the baseline count toward --fail-on
npx guardrail-api audit --spec ./openapi.yaml --static-only --baseline .guardrail-baseline.json --fail-on high
  • Findings are identified by a stable fingerprint (rule, method, path, title and parameter), so the baseline does not drift between runs.
  • Baselined findings are excluded from findings and summary but kept in the JSON report under baseline.findings. Fixed entries are listed in baseline.stale, and the console suggests refreshing the file with --update-baseline.
  • Use the same scope (--static-only, --target…) when creating and checking the baseline; otherwise dynamic entries show up as stale.
  • If the baseline file does not exist, the audit fails with an explicit error (except with --update-baseline, which creates it). Runs with --update-baseline always exit 0.

Exit codes

| Code | Meaning | | :--- | :--- | | 0 | Passed: no finding reaches the --fail-on threshold. | | 1 | At least one finding is at or above --fail-on (default critical). | | 2 | The scan could not be trusted: invalid arguments or config, unreadable spec, a rule crashed, or dynamic analysis was requested and the target was unreachable. |

2 takes precedence over 1: an incomplete scan is never reported as a result.


Rules

| ID | Type | Default severity | What it checks | CWE | | :--- | :--- | :--- | :--- | :--- | | ST-001 | Static | High | Operations without any security requirement | 306 | | ST-002 | Static | Medium | Untyped or unbounded input, mass assignment risk | 20 | | ST-003 | Static | Critical | Sensitive or destructive endpoints without auth | 285 | | ST-004 | Static | High | Plain HTTP servers, API keys in the query string | 319, 598 | | ST-005 | Static | High | OAuth2 implicit/password flows, HTTP Basic | 1390, 522 | | ST-006 | Static | Medium | Inputs that accept URLs (SSRF, open redirect) | 918 | | ST-007 | Static | High | Credentials in example/examples/default values | 798 | | DY-001 | Dynamic | Critical | Secured endpoints that answer without credentials | 306 | | DY-002 | Dynamic | Medium | Missing security headers, version disclosure | 693 | | DY-003 | Dynamic | High | Permissive or reflected CORS origins | 942 | | DY-004 | Dynamic | High | 500 errors on malformed input | 20 | | DY-005 | Dynamic | Critical | Objects of one user readable by another (BOLA/IDOR) | 639 | | DY-006 | Dynamic | Low | Response properties missing from the documented schema | 213 | | DY-007 | Dynamic | Medium | Stack traces, SQL errors and debug pages in error responses | 209 | | DY-008 | Dynamic | Medium | Undocumented HTTP methods that answer 2xx, TRACE | 749 |

Severity varies per finding; the table shows each rule's default.

OWASP API Top 10 coverage

Every finding carries its rule's OWASP API Security Top 10 (2023) categories: owasp in JSON and in SARIF result properties, owasp-api-2023/APIn tags on SARIF rules, an OWASP APIn:2023 tag in the console, Markdown and HTML reports.

| Category | Rules | Coverage | | :--- | :--- | :--- | | API1:2023 Broken Object Level Authorization | DY-005 | Cross-user access to the same object (needs a second identity with --auth-b) | | API2:2023 Broken Authentication | ST-001, ST-003, ST-005, DY-001 | Missing/unenforced auth, weak flows | | API3:2023 Broken Object Property Level Authorization | ST-002, DY-006 | Mass assignment and undocumented response properties | | API4:2023 Unrestricted Resource Consumption | ST-002 | Unbounded inputs only, no rate limiting checks | | API5:2023 Broken Function Level Authorization | ST-003, DY-008 | Unauthenticated sensitive/destructive endpoints, undocumented methods (no role-based checks) | | API6:2023 Unrestricted Access to Sensitive Business Flows | — | Not covered (business logic) | | API7:2023 Server Side Request Forgery | ST-006 | URL-accepting inputs in the contract (no live SSRF probes) | | API8:2023 Security Misconfiguration | ST-004, ST-007, DY-002, DY-003, DY-004, DY-007 | Transport, leaked secrets, headers, CORS, error handling, verbose errors | | API9:2023 Improper Inventory Management | DY-008 | HTTP methods accepted but not documented (no API version or host inventory) | | API10:2023 Unsafe Consumption of APIs | — | Not covered (depends on server-side code) |

Static rules

  • ST-001 · Missing Authentication Scheme. Reports operations that declare no security requirement, neither on the operation nor globally. Operations with an explicit security: [] (a documented choice to be public) and OPTIONS preflights are not reported, nor are authentication bootstrap endpoints (/login, /register, /token…), which must be public.
  • ST-002 · Strict Parameter & Schema Validation. Inspects parameters and request bodies, recursing into properties, items, allOf/oneOf/anyOf and additionalProperties, with protection against circular references. To keep noise low:
    • Untyped parameter (Medium): one finding per parameter without a type or schema.
    • Unbounded inputs (Low): at most one finding per operation, listing strings without maxLength/pattern/enum/format and numbers without minimum/maximum, including body properties by JSON path (e.g. body.address.zip).
    • Untyped request body (High): a body without type, properties, items or composition.
    • Mass assignment (Medium): only when an object that does not set additionalProperties: false contains readOnly: true properties or server-controlled names: role(s), admin, isAdmin, superuser, staff, permissions, privileges, scopes, balance, credit(s), verified, emailVerified, approved, ownerId, tenantId, passwordHash, hashedPassword, passwordSalt, salt (compared ignoring case, _ and -). Generic names such as status or password are deliberately excluded.
  • ST-003 · Unprotected Sensitive Endpoints. Flags unauthenticated endpoints whose path suggests sensitive resources, and unauthenticated DELETE/PUT/PATCH. Privileged resources (/admin, /roles, /permissions, /secrets, /billing, /keys…) are Critical; generic ones (/users, /accounts, /settings) are High. Authentication bootstrap endpoints (/login, /signup, /register, /oauth, /token, /refresh, /forgot-password…) are excluded because they must be public.
  • ST-004 · Insecure Transport. Two checks:
    • Plain HTTP server (High, Medium when an HTTPS server for the same host is also declared): servers[].url at root, path and operation level (variables resolved with their default), or schemes: [http] + host in Swagger 2.0. Local and reserved hosts are skipped: localhost, 127.x, ::1, 0.0.0.0, *.localhost, *.local, *.test, *.example, *.invalid and example.com/.org/.net. Relative URLs, unresolved variables and Swagger 2.0 specs without an explicit schemes are not reported.
    • API key in the query string (Medium; Low when the scheme is not referenced by any security requirement): apiKey schemes with in: query, because URLs end up in access logs, proxies, browser history and Referer headers even over HTTPS.
  • ST-005 · Weak OAuth2 Flows. Flags OAuth2 schemes with the implicit flow (High) or the resource owner password flow (High), both deprecated by the OAuth 2.0 Security BCP (RFC 9700) and removed in OAuth 2.1, and HTTP basic authentication (Medium). Schemes that are defined but never referenced are reported as Low. authorizationCode, clientCredentials, bearer and digest schemes are not reported.
  • ST-006 · SSRF-Prone Parameters. Reports, once per operation, the parameters and request body properties (recursively, with circular reference protection) that accept a URL: format: uri/url/uri-reference/iri, or names such as url, uri, callback, webhook, redirect, returnTo, feed, endpoint and anything ending in Url/Uri (callbackUrl, redirect_uri, image_url…), compared ignoring case, _ and -. Ambiguous names (next, target, dest, destination) only count when an example, default or description shows a URL, so pagination cursors are not flagged. Non-string, enum/const and readOnly inputs are skipped. Medium, High when the operation requires no authentication.
  • ST-007 · Secrets in Spec Examples. Scans example, examples and default values anywhere in the specification (not descriptions, not x- extensions) for PEM private keys (Critical), AWS access key IDs, GitHub tokens, Slack tokens and Stripe live keys (High), JWTs, Bearer tokens and high-entropy values in fields named like password, secret, token or apiKey (Medium). Obvious placeholders (your-api-key, changeme, xxxx, <token>, ..., values containing example/sample/dummy…), AWS documentation keys and the jwt.io sample token are ignored. The secret is never printed: messages show its first 4 characters and its length.

Findings of ST-004, ST-005 and ST-007 carry a JSON Pointer in details.specPointer (e.g. /servers/2, /components/securitySchemes/oauth/flows/implicit), used for the report line and to keep fingerprints distinct.

Dynamic rules

  • DY-001 · Missing Authentication Enforcement. Calls each secured operation without credentials. A 2xx response is reported as a Critical authentication bypass. 404/405 responses and network errors are recorded as inconclusive in coverage.inconclusive.
  • DY-002 · Security Headers Validation. Checks X-Content-Type-Options: nosniff, Strict-Transport-Security (HTTPS targets only: browsers ignore it over HTTP), X-Frame-Options or CSP frame-ancestors, Content-Security-Policy, and version disclosure in X-Powered-By and Server.
  • DY-003 · CORS Misconfiguration Check. Sends Origin: https://malicious-domain.com and detects reflected origins (Critical when combined with Access-Control-Allow-Credentials: true), wildcards with credentials and wildcards on authenticated endpoints.
  • DY-004 · Input Validation Fuzzing & Error Handling. Sends invalid types and special characters in path, query and body. Reports operations that answer 500 instead of a controlled 400/422.
  • DY-005 · Broken Object Level Authorization (BOLA/IDOR). OWASP API1:2023. Needs a second identity (--auth-b / secondaryHeaders); skipped otherwise. For every secured GET addressed by a path parameter with a known ID (from pathParams or a spec example, never a guessed fallback), it requests the object as identity A (-H) and then as identity B: B's headers replace A's credential headers, other headers are kept. If both get 2xx and B receives the same object, it is a Critical finding. "Same object" means the same identity fields (id, _id, uuid, *Id, *_id) when A's body has them, otherwise the same normalized body (sorted keys, timestamps and request IDs ignored). B answered 401/403/404, or a different object (its own), passes. A not getting 2xx, an empty body, no known ID or another status for B is recorded as inconclusive. Public operations (security: []) are not probed. The reproduction curl masks B's credentials (Bearer <redacted>). If an object is meant to be shared between users, suppress the finding.
  • DY-006 · Undocumented Response Properties (Excessive Data Exposure). OWASP API3:2023. Sends each GET and compares a 2xx JSON body with the documented response schema for that status (exact code, then 2XX; application/json or any +json media type). It recurses into nested objects and arrays and treats allOf/oneOf/anyOf as a union, so a property declared in any branch counts as documented; null values are accepted. Only objects whose schema declares properties are checked: extra keys are documented by additionalProperties: true, an additionalProperties schema or a matching patternProperties; schemas without properties (free-form objects) are not checked. One finding per operation lists the JSON paths ($.address.internalCode, $[*].extra), never their values. Low by default; High when an undocumented name looks sensitive (password, hash, salt, token, secret, apiKey, ssn, cvv, otp, internal…; pagination tokens excluded).
  • DY-007 · Verbose Error Disclosure. OWASP API8:2023. Provokes errors with malformed input: path and query parameters set to guardrail'"<>;-- on GET operations, a request to an unknown route and, only with --allow-destructive, a truncated JSON body on POST/PUT/PATCH. Error responses (4xx/5xx) are searched for SQL errors (MySQL, PostgreSQL, Oracle, SQL Server, SQLite, ORMs) and framework debug pages (Django, Werkzeug, Laravel, Symfony, ASP.NET, Rails, Express, debug headers), both High; stack traces (Java, .NET, Python, Node.js, Go, PHP, Ruby, or a stack property in a JSON error), Medium; and internal file paths, Low. One finding per operation with short, truncated excerpts.
  • DY-008 · Undocumented HTTP Methods. OWASP API9:2023 / API5:2023. For every documented path it sends the methods the path does not declare. In safe mode only GET is sent (on paths that do not document GET/HEAD); POST/PUT/PATCH/DELETE and a single TRACE (Cross-Site Tracing) are only sent with --allow-destructive. A 2xx is a finding (Medium; High for state-changing methods); 404/405/501 and 401/403 are fine. A control request to a route that cannot exist avoids false positives on catch-all servers: if it answers 2xx for a method, that method is not checked. OPTIONS and HEAD are never flagged.

Configuration

Guardrail API looks for .guardrailrc.json (or .guardrailrc) in the working directory. Use --config <path> to load another file. Command-line flags take precedence over the config.

A typical config:

{
  "$schema": "./node_modules/guardrail-api/schema/guardrailrc.schema.json",
  "failOn": "high",
  "baseline": ".guardrail-baseline.json",
  "ignore": {
    "endpoints": ["/health", "/internal/**"]
  },
  "rules": {
    "DY-002": "low"
  },
  "pathParams": {
    "userId": "42"
  }
}

The $schema line enables autocompletion and validation in editors such as VS Code. The file is also validated when loaded: unknown options (with a hint for typos such as failon → failOn), wrong types and unknown rule IDs stop the run with exit code 2 and the full list of problems.

Reference

| Option | Type | Description | | :--- | :--- | :--- | | failOn | critical | high | medium | low | info | Same as --fail-on. | | targetUrl | URL | Base URL for dynamic probes. Same as --target. | | timeout | integer (ms) | Per-request timeout. Default 5000. | | customHeaders | object | Headers added to dynamic requests. Same as -H. | | credentialHeaders | string[] | Extra header names that carry credentials, stripped from unauthenticated probes. | | allowDestructive | boolean | Same as --allow-destructive. | | pathParams | object | Real values for path parameters, by name ({ "userId": "42" }). | | secondaryHeaders | object | Credential headers of a second identity for DY-005 ({ "Authorization": "Bearer <token of user B>" }). Same as --auth-b. | | baseline | path | Baseline file. Same as --baseline. | | ignore.endpoints | string[] | Endpoints whose findings are ignored and that are never probed by dynamic rules. See below. | | ignore.rules | string[] | Rule IDs ignored in the whole project. Ignored dynamic rules send no requests. | | rules | object | Severity override per rule: a severity, or off to drop the rule ({ "ST-002": "off" }). |

Ignoring is not just cosmetic: endpoints in ignore.endpoints, dynamic rules in ignore.rules or set to off, and operations whose x-guardrail-ignore covers a rule are excluded from the requests themselves, and listed in the report (dynamicScope.excludedOperations, dynamicScope.disabledRules). Use it for endpoints that must never be called, such as a GET that resets data.

Endpoint patterns in ignore.endpoints:

  • An exact path: /health ignores /health, but not /healthcare-records or /health/live.
  • * matches one segment (/users/* matches /users/{id}), ** matches any number of segments (/internal/** matches /internal and /internal/a/b), ? matches one character.
  • Optional HTTP method prefix: "DELETE /users/*" ignores only the DELETE operation.
  • OpenAPI templates such as {id} are matched literally.

Inline suppression

Exceptions can also live in the spec itself, next to the endpoint they justify, with the x-guardrail-ignore extension. It accepts true (all rules) or a list of rule IDs, at three levels:

x-guardrail-ignore: ["DY-004"]        # document: applies everywhere
paths:
  /health:
    x-guardrail-ignore: true          # path item: every operation of /health
    get:
      responses: { "200": { description: OK } }
  /users/{id}:
    delete:
      x-guardrail-ignore: ["ST-003"]  # operation: only DELETE /users/{id}

Nothing is hidden silently: the report includes a suppressed count by reason (config rule, config endpoint, inline, baseline), and the console prints a summary line.


SARIF and GitHub Code Scanning

The SARIF 2.1.0 report is designed for GitHub Code Scanning:

  • Exact locations. For local specs, each finding points to the line and column of the operation, parameter, request body, server entry, security scheme or example value. Remote specs (URLs) are reported without a line.
  • Stable fingerprints (partialFingerprints), so GitHub tracks, deduplicates and closes alerts across runs.
  • Severity through security-severity: Critical 9.5, High 8.0, Medium 5.5, Low 3.0, Info 1.0.
  • Rule metadata: CWE and OWASP API Top 10 tags (owasp-api-2023/API8), precision and a helpUri pointing to the rule's entry in this README.

Programmatic API

The package also exports the engine, typed for TypeScript:

import { writeFileSync } from 'node:fs';
import { runAudit, determineExitCode, generateSarifReport } from 'guardrail-api';

const report = await runAudit({
  specPathOrUrl: './openapi.yaml',
  staticOnly: true,
});

console.log(report.summary); // { critical, high, medium, low, info, total }
writeFileSync('results.sarif', generateSarifReport(report));
process.exitCode = determineExitCode(report, 'HIGH');

The CLI itself is available as guardrail-api/cli (createCli, runCli). Importing them from the root entry still works but is deprecated and will be removed in 3.0.


Benchmark

A reproducible run against VAmPI, a deliberately vulnerable API (pinned image, both safe and destructive modes): of its 9 documented vulnerabilities, 2 are detected by live probes (BOLA, with two users, and SQL injection, with the leaked SQL error as evidence), 1 is flagged from the contract (the unauthenticated debug endpoint) and 6 are not detected (unauthorized password change, mass assignment, enumeration, ReDoS, rate limiting, weak JWT key). The full table, the false positives found and the command to reproduce it are in benchmark/README.md.


Limitations

Guardrail API is a fast first line of defense, not a replacement for a full DAST scanner (such as OWASP ZAP or Burp Suite) or a penetration test.

  • Static rules can only judge what the spec declares. An incomplete or outdated contract produces incomplete results.
  • Dynamic probes are deliberately light: a few requests per operation, no crawling and no login flows (pass a token with -H).
  • In safe mode, operations that change state are not probed.
  • Authorization between users (BOLA/IDOR) is only tested for readable objects with known IDs and two identities (--auth-b). Rate limiting and business logic flaws are not tested yet.

Command reference

guardrail-api audit [options]

  -s, --spec <pathOrUrl>     OpenAPI/Swagger spec, local path or URL (required)
  -t, --target <url>         Base URL of the running API for dynamic probes
  -c, --config <path>        Config file (default: ./.guardrailrc.json)
      --static-only          Run only static analysis
      --dynamic-only         Run only dynamic probes
      --allow-destructive    Also send POST/PUT/PATCH/DELETE probes
      --fail-on <severity>   critical | high | medium | low | info (default: critical)
  -f, --format <format>      console | json | markdown | html | sarif (default: console)
  -o, --output <path>        Write the report to a file
      --timeout <ms>         Per-request timeout (default: config or 5000)
  -H, --header <k:v...>      Extra HTTP headers for dynamic requests
      --auth-b <k:v...>      Credential headers of a second user, to test BOLA (DY-005)
      --baseline <file>      Only findings not in this baseline count
      --update-baseline      Write current findings to the baseline
  -h, --help                 Show help
  -V, --version              Show version

Contributing

Bug reports, rule ideas and pull requests are welcome. See CONTRIBUTING.md for the development setup and how to add a rule, and SECURITY.md to report a vulnerability privately.

License

MIT