Skip to content
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

yaml
# 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.

FieldTypeDefaultDescription
profileenum—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.
authenticationobject—Auth scheme, JWT algorithm allow/ban lists, MFA, account lockout, password policy.
authorizationobject—RBAC, rule-based (ownership), or ABAC access control. The BOLA defense lives here.
csrfobject—Origin-check, double-submit, or custom-header CSRF defense.
rateLimitobject | array—One or more rate limits, keyed by IP, user-id, API key, fingerprint, or composites.
timeoutobject—Connect / read / write timeouts in milliseconds.
cacheableboolean | object—Response cacheability, TTL, and cache-key variation.
corsobject—Cross-origin policy. The schema rejects allowedOrigins: ["*"] combined with credentials.
mtlsobject—Mutual TLS for inbound connections.
ipPolicyobject—IP allowlist or denylist (mutually exclusive).
requestobject—Request-side hardening: body caps, content-type allowlist, per-field schema, injection guards, webhook signatures, idempotency.
responseobject—Response hardening headers, cookie defaults, error scrubbing, JSON-hijack guard.
loggingobject—Audit/access logging events, sink, and PII redaction (SSEC-AUDIT).
graphqlobject—Depth/complexity/alias/batch limits plus v0.8 per-operation authorization.
websocketobject—WebSocket origin, message size, rate, idle timeout.
botProtectionobject—Turnstile / reCAPTCHA / hCaptcha challenge.
tlsobjectTLSv1.2Inbound TLS floor: minimum version + allowed cipher suites.
outboundCallsarray—Declared outbound calls (webhooks, downstream APIs): signing, response schema, TLS floor.
deprecatedboolean—Marks the endpoint deprecated; pair with sunsetDate and replacementEndpoint.
targetOverridesobject—Vendor-specific escape hatch per gateway target, passed through unchanged.
mitigatesarray—OWASP API Top 10 (2023) IDs this policy addresses: API1:2023 … API10:2023.
/ 03section

authentication

FieldTypeDefaultDescription
typeenum (required)—bearer-jwt · api-key · oauth2 · mtls · basic · custom-token · none
allowedAlgorithmsenum[]—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.
bannedAlgorithmsenum[]—Explicit denial over the full algorithm space (incl. HS256/384/512, none). Cannot overlap allowedAlgorithms.
jwksUriuri | ${VAR}—Required for bearer-jwt. Secrets resolve via ${ENV} or $vault.path. They are never literals.
scopesstring[]—Required for oauth2.
tokenFormatenum—opaque · base64 · jwt; required for custom-token, with validationEndpoint for introspection.
tokenSourcesenum[]["header"]Where tokens may arrive: header · cookie · query.
mfaRequiredboolean—Declares the route requires a second factor.
accountLockoutobject—attempts + window + identifier (e.g. request.body.email) — brute-force lockout.
passwordPolicyobject—minLength ≥ 8, case/digit/symbol requirements, blocklist.
sessionRotateOnAuthbooleanfalseRotate session identifier on privilege change (fixation defense).
yaml
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.

FieldTypeDefaultDescription
typeenum (required)—rbac · rule-based · abac
rolesstring[]—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.refRuleRef—Caller-identity reference compared against the resource: namespaces jwt.*, principal.*, session.*, header.*, request.*, resource.*. resource.ownerId equals jwt.sub is the canonical BOLA rule.
resourceLookupobject—How the gateway fetches the owning resource: endpoint + identifierFrom + expose fields. Makes ownership checks enforceable at the perimeter.
yaml
# 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

FieldTypeDefaultDescription
methodenum (required)—origin-check · double-submit · custom-header. Pick exactly one.
allowedOriginsstring[]—Required for origin-check.
tokenHeaderstring—Required for double-submit and custom-header.
tokenCookiestring—Required for double-submit — the cookie the header must match.
yaml
# 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

