Docs›Schema›x-security schema reference v0.8.0 · Apache-2.0 · JSON Schema
x-security schema reference
One block per route, in the OpenAPI file you already have. Every top-level key, every sub-object fully fielded, every section with a validating YAML example. The spec, JSON Schema, and examples live in the open repo (Apache-2.0): Spec source ↗
/ 01section
A complete policy in one screen
# GET /users/{id} — one route, one policy, in your OpenAPI file
x-security:
profile: standard-crud
authentication:
type: bearer-jwt
allowedAlgorithms: [RS256, ES256] # alg:none not expressible
jwksUri: ${JWKS_URL} # secrets by reference only
authorization:
type: rule-based
rules:
- field: resource.ownerId
operator: equals
value: { ref: jwt.sub } # the BOLA rule
rateLimit:
requests: 60
window: 60s
identifier: user-id # not IP
request:
maxBodySize: 1MB
denyUnknownFields: true
schema:
id: { type: uuid }
response:
headers:
hsts: { maxAge: 31536000 }
contentTypeOptions: nosniff
errorScrubbing: { stripStackTraces: true }
mitigates: [API1:2023, API4:2023, API8:2023]
Design rule
The schema makes entire bug classes inexpressible rather than discouraged: symmetric JWT algorithms and alg:none have no spelling in allowedAlgorithms, wildcard CORS with credentials fails validation, and secrets only exist as ${ENV} / $vault references.
/ 02section
Top-level keys
Everything is optional. A policy describes only what the route needs, and profile supplies the defaults the block deltas against.
| Field | Type | Default | Description |
|---|
profile | enum | — | Security preset the rest of the block deltas against: auth-endpoint, standard-crud, file-upload, webhook-receiver, public-read-only, admin-panel, server-rendered-page, graphql-resolver, grpc-method, internal-rpc, static-asset, unknown. |
authentication | object | — | Auth scheme, JWT algorithm allow/ban lists, MFA, account lockout, password policy. |
authorization | object | — | RBAC, rule-based (ownership), or ABAC access control. The BOLA defense lives here. |
csrf | object | — | Origin-check, double-submit, or custom-header CSRF defense. |
rateLimit | object | array | — | One or more rate limits, keyed by IP, user-id, API key, fingerprint, or composites. |
timeout | object | — | Connect / read / write timeouts in milliseconds. |
cacheable | boolean | object | — | Response cacheability, TTL, and cache-key variation. |
cors | object | — | Cross-origin policy. The schema rejects allowedOrigins: ["*"] combined with credentials. |
mtls | object | — | Mutual TLS for inbound connections. |
ipPolicy | object | — | IP allowlist or denylist (mutually exclusive). |
request | object | — | Request-side hardening: body caps, content-type allowlist, per-field schema, injection guards, webhook signatures, idempotency. |
response | object | — | Response hardening headers, cookie defaults, error scrubbing, JSON-hijack guard. |
logging | object | — | Audit/access logging events, sink, and PII redaction (SSEC-AUDIT). |
graphql | object | — | Depth/complexity/alias/batch limits plus v0.8 per-operation authorization. |
websocket | object | — | WebSocket origin, message size, rate, idle timeout. |
botProtection | object | — | Turnstile / reCAPTCHA / hCaptcha challenge. |
tls | object | TLSv1.2 | Inbound TLS floor: minimum version + allowed cipher suites. |
outboundCalls | array | — | Declared outbound calls (webhooks, downstream APIs): signing, response schema, TLS floor. |
deprecated | boolean | — | Marks the endpoint deprecated; pair with sunsetDate and replacementEndpoint. |
targetOverrides | object | — | Vendor-specific escape hatch per gateway target, passed through unchanged. |
mitigates | array | — | OWASP API Top 10 (2023) IDs this policy addresses: API1:2023 … API10:2023. |
/ 03section
authentication
| Field | Type | Default | Description |
|---|
type | enum (required) | — | bearer-jwt · api-key · oauth2 · mtls · basic · custom-token · none |
allowedAlgorithms | enum[] | — | Required for bearer-jwt. Asymmetric only: RS256/384/512, ES256/384/512, PS256/384/512, EdDSA. Symmetric and none are not expressible here — that kills the alg-confusion class by construction. |
bannedAlgorithms | enum[] | — | Explicit denial over the full algorithm space (incl. HS256/384/512, none). Cannot overlap allowedAlgorithms. |
jwksUri | uri | ${VAR} | — | Required for bearer-jwt. Secrets resolve via ${ENV} or $vault.path. They are never literals. |
scopes | string[] | — | Required for oauth2. |
tokenFormat | enum | — | opaque · base64 · jwt; required for custom-token, with validationEndpoint for introspection. |
tokenSources | enum[] | ["header"] | Where tokens may arrive: header · cookie · query. |
mfaRequired | boolean | — | Declares the route requires a second factor. |
accountLockout | object | — | attempts + window + identifier (e.g. request.body.email) — brute-force lockout. |
passwordPolicy | object | — | minLength ≥ 8, case/digit/symbol requirements, blocklist. |
sessionRotateOnAuth | boolean | false | Rotate session identifier on privilege change (fixation defense). |
authentication:
type: bearer-jwt
jwksUri: ${JWKS_URL} # secrets by reference, never literals
issuer: https://auth.example.com
audience: https://api.example.com
allowedAlgorithms: [RS256, ES256] # asymmetric only — alg:none has no spelling
bannedAlgorithms: [HS256, HS384, HS512, none]
tokenSources: [header] # header | cookie | query
mfaRequired: true
accountLockout:
attempts: 5
window: 15m
identifier: request.body.email # what to count failures against
passwordPolicy:
minLength: 12
requireUppercase: true
requireDigit: true
requireSymbol: true
blocklist: [password123, letmein]
sessionRotateOnAuth: true # fixation defense
# custom-token variant — opaque tokens validated by introspection
authentication:
type: custom-token
tokenFormat: opaque
headerName: X-Session-Token
validationEndpoint: https://auth.internal/introspect
/ 04section
authorization
Ownership is first-class: a rule compares a resource field against a caller-identity reference, and resourceLookup tells the gateway how to fetch the resource — which is what makes BOLA enforceable at the perimeter instead of a code-review comment.
| Field | Type | Default | Description |
|---|
type | enum (required) | — | rbac · rule-based · abac |
roles | string[] | — | Required for rbac. |
rules[] | object[] | — | Required for rule-based. Each rule: field + operator (equals, not-equals, in, not-in, matches, contains) + value — literal or reference. |
rules[].value.ref | RuleRef | — | Caller-identity reference compared against the resource: namespaces jwt.*, principal.*, session.*, header.*, request.*, resource.*. resource.ownerId equals jwt.sub is the canonical BOLA rule. |
resourceLookup | object | — | How the gateway fetches the owning resource: endpoint + identifierFrom + expose fields. Makes ownership checks enforceable at the perimeter. |
# rule-based — the BOLA defense
authorization:
type: rule-based
rules:
- field: resource.ownerId # field on the looked-up resource
operator: equals # equals | not-equals | in | not-in | matches | contains
value: { ref: jwt.sub } # caller identity reference
resourceLookup:
endpoint: /documents/{id} # how the gateway fetches the resource
identifierFrom: request.params.id # where the id lives in this request
expose: [ownerId] # fields the rules may read
mitigates: [API1:2023]
# rbac variant
authorization:
type: rbac
roles: [admin, editor]
# abac variant
authorization:
type: abac
attributes:
department: { ref: jwt.dept }
clearance: secret
/ 05section
csrf
| Field | Type | Default | Description |
|---|
method | enum (required) | — | origin-check · double-submit · custom-header. Pick exactly one. |
allowedOrigins | string[] | — | Required for origin-check. |
tokenHeader | string | — | Required for double-submit and custom-header. |
tokenCookie | string | — | Required for double-submit — the cookie the header must match. |
# pick exactly one method
csrf:
method: origin-check
allowedOrigins: [https://app.example.com]
csrf:
method: double-submit
tokenHeader: X-CSRF-Token
tokenCookie: csrf_token
csrf:
method: custom-header
tokenHeader: X-Requested-With
/ 06section
rateLimit
| Field | Type | Default | Description |
|---|
requests / window | int / Duration (required) | — | e.g. 60 per "60s". |
identifier | string | string[] | object | ip | Bucket key: ip, user-id, api-key, fingerprint, header:X-Custom — or a composite with combinator concat / distinct / min-of. |
burst | int | — | Burst allowance above the steady rate. |
when | enum | — | Conditional limits: authenticated vs unauthenticated traffic. |
# single limit
rateLimit:
requests: 60
window: 60s
identifier: user-id # ip | user-id | api-key | fingerprint | header:X-...
burst: 10
# array form — different budgets for different callers
rateLimit:
- requests: 120
window: 60s
identifier: user-id
when: authenticated
- requests: 5
window: 1m
when: unauthenticated
identifier: # composite identifier
components: [ip, fingerprint]
combinator: distinct # concat | distinct | min-of
/ 07section
request
| Field | Type | Default | Description |
|---|
maxBodySize | ByteSize | — | e.g. "1MB" (body cap). |
contentType | string[] | — | Content-type allowlist. |
schema | map<field, ParamSchema> | — | Per-field validation. See ParamSchema below. |
denyUnknownFields | boolean | false | Reject fields not in the schema (mass-assignment defense). |
allowedFields | string[] | — | Allowlist shorthand; cannot coexist with denyUnknownFields: false. |
denyFields | string[] | — | Denylist of privileged fields (e.g. role, isAdmin) — API6 mass-assignment. |
allowedMethods | enum[] | — | HTTP method allowlist for the path. |
disableExternalEntities | boolean | false | XXE defense for XML bodies. |
signature | object | — | Webhook verification: hmac-sha256 / hmac-sha1 / ed25519, secret via secretRef, optional timestamp tolerance and nonce-cache replay defense. |
idempotencyKey | object | — | header + ttl dedupe window, a replay defense. Edge-level; does not replace in-handler transactionality. |
serializeBy | object | — | Serialize in-flight requests per key (e.g. jwt.sub) with optional concurrencyLimit — race-window narrowing, partial by design. |
duplicateParamPolicy | enum | reject | HTTP parameter pollution: first · last · reject. |
headerInjectionGuard | boolean | false | CR/LF/NUL header-injection guard. |
pathCanonicalization | boolean | false | Normalize traversal sequences before route match. |
allowedHosts | string[] | — | Host-header allowlist. |
dataAtRest | object | — | Declares storage posture (encrypted / hashed / tokenized) per field. Advisory-only: compiles to nothing, drives scan findings. |
request:
contentType: [application/json] # allowlist — everything else is 415
maxBodySize: 1MB
allowedMethods: [GET, POST]
denyUnknownFields: true # mass-assignment guard
denyFields: [role, isAdmin] # privileged fields, always rejected
duplicateParamPolicy: reject # HTTP parameter pollution
headerInjectionGuard: true # CR/LF/NUL in header values
pathCanonicalization: true # normalize ../ before route match
allowedHosts: [api.example.com] # Host-header allowlist
disableExternalEntities: true # XXE, if XML is accepted at all
schema: # per-field ParamSchema — see below
email:
type: email
maxLength: 254
pii: true # drives log redaction
comment:
type: free-text
maxLength: 4000
injectionGuard: [xss, sql] # per-arg sink declaration
webhookUrl:
type: url
blockPrivateRanges: true # SSRF: RFC1918, loopback, link-local
domainAllowlist: ["*.example.com"]
avatar:
type: binary
maxSize: 5MB
allowedMimeTypes: [image/png, image/jpeg]
extensionAllowlist: [.png, .jpg]
magicByteCheck: true # MIME must match magic bytes
denyDoubleExtension: true # rejects avatar.pdf.exe
ParamSchema — per-field validation
Used by request.schema and response.schema, one entry per field. The email, webhookUrl, and avatar fields in the example above are ParamSchemas.
| Field | Type | Default | Description |
|---|
type | SemanticType | — | string · integer · float · boolean · email · phone · url · date · datetime · uuid · ip-address · name · free-text · binary. Semantic, not just primitive — email validates shape, not "is a string". |
min / max / minLength / maxLength / fixedLength / pattern | number | regex | — | Range, length, and pattern constraints. |
injectionGuard | enum[] | — | Per-argument sink declaration: sql · nosql · os-command · xpath · ldap · code-eval · xss · deserialization · ai-prompt. Explicit per-arg, replacing string-type heuristics. |
blockPrivateRanges | boolean | — | SSRF guard for url fields: rejects RFC1918, loopback, link-local, ULA, non-HTTP(S). |
redirectAllowedDomains | string[] | — | Open-redirect defense; glob patterns allowed. |
domainAllowlist | string[] | — | Domain whitelist for email/url types. |
allowedMimeTypes / maxSize / magicByteCheck / extensionAllowlist / denyDoubleExtension | upload guards | — | File-upload hardening, incl. magic-byte verification and *.pdf.exe rejection. |
pii | boolean | — | Marks the field sensitive; drives log redaction. |
Webhook signatures, replay & race defenses, at-rest posture
| Field | Type | Default | Description |
|---|
signature.algorithm | enum (required) | — | hmac-sha256 · hmac-sha1 · ed25519. |
signature.headerName / secretRef / body | required | — | Signature header, secret VarRef, and whether the raw or canonical body is signed. |
signature.timestampHeader + timestampToleranceSeconds | optional pair | — | Reject stale signatures (1–3600s window). |
signature.nonceHeader + nonceCacheTtl | optional pair | — | Replay dedupe; the ttl requires the header. |
idempotencyKey | object | — | header + ttl, both required. Edge-level dedupe; not in-handler atomicity. |
serializeBy | object | — | key (RuleRef-style, required) + scope (global | per-identifier). Pair with concurrencyLimit. |
dataAtRest | object | — | fields[] + protection (encrypted | hashed | tokenized). Advisory-only: compiles to nothing on every target. |
# webhook receiver — verify before any state read
request:
signature:
algorithm: hmac-sha256 # hmac-sha256 | hmac-sha1 | ed25519
headerName: X-Hub-Signature-256
secretRef: ${WEBHOOK_SECRET}
body: raw # raw | canonical
timestampHeader: X-Timestamp
timestampToleranceSeconds: 300
nonceHeader: X-Nonce # replay defense
nonceCacheTtl: 10m
# replay + race-window defenses (API6)
request:
idempotencyKey:
header: Idempotency-Key
ttl: 5m # dedupe window at the edge
serializeBy:
key: request.body.account_id # one in-flight request per key
scope: per-identifier # global | per-identifier
concurrencyLimit: 1
# at-rest posture — ADVISORY ONLY: compiles to nothing, drives scan findings
request:
dataAtRest:
fields: [ssn, cardNumber]
protection: encrypted # encrypted | hashed | tokenized
/ 08section
response
| Field | Type | Default | Description |
|---|
headers | object | — | Hardening headers: csp, hsts, frameOptions, contentTypeOptions, referrerPolicy, permissionsPolicy, coop / coep / corp, cacheControl. |
cookies.defaults | object | — | Defaults applied to every Set-Cookie. |
errorScrubbing | object | — | stripStackTraces, stripServerHeaders, genericMessages, per-status body overrides. |
forbidArrayRoot | boolean | false | Rejects array-rooted JSON responses (JSON-hijacking, API3). |
schema / stripUnknownFields / contentType | mixed | — | Response-side field validation and content-type allowlist. |
response:
contentType: [application/json]
forbidArrayRoot: true # JSON-hijacking (API3)
stripUnknownFields: true
schema:
ssn: { type: string, pii: true } # redact on egress
headers:
csp: "default-src 'self'"
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true }
frameOptions: DENY # DENY | SAMEORIGIN
contentTypeOptions: nosniff
referrerPolicy: strict-origin-when-cross-origin
permissionsPolicy: "camera=(), geolocation=()"
coop: same-origin
coep: require-corp
corp: same-origin
cacheControl: "no-store"
cookies:
defaults: # applied to every Set-Cookie
httpOnly: true
secure: true
sameSite: Strict # Strict | Lax | None
path: /
maxAge: 3600
errorScrubbing:
stripStackTraces: true
stripServerHeaders: true
genericMessages: true
statusOverride:
"5xx": "Something went wrong."
/ 09section
cors · timeout · cacheable · mtls · ipPolicy · tls
| Field | Type | Default | Description |
|---|
cors.allowedOrigins | string[] | — | Origin allowlist. The schema rejects ["*"] combined with credentials: true. |
cors.allowedMethods / allowedHeaders / exposeHeaders | string[] | — | Method and header allowlists, plus headers exposed to the browser. |
cors.maxAge | integer | — | Preflight cache seconds. |
cors.credentials | boolean | false | Allow cookies/authorization on cross-origin calls. |
timeout | object | — | connect / read / write, all in milliseconds. |
cacheable | boolean | object | — | Shorthand boolean, or { enabled, ttl, varyBy[], unkeyedHeadersStrip[] } — the strip list is cache-poisoning hygiene. |
mtls | object | — | enabled (required) + clientCertRef (VarRef to the CA bundle) + pinnedCertificates[]. |
ipPolicy | object | — | allow or deny list of CIDRs (IPv4/IPv6), mutually exclusive. |
tls | object | TLSv1.2 | minVersion (TLSv1.2 | TLSv1.3) + allowedCipherSuites[], the inbound floor. |
cors:
allowedOrigins: [https://app.example.com] # "*" + credentials fails validation
allowedMethods: [GET, POST]
allowedHeaders: [Authorization, Content-Type]
exposeHeaders: [X-Request-Id]
maxAge: 600
credentials: true
timeout: # milliseconds
connect: 2000
read: 10000
write: 10000
cacheable: # boolean shorthand, or:
enabled: true
ttl: 300
varyBy: [Accept-Language] # cache-key variation
unkeyedHeadersStrip: [X-Debug] # cache-poisoning hygiene
mtls:
enabled: true
clientCertRef: ${CLIENT_CA_BUNDLE}
pinnedCertificates: ["sha256/AAAA..."]
ipPolicy: # allow and deny are mutually exclusive
deny: [203.0.113.0/24, "2001:db8::/32"]
tls:
minVersion: TLSv1.3 # TLSv1.2 | TLSv1.3
allowedCipherSuites: [TLS_AES_256_GCM_SHA384]
/ 10section
logging
| Field | Type | Default | Description |
|---|
events | enum[] (required) | — | auth-failure · auth-success · authz-deny · rate-limit-trip · injection-block · request · response — at least one. |
sink | enum | stdout | stdout · file · syslog · http-collector. |
sinkRef | VarRef | — | Collector URL — required when sink is http-collector. |
piiRedaction | boolean | false | Masks fields marked pii: true in logged payloads. |
logging:
events: [auth-failure, authz-deny, rate-limit-trip, injection-block]
sink: http-collector # stdout | file | syslog | http-collector
sinkRef: ${AUDIT_COLLECTOR_URL} # required for http-collector
piiRedaction: true # fields marked pii: true are masked
/ 11section
graphql
| Field | Type | Default | Description |
|---|
maxDepth / maxComplexity / maxAliases / batchLimit | integer | — | Block-level static limits — the API4 resource-consumption defense. |
disableIntrospection | boolean | — | Reject __schema / __type queries in production. |
allowedOperations | enum[] | — | query · mutation · subscription. |
operations[] | object[] | — | v0.8 per-operation overrides: name (required), operationType, per-op maxDepth/maxComplexity/maxAliases, and a full per-resolver authz block (BOLA/BFLA at the resolver — override-only on every target). |
graphql:
maxDepth: 10 # block-level static limits (API4)
maxComplexity: 2000
maxAliases: 15
batchLimit: 5
disableIntrospection: true
allowedOperations: [query, mutation]
operations: # v0.8 — per-operation overrides
- name: deleteUser
operationType: mutation
authz: # per-resolver BOLA/BFLA (override-only)
type: rule-based
rules:
- field: resource.ownerId
operator: equals
value: { ref: jwt.sub }
- name: searchPosts
operationType: query
maxDepth: 6
maxComplexity: 500
/ 12section
websocket · botProtection
| Field | Type | Default | Description |
|---|
websocket.allowedOrigins | string[] (required) | — | Origin allowlist for the upgrade handshake. |
websocket.maxMessageSize | ByteSize | — | Per-frame cap. |
websocket.messageRateLimit | object | — | { messages, window } — both required. |
websocket.maxConnectionsPerIdentifier | integer | — | Concurrent-connection cap per caller. |
websocket.idleTimeout | Duration | — | Drop idle connections. |
botProtection.provider | enum (required) | — | turnstile · recaptcha · hcaptcha. |
botProtection.secretRef | VarRef (required) | — | Provider secret, by reference. |
botProtection.threshold | number | 0.5 | Score cutoff for challenge/deny. |
botProtection.mode | enum (required) | — | observe first, enforce when calibrated. |
websocket:
allowedOrigins: [https://app.example.com]
maxMessageSize: 64KB
messageRateLimit: { messages: 20, window: 10s }
maxConnectionsPerIdentifier: 3
idleTimeout: 5m
botProtection:
provider: turnstile # turnstile | recaptcha | hcaptcha
secretRef: ${TURNSTILE_SECRET}
threshold: 0.5
mode: observe # observe first, enforce later
/ 13section
outboundCalls
| Field | Type | Default | Description |
|---|
endpoint | uri (required) | — | The downstream URL this route is declared to call. |
signatureAlgorithm + secretRef | enum + VarRef | — | hmac-sha256 · hmac-sha512 · ed25519 · none; secret required unless none. |
responseSchema | object | — | OpenAPI 3.0 fragment the downstream reply must validate against (API10). |
timeoutMs / allowedTlsVersions / timestampToleranceSeconds | mixed | — | Call budget, TLS floor for the outbound leg, signature freshness. |
outboundCalls: # declared downstream trust (API10)
- endpoint: https://hooks.partner.com/notify
signatureAlgorithm: hmac-sha256 # sign what you send
secretRef: ${PARTNER_WEBHOOK_KEY}
timestampToleranceSeconds: 300
timeoutMs: 5000
allowedTlsVersions: [TLSv1.3]
responseSchema: # OpenAPI 3.0 fragment — validate replies
type: object
required: [status]
properties:
status: { type: string }
/ 14section
Lifecycle, overrides & OWASP mapping
| Field | Type | Default | Description |
|---|
deprecated | boolean | — | Marks the endpoint deprecated (API9 inventory hygiene). |
sunsetDate | date | — | ISO 8601 — when it stops being served. |
replacementEndpoint | string | — | Where callers should migrate. |
targetOverrides | object | — | Per-gateway escape hatch — keys kong, kong-enterprise, coraza, bunkerweb, openappsec, cloudflare, aws-apigw (and firewall, reserved). Passed through unchanged. |
mitigates | OwaspId[] | — | API1:2023 … API10:2023, declared coverage, consumed by xsecurity report --owasp. |
deprecated: true
sunsetDate: "2026-12-31"
replacementEndpoint: /v2/users/{id}
targetOverrides: # per-gateway escape hatch, passed through
kong:
plugins:
- name: request-transformer
cloudflare:
phaseOverride: http_request_firewall_custom
mitigates: [API1:2023, API4:2023] # what this policy addresses, for reports
/ 15section
Type aliases
| Field | Type | Default | Description |
|---|
Duration | pattern | — | \d+(ms|s|m|h|d) — "30s", "5m", "1d" |
ByteSize | pattern | — | \d+(B|KB|MB|GB) — "1MB", "50MB" |
VarRef | pattern | — | ${ENV_VAR} or $vault.path. Secrets are referenced, never inlined. |
OwaspId | pattern | — | API1:2023 … API10:2023 |
SsecId | pattern | — | x-security-native categories: SSEC-INJECTION, SSEC-PROMPT, SSEC-AUDIT, SSEC-STORAGE. |
/ 16section
Honesty markers
Some declarations are deliberately weaker than they look, and the schema says so instead of overclaiming. request.dataAtRest is advisory-only — it compiles to nothing on every target and exists to document posture and drive scan findings. idempotencyKey and serializeBy are edge-level race-window narrowing, not in-handler transactional atomicity. Per-operation GraphQL authorization is override-only everywhere; it requires an operator-supplied GraphQL processor. The xsecurity report --coverage output names these limits per target rather than rounding up.
Versioning
Current version 0.8.0. Policies migrate forward with xsecurity migrate --from 0.4 --to 0.5-style commands; the schema is additive across minor versions.