Skip to content

Latest commit

 

History

History
532 lines (415 loc) · 23.4 KB

security.md

File metadata and controls

532 lines (415 loc) · 23.4 KB

Security

CAPI supports two complementary authorization mechanisms: OAuth2/OIDC for token validation and OPA (Open Policy Agent) for fine-grained policy decisions. Both can be used independently or together.

Authorization rules

The REST, WebSocket and gRPC listeners share one authorization gate, so a service is protected the same way whichever listener reaches it. (WebDAV has its own; see WebDAV Gateway.) The gate answers two questions.

1. Does this call need authorizing?

secured OpenAPI spec (open-api) opa-rego Which calls
true any any Every call. The spec's security requirements are ignored.
false none none None — anonymous.
false none set Every call. A policy is never dropped because secured was left false.
false declared any Only the operations the spec protects; the others are anonymous.

An operation is protected when it has a security requirement — its own or, when it declares none, the spec's global security. security: [] on an operation, or a requirement list containing an empty object {} (OpenAPI's "authentication optional"), makes it anonymous. A path or method the spec does not declare is refused with 400. A service whose declared spec is not loaded is refused with 503 rather than treated as having no spec.

2. Is this caller allowed?

  1. A token must be present and verify — signature and expiry, against oauth2.keys. Otherwise 401.
  2. Every rule the service declares must pass:
    • subscription-group — the token's subscriptions claim must contain the group. Realm roles (realm_access.roles) are not consulted.
    • opa-rego — the policy must allow the call. OPA disabled, or a policy the bundle does not declare, is a refusal; a bundle not loaded yet is 503 with Retry-After: 1. An OPA policy never falls through to a weaker check.
  3. A service declaring neither subscription-group nor opa-rego refuses every protected call with 403, even with a valid token: there is nothing to authorize the caller against.

A refused caller gets 403. On the gRPC listener the same outcomes are grpc-status 16 (UNAUTHENTICATED), 7 (PERMISSION_DENIED) and 14 (UNAVAILABLE).

API keys. On a service with apiKey enabled, a valid key stands in for the token when the service is secured and declares no opa-rego. It never satisfies a policy (there are no claims to evaluate), nor an operation the spec protects on a service that is not secured.

Changed in 2.25.1. See the release notes: a secured service with neither group nor policy now refuses every call; realm roles no longer count as group membership; a missing or invalid token is 401 (it was 403 on the subscription and OPA checks); and the WebSocket and gRPC listeners now enforce opa-rego.

OAuth2 / OIDC

When a call needs authorizing (see Authorization rules), CAPI validates the Bearer token before proxying to the backend.

Configuration

capi:
  oauth2:
    enabled: true
    cookieName: ""
    keys:
      - http://keycloak:8080/realms/capi/protocol/openid-connect/certs
      - http://auth0.example.com/.well-known/jwks.json
Field Description
enabled Enable OAuth2 token validation globally.
cookieName Optional. When set, CAPI also looks for the token in a cookie with this name (useful for browser-based clients).
keys List of JWKS (JSON Web Key Set) endpoints. CAPI fetches public keys from each endpoint at startup and uses them to verify JWT signatures. Multiple providers are supported.

How It Works

  1. Client sends a request with Authorization: Bearer <token> header
  2. CAPI validates the JWT signature against the configured JWKS endpoints
  3. CAPI checks token expiration
  4. If missing or invalid, CAPI returns 401 Unauthorized
  5. If valid, the service's subscription-group and opa-rego are checked; a refusal is 403 Forbidden

Token Sources

CAPI looks for tokens in this order:

  1. Authorization: Bearer <token> header
  2. access_token query parameter — unless oauth2.allowQueryParameterToken: false
  3. Cookie (if cookieName is configured)

A token in a URL ends up in access logs, browser history and Referer headers along the way. CAPI now strips access_token from the query string before forwarding, so it no longer reaches the backend's own logs — CAPI has already re-emitted it as Authorization: Bearer …. Set oauth2.allowQueryParameterToken: false to stop accepting it entirely; capi_query_token_requests_total{service} tells you who still relies on it first.

An access_token request header was also honoured until 2026-09-29. It was never a documented source and is no longer accepted.