FieldTypeDefaultDescription
requests / windowint / Duration (required)—e.g. 60 per "60s".
identifierstring | string[] | objectipBucket key: ip, user-id, api-key, fingerprint, header:X-Custom — or a composite with combinator concat / distinct / min-of.
burstint—Burst allowance above the steady rate.
whenenum—Conditional limits: authenticated vs unauthenticated traffic.
yaml
# 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

FieldTypeDefaultDescription
maxBodySizeByteSize—e.g. "1MB" (body cap).
contentTypestring[]—Content-type allowlist.
schemamap<field, ParamSchema>—Per-field validation. See ParamSchema below.
denyUnknownFieldsbooleanfalseReject fields not in the schema (mass-assignment defense).
allowedFieldsstring[]—Allowlist shorthand; cannot coexist with denyUnknownFields: false.
denyFieldsstring[]—Denylist of privileged fields (e.g. role, isAdmin) — API6 mass-assignment.
allowedMethodsenum[]—HTTP method allowlist for the path.
disableExternalEntitiesbooleanfalseXXE defense for XML bodies.
signatureobject—Webhook verification: hmac-sha256 / hmac-sha1 / ed25519, secret via secretRef, optional timestamp tolerance and nonce-cache replay defense.
idempotencyKeyobject—header + ttl dedupe window, a replay defense. Edge-level; does not replace in-handler transactionality.
serializeByobject—Serialize in-flight requests per key (e.g. jwt.sub) with optional concurrencyLimit — race-window narrowing, partial by design.
duplicateParamPolicyenumrejectHTTP parameter pollution: first · last · reject.
headerInjectionGuardbooleanfalseCR/LF/NUL header-injection guard.
pathCanonicalizationbooleanfalseNormalize traversal sequences before route match.
allowedHostsstring[]—Host-header allowlist.
dataAtRestobject—Declares storage posture (encrypted / hashed / tokenized) per field. Advisory-only: compiles to nothing, drives scan findings.
yaml
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.

FieldTypeDefaultDescription
typeSemanticType—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 / patternnumber | regex—Range, length, and pattern constraints.
injectionGuardenum[]—Per-argument sink declaration: sql · nosql · os-command · xpath · ldap · code-eval · xss · deserialization · ai-prompt. Explicit per-arg, replacing string-type heuristics.
blockPrivateRangesboolean—SSRF guard for url fields: rejects RFC1918, loopback, link-local, ULA, non-HTTP(S).
redirectAllowedDomainsstring[]—Open-redirect defense; glob patterns allowed.
domainAllowliststring[]—Domain whitelist for email/url types.
allowedMimeTypes / maxSize / magicByteCheck / extensionAllowlist / denyDoubleExtensionupload guards—File-upload hardening, incl. magic-byte verification and *.pdf.exe rejection.
piiboolean—Marks the field sensitive; drives log redaction.

Webhook signatures, replay & race defenses, at-rest posture

FieldTypeDefaultDescription
signature.algorithmenum (required)—hmac-sha256 · hmac-sha1 · ed25519.
signature.headerName / secretRef / bodyrequired—Signature header, secret VarRef, and whether the raw or canonical body is signed.
signature.timestampHeader + timestampToleranceSecondsoptional pair—Reject stale signatures (1–3600s window).
signature.nonceHeader + nonceCacheTtloptional pair—Replay dedupe; the ttl requires the header.
idempotencyKeyobject—header + ttl, both required. Edge-level dedupe; not in-handler atomicity.
serializeByobject—key (RuleRef-style, required) + scope (global | per-identifier). Pair with concurrencyLimit.
dataAtRestobject—fields[] + protection (encrypted | hashed | tokenized). Advisory-only: compiles to nothing on every target.
yaml
# 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

FieldTypeDefaultDescription
headersobject—Hardening headers: csp, hsts, frameOptions, contentTypeOptions, referrerPolicy, permissionsPolicy, coop / coep / corp, cacheControl.
cookies.defaultsobject—Defaults applied to every Set-Cookie.
errorScrubbingobject—stripStackTraces, stripServerHeaders, genericMessages, per-status body overrides.
forbidArrayRootbooleanfalseRejects array-rooted JSON responses (JSON-hijacking, API3).
schema / stripUnknownFields / contentTypemixed—Response-side field validation and content-type allowlist.
yaml
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

FieldTypeDefaultDescription
cors.allowedOriginsstring[]—Origin allowlist. The schema rejects ["*"] combined with credentials: true.
cors.allowedMethods / allowedHeaders / exposeHeadersstring[]—Method and header allowlists, plus headers exposed to the browser.
cors.maxAgeinteger—Preflight cache seconds.
cors.credentialsbooleanfalseAllow cookies/authorization on cross-origin calls.
timeoutobject—connect / read / write, all in milliseconds.
cacheableboolean | object—Shorthand boolean, or { enabled, ttl, varyBy[], unkeyedHeadersStrip[] } — the strip list is cache-poisoning hygiene.
mtlsobject—enabled (required) + clientCertRef (VarRef to the CA bundle) + pinnedCertificates[].
ipPolicyobject—allow or deny list of CIDRs (IPv4/IPv6), mutually exclusive.
tlsobjectTLSv1.2minVersion (TLSv1.2 | TLSv1.3) + allowedCipherSuites[], the inbound floor.
yaml
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

FieldTypeDefaultDescription
eventsenum[] (required)—auth-failure · auth-success · authz-deny · rate-limit-trip · injection-block · request · response — at least one.
sinkenumstdoutstdout · file · syslog · http-collector.
sinkRefVarRef—Collector URL — required when sink is http-collector.
piiRedactionbooleanfalseMasks fields marked pii: true in logged payloads.
yaml
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

FieldTypeDefaultDescription
maxDepth / maxComplexity / maxAliases / batchLimitinteger—Block-level static limits — the API4 resource-consumption defense.
disableIntrospectionboolean—Reject __schema / __type queries in production.
allowedOperationsenum[]—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).
yaml
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

FieldTypeDefaultDescription
websocket.allowedOriginsstring[] (required)—Origin allowlist for the upgrade handshake.
websocket.maxMessageSizeByteSize—Per-frame cap.
websocket.messageRateLimitobject—{ messages, window } — both required.
websocket.maxConnectionsPerIdentifierinteger—Concurrent-connection cap per caller.
websocket.idleTimeoutDuration—Drop idle connections.
botProtection.providerenum (required)—turnstile · recaptcha · hcaptcha.
botProtection.secretRefVarRef (required)—Provider secret, by reference.
botProtection.thresholdnumber0.5Score cutoff for challenge/deny.
botProtection.modeenum (required)—observe first, enforce when calibrated.
yaml
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

FieldTypeDefaultDescription
endpointuri (required)—The downstream URL this route is declared to call.
signatureAlgorithm + secretRefenum + VarRef—hmac-sha256 · hmac-sha512 · ed25519 · none; secret required unless none.
responseSchemaobject—OpenAPI 3.0 fragment the downstream reply must validate against (API10).
timeoutMs / allowedTlsVersions / timestampToleranceSecondsmixed—Call budget, TLS floor for the outbound leg, signature freshness.
yaml
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

FieldTypeDefaultDescription
deprecatedboolean—Marks the endpoint deprecated (API9 inventory hygiene).
sunsetDatedate—ISO 8601 — when it stops being served.
replacementEndpointstring—Where callers should migrate.
targetOverridesobject—Per-gateway escape hatch — keys kong, kong-enterprise, coraza, bunkerweb, openappsec, cloudflare, aws-apigw (and firewall, reserved). Passed through unchanged.
mitigatesOwaspId[]—API1:2023 … API10:2023, declared coverage, consumed by xsecurity report --owasp.
yaml
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

FieldTypeDefaultDescription
Durationpattern—\d+(ms|s|m|h|d) — "30s", "5m", "1d"
ByteSizepattern—\d+(B|KB|MB|GB) — "1MB", "50MB"
VarRefpattern—${ENV_VAR} or $vault.path. Secrets are referenced, never inlined.
OwaspIdpattern—API1:2023 … API10:2023
SsecIdpattern—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.