Example

# Get a token from your OIDC provider
TOKEN=$(curl -s -X POST http://keycloak:8080/realms/capi/protocol/openid-connect/token \
  -d "grant_type=client_credentials" \
  -d "client_id=my-client" \
  -d "client_secret=my-secret" | jq -r .access_token)

# Call a secured service through CAPI
curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:8380/api/order-service/v1/orders

OPA (Open Policy Agent)

OPA provides fine-grained, policy-based authorization. CAPI sends request context to OPA, which evaluates a Rego policy and returns an allow/deny decision.

Configuration

capi:
  opa:
    enabled: true
    wasmBundleUrl: http://opa-bundle-server/bundle.tar.gz
    wasmBundleToken:               # optional; sent as Authorization: Bearer <token>
    wasmBundlePollIntervalSeconds: 60
    wasmPoolSize: 10
Field Default Description
enabled false Enable OPA authorization globally.
wasmBundleUrl — URL of the .tar.gz Wasm bundle. Re-fetched on ETag change.
wasmBundleToken — Optional bearer token for the bundle server.
wasmBundlePollIntervalSeconds 60 How often the bundle is polled.
wasmPoolSize 10 Size of the shared policy-instance pool.

There is no endpoint key and no HTTP OPA mode. Earlier revisions of this page documented opa.endpoint: http://opa:8181 and an "OPA HTTP fallback". Neither exists: CAPI evaluates Rego compiled to WebAssembly, in-process, only. Setting endpoint makes CAPI fail to start — unknown configuration properties are rejected, not ignored.

Per-Service Policies

Each service can declare its own OPA policy via the opa-rego metadata key:

curl -X PUT http://localhost:8500/v1/agent/service/register \
  -H "Content-Type: application/json" \
  -d '{
    "Name": "order-service",
    "Port": 8080,
    "Address": "10.0.0.10",
    "Meta": {
      "group": "v1",
      "root-context": "/orders",
      "scheme": "http",
      "secured": "true",
      "opa-rego": "capi/order_policy"
    }
  }'

opa-rego protects the service even when secured is false: without an OpenAPI spec every call is authorized, with one only the operations the spec protects. Add subscription-group as well and the caller must pass both.

CAPI evaluates the capi/order_policy entrypoint from the loaded Wasm bundle. The bundle must declare an entrypoint at <opa-rego>/allow; a service naming a policy the bundle does not declare is rejected with 403 Unknown policy.

OPA Input

CAPI sends the following input to OPA. The token is verified (signature and expiry) before OPA is consulted, so every claim here comes from a token CAPI accepted.

{
  "input": {
    "sub": "user-id",
    "azp": "client-id",
    "realm_access": { "roles": ["admin"] },
    "token": {
      "sub": "user-id",
      "azp": "client-id",
      "realm_access": { "roles": ["admin"] }
    },
    "service": "order-service:v1",
    "method": "GET",
    "path": "/api/order-service/v1/orders/123"
  }
}
  • token: the token's claims. The same claims also appear at the top level (input.azp), which is what policies written before 2.25.6 read; both forms keep working.
  • service: the service the call is for, as name:group.
  • method and path: the HTTP method and the request path, on REST and WebDAV calls. They are written after the claims, so a token carrying a method, path or service claim cannot stand in for them.

Before 2.25.6 only service and the top-level claims were sent, despite what this page said.

Example Rego Policy

package capi.order_policy

default allow = false

allow {
    input.method == "GET"
}

allow {
    input.method == "POST"
    input.token.realm_access.roles[_] == "admin"
}

This policy allows all GET requests but restricts POST to users with the admin role.

Evaluation model

Rego is compiled to WebAssembly and evaluated in-process, on the XNIO I/O thread: sub-millisecond, no network call, no thread dispatch. This keeps the whole request path — accept to proxy handoff — free of blocking I/O, matching every other pre-proxy check (JWT validation, API key lookup, throttle counters).

Compile your Rego to a .wasm bundle and serve it from a bundle server; point wasmBundleUrl at it. Services then name their policy with the opa-rego metadata key. Instances are drawn from one shared pool (wasmPoolSize) that grows under load and self-heals if an evaluation fails.

Authorization Flow

  1. Client sends a request with a Bearer token
  2. CAPI extracts the token — no token is 401, the OPA path does not skip authentication
  3. CAPI verifies the JWT signature and expiry before trusting any decoded claim — 401 Invalid authentication if it does not verify. OPA never sees an unverified token.
  4. If the service also declares a subscription-group, the token must be in it — 403 Not subscribed
  5. OPA disabled on this CAPI — 403 Policy engine not enabled
  6. If the policy engine has no bundle loaded yet, CAPI returns 503 with Retry-After: 1 rather than falling back to a weaker check
  7. A service naming a policy the bundle does not declare is rejected with 403 Unknown policy
  8. The policy is evaluated in-process and returns allow/deny
  9. Allowed requests are proxied; denied requests get 403 Access denied by policy

SSL / TLS

Gateway SSL

CAPI can terminate TLS on all its listeners:

capi:
  ssl:
    enabled: true
    keyStoreType: PKCS12
    path: /capi/certs/keystore.p12
    password: changeit

When using the Helm chart, provide the keystore as a base64-encoded value:

helm install capi-core helm/capi-core \
  --set capi.ssl.enabled=true \
  --set capi.ssl.keystoreBase64=$(base64 -i keystore.p12) \
  --set capi.ssl.password=changeit

Custom Truststore

To connect to upstream services with self-signed or internal CA certificates:

capi:
  trustStore:
    enabled: true
    path: /capi/certs/truststore.jks
    password: changeit

Inspect the loaded certificates via the Admin API:

curl http://localhost:8381/info/truststore

When the truststore is backed by Consul KV you can also add and remove certificates at runtime — PUT /info/truststore with a PEM body, and DELETE /info/truststore/{alias}. See Admin API — Truststore.

Path handling

CAPI binds the authorization decision to the service prefix in the path (/api/<service>/<group>), then strips that prefix and forwards the remainder to the backend. A . or .. segment in the remainder can therefore escape the root-context the service was registered with, while the request has already been authorized as that service.

capi:
  rest:
    rejectDotSegments: false   # true = refuse such paths with 400
  • Only a whole segment equal to . or .. is refused. Ordinary paths containing dots — /range/1..10, /files/report..pdf, /a..b, /v1.2.3/x, /.hidden — are unaffected. A substring test would reject all of those, which is why the check is segment-wise.

  • Percent-encoded forms are covered by the same rule: Undertow decodes %2e%2e, %2E%2E and mixed .%2e into .. before any handler runs. Double-encoded %252e%252e arrives as the literal segment %2e%2e and is not treated as a dot-segment — reaching .. from there requires a backend that percent-decodes twice, which is a defect in that backend.

  • Path parameters do not hide a dot-segment: a segment is compared up to its first ;, so ..; and ..;x=1 count as ... Tomcat, and so Spring Boot, strips ; parameters from each segment before normalising the path, and resolves them as ...

  • Off by default, because refusing a request an existing deployment forwards today is a behaviour change. While off, such requests are forwarded unchanged and only counted:

    capi_dot_segment_requests_total{service="...",action="observed"}
    

    Watch that stay at zero on real traffic, then set rejectDotSegments: true and the same paths return 400 (counted with action="rejected"). The check runs before any authorization decision.

Encoded slashes (%2F) are not currently rejected. Undertow does not decode them, so /foo%2F..%2F..%2Fadmin reaches the backend intact and is treated as a single path segment by the OpenAPI operation gate. A backend that decodes %2F will see a different path from the one CAPI validated. Tomcat and Spring reject encoded slashes by default; if yours does not, treat this as an open item.

Emergency path blocklist

For incidents: a backend exposes something it should not, such as Spring Boot's /actuator, and traffic must stop reaching it now, before its owner can ship a fix.

capi:
  blockedPaths:
    - /actuator

Any request whose path contains a listed rule gets 404 on the REST, WebSocket and WebDAV listeners. MCP and gRPC are not covered: MCP only calls the operations a spec declares, and gRPC routes by header, not by path.

How a rule matches

  • Whole segments, anywhere in the path, case-insensitive. Through CAPI a backend path arrives as /api/<service>/<group>/actuator/..., so a prefix match would never fire. /actuator blocks /api/orders/v1/actuator and /api/orders/v1/ACTUATOR/env, but not /api/orders/v1/actuators.
  • A multi-segment rule matches consecutive segments. /actuator/env blocks /api/orders/v1/actuator/env/... and leaves /api/orders/v1/actuator/health alone.
  • The path is canonicalised first, so another spelling of the same path cannot walk past the rule: percent-decoding (repeated, so %2561ctuator is caught), \ treated as /, ;parameters stripped from each segment (/actuator;jsessionid=x), empty and . segments dropped, .. resolved (/x/..;/actuator), and %2F treated as a separator. Both the raw request URI, which is what CAPI forwards, and the decoded path are checked.
  • The query string is not matched: /orders?next=/actuator is not blocked.

What the caller sees. The same 404 as an unknown route, returned before CORS preflight handling and before every authorization gate. A probe learns neither that the path exists nor whether its credentials would have been accepted.

Observability. Each blocked request increments

capi_blocked_requests_total{listener="rest|websocket|webdav", rule="/actuator", service="..."}

with service="unrouted" when the path did not resolve to a service. It also appears in the access log as a 404. Active rules are logged at WARN on startup.

Rules are validated at startup. A blank rule, a rule that resolves to / (it would block every request), a dot segment, or wildcard/query/parameter/percent syntax (*, ?, #, ;, %, \) stops CAPI from starting, rather than silently blocking nothing or everything.

Changing the list needs a restart. It is read once at startup. With the Helm chart, a helm upgrade that changes the config rolls the pods automatically through the checksum/config annotation. A ConfigMap edited by hand does not: follow it with kubectl rollout restart deployment/<capi-deployment>. Until the rollout finishes, pods that have not restarted yet still serve the path, so for the first minutes of an incident a WAF or load balancer rule in front of CAPI is faster.

This is a stop-gap, not a policy layer. The fix belongs in the backend: disable the endpoint or move it to a management port the gateway never routes to, then remove the rule.

OpenAPI spec endpoints

The open-api service metadata key is the one URL a service owner supplies that CAPI then requests itself — using the Consul HTTP client, which carries CAPI's trust store. Endpoints are checked before they are fetched:

capi:
  openApi:
    allowLocalSpecEndpoints: false
Target Allowed
Public addresses yes
Private / RFC 1918 (10.x, 172.16-31.x, 192.168.x) yes — this is where a spec normally lives
Loopback (127.0.0.0/8, ::1, localhost) no, unless allowLocalSpecEndpoints: true
Link-local (169.254.0.0/16, fe80::/10) never — the cloud metadata endpoints

Deliberately not a blanket private-range block. CAPI's legitimate backends are on RFC 1918 addresses, so refusing them would break the feature rather than secure it. What is refused is the two ranges that are never a valid spec host: cloud metadata, and loopback — which from the gateway means CAPI's own admin port or a co-located Consul agent, neither of which the service describing itself could legitimately point at.

The host is resolved before comparison, so 2130706433 and 127.1 are caught along with the dotted form, as is a hostname that resolves to a blocked address. Note that Java does not parse octal dotted-quads: 0177.0.0.1 resolves to 177.0.0.1, an ordinary public address, and is allowed — which matches what the HTTP client would connect to.

Kubernetes deployment

The rendered CAPI configuration embeds the Consul token, the OPA bundle token and the keystore / truststore passwords, so the Helm chart writes it to a Secret, not a ConfigMap.

A ConfigMap would be the wrong object for it: anything holding get/list on the namespace can read one, it is not encrypted at rest by default, and kubectl describe configmap prints it in full. Until 2026-09-29 the chart used a ConfigMap, so those credentials were readable by every workload in the namespace. If you deployed a chart before that, rotate the Consul and OPA tokens.

The Secret mounts exactly as the ConfigMap did, so no other change is needed.

WebSocket origins

A page the victim happens to visit can open a WebSocket to the gateway. Without a check the socket is established in the victim's network position — which matters most for services needing no subscription, since those are reachable with no credential at all.

capi:
  websocket:
    enforceOriginCheck: false   # true = refuse an upgrade from an unlisted Origin
  • Uses the same allowlist as CORS — capi.allowedOrigins, overridden per service by the allowed-origins metadata key.
  • A request with no Origin is always allowed. Browsers always send one on a handshake, so its absence identifies a non-browser client — not what this attack uses. Refusing them would break every server-to-server WebSocket client for no security gain.
  • Off by default, because refusing an upgrade breaks a client outright rather than degrading it. While off, an unlisted origin connects as before and is counted via capi_websocket_origin_total{action="observed"}; watch that, then enable.

Scope worth being precise about. CAPI's WebSocket authentication accepts only the Authorization header or the access_token query parameter — not cookies. A browser cannot set headers on a WebSocket handshake, so a cross-site page has no ambient credential to ride and cannot authenticate to a secured service. The real exposure is unsecured services plus the victim's network position, which is what this setting addresses.

gRPC

The gRPC listener routes by the x-capi-service header and applies the same authorization rules as REST and WebSocket: secured and opa-rego protect a service, and the caller must pass its subscription-group and its policy. (There is no OpenAPI spec on this listener.) Until 2026-09-29 this listener dispatched straight to the backend; until 2.25.1 it ignored opa-rego.

Refusals use gRPC semantics rather than HTTP status codes, because a gRPC client reads grpc-status and would surface a bare 401 as an opaque transport error:

Situation Response
No token, or a token that does not verify HTTP 200, grpc-status: 16 (UNAUTHENTICATED)
Not in the subscription group, refused by the policy, or no rule declared HTTP 200, grpc-status: 7 (PERMISSION_DENIED)
Policy engine not loaded yet HTTP 200, grpc-status: 14 (UNAVAILABLE)
oauth2 not configured, service protected HTTP 200, grpc-status: 16 — refused, not passed through

Services with neither secured nor opa-rego are unaffected and still route without a token.

Note this listener still has no throttle or request-time watchdog. Treat the gRPC port as internal.

CORS

CORS is controlled by two keys. corsEnabled is the master switch: while it is false CAPI sends no CORS header at all, and both allowedOrigins and any per-service allowed-origins metadata are ignored. With it true, an origin must be allowlisted to receive any CORS header — an empty list denies every origin:

capi:
  corsEnabled: true
  allowedOrigins:
    - https://app.example.com
  allowedHeaders:
    - Origin
    - Accept
    - X-Requested-With
    - Content-Type
    - Access-Control-Request-Method
    - Authorization

With corsEnabled: true and the request's Origin on the allowlist, CAPI sets:

  • Access-Control-Allow-Origin: <that origin>
  • Access-Control-Allow-Credentials: true
  • Vary: Origin

And on a preflight, regardless of origin:

  • Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH
  • Access-Control-Max-Age: 86400

With allowedOrigins: ["*"], Access-Control-Allow-Origin: * is sent and Access-Control-Allow-Credentials is never sent — the pair is invalid per the Fetch standard, so cookie-authenticated browser clients need their origin listed explicitly.

corsEnabled: false was previously reporting-only — it appeared in /info/capi but gated nothing, so a config reading corsEnabled: false could still serve CORS headers. It is now enforced.

Per-service origins (preferred)

CORS origins belong to whoever owns the service, so they travel with the Consul registration:

{ "Meta": { "allowed-origins": "https://team-a-app.example,https://team-a-admin.example" } }
  • A service that declares allowed-origins uses exactly that list — it replaces the gateway default rather than adding to it.
  • A service that declares nothing inherits capi.allowedOrigins.
  • One service's origins never apply to another, so listing an origin for your service does not grant it access to anyone else's.
  • Requires capi.corsEnabled: true; the master switch overrides per-service origins.
  • Changing the list is a re-registration, not a CAPI redeploy — but remember CAPI only picks up changed metadata when the version meta is bumped (see capi-service-discovery).

Use capi.allowedOrigins for an origin that genuinely spans the whole gateway, such as a shared developer portal, and the ServiceMeta key for everything else.

Note: allowed-origins was present in ServiceMeta but read by nothing until 2026-09-25 — registrations that set it had no effect before then.