CORS, CountLimit, Cache and SQLInjectionFilter in API Studio for the DataPower Nano Gateway: worked examples
Draft!!
Four policies sit around the payload instead of inside it: what a browser may send, how often a caller may call, what can be answered from memory, and what must never reach the backend. This post runs each one against a real gateway and records what came back, including three results that surprised me.
For a limit that resets on a clock, see the RateLimit post. It also covers why a rate limit is a plan setting rather than an assembly policy.
The test project
One API Studio project, one API called nano-traffic, one operation for each case:
| Operation | Policy | What it shows |
|---|---|---|
OPTIONS /cors/allowed |
CORS |
Preflight from a listed origin |
OPTIONS /cors/denied |
CORS |
Preflight from a denied origin |
GET /limit/count |
CountLimit |
Refusing the third call |
GET /cache/read |
Cache |
The second caller served from memory |
GET /security/sqli |
SQLInjectionFilter |
A payload blocked, and a payload that is not |
CORS is not an assembly policy. It is a list of rules on the API itself, under spec.cors. The other three sit in an OperationSwitch assembly. There is no backend. Each operation builds its own response with a Set policy, so a response that came from a policy cannot be mistaken for one that came from a backend.
Every call goes to the published product URL with the client credentials of a subscribed application, except the CORS preflight, which I also ran without them:
curl -s -i \
-H "X-IBM-Client-Id: <client-id>" \
-H "X-IBM-Client-Secret: <client-secret>" \
"https://<gateway-host>/1.0.0/nano-traffic/limit/count?client=test1"
TLS was validated against the cluster’s own CA on every call.
Example 1: CORS preflight from a listed origin
The rules live in a CORS resource that the API references:
kind: API
spec:
cors:
$ref: 'nanogw-policy-samples:nano-traffic-cors:1.0.0'
kind: CORS
spec:
rules:
- action: allow
originList:
- https://app.example.test
allowMethods: [GET, POST, OPTIONS]
allowHeaders: [Content-Type, X-Request-Id, X-Version]
exposeHeaders:
predefined: true
backend: true
maxAge: 600
allowCredentials: false
- action: deny
originList:
- https://evil.example.test
The preflight a browser would send:
curl -i -X OPTIONS \
-H 'Origin: https://app.example.test' \
-H 'Access-Control-Request-Method: GET' \
-H 'Access-Control-Request-Headers: X-Request-Id' \
"https://<gateway-host>/1.0.0/nano-traffic/cors/allowed"
Response:
HTTP/2 204
access-control-allow-methods: GET
access-control-allow-headers: Content-Type
access-control-allow-headers: X-Request-Id
access-control-allow-headers: X-Version
access-control-allow-origin: https://app.example.test
vary: origin
The same call without the client credentials returns the identical response. That is correct. Browsers do not send credentials on a preflight, and the gateway answers it before any assembly runs. The Set policy behind /cors/allowed was never reached.
Three details:
Access-Control-Allow-Methodsholds only the method I asked about, not theGET, POST, OPTIONSI configured.Access-Control-Allow-Headersis the full configured list, not justX-Request-Id.- There is no
Access-Control-Max-Age.
The last one is a defect in the project, not in the gateway’s behaviour. The YAML says maxAge: 600 and lint accepts it. I read the API resource on the cluster after publishing, and the rule has no maxAge field at all. From my project notes, the field the gateway reads is maxAgeSeconds, which lint rejects. I did not try that field.
A real request from the same origin carries the response headers a browser needs:
curl -i -H "X-IBM-Client-Id: <client-id>" -H "X-IBM-Client-Secret: <client-secret>" \
-H 'Origin: https://app.example.test' \
"https://<gateway-host>/1.0.0/nano-traffic/limit/count?client=test1"
HTTP/2 200
access-control-expose-headers: location
access-control-expose-headers: retry-after
vary: origin
access-control-allow-origin: https://app.example.test
That is what exposeHeaders.predefined: true adds. I did not test backend: true, because the Set policy produces no backend headers to expose.
Example 2: a denied origin
The same rules, with Origin: https://evil.example.test:
curl -i -X OPTIONS \
-H 'Origin: https://evil.example.test' \
-H 'Access-Control-Request-Method: GET' \
-H "X-IBM-Client-Id: <client-id>" -H "X-IBM-Client-Secret: <client-secret>" \
"https://<gateway-host>/1.0.0/nano-traffic/cors/denied"
HTTP/2 200
OK
No Access-Control-Allow-* header, so the browser refuses to send the real request. The body is the plain text OK. It is not the JSON the Set policy would have built, so the assembly did not run.
A status check cannot tell this from a working call. A 200 came back. The test has to assert that access-control-allow-origin is absent.
The denial follows the Origin header, not the preflight. A normal GET to /limit/count with Origin: https://evil.example.test also returned 200 with the body OK, and none of the assembly’s JSON. It is still not authorisation. A caller that sends no Origin, or a different one, is not affected. The assembly has to authenticate the request itself.
Example 3: an origin with no rule
This is the result I did not expect. My project notes say an origin that matches no rule gets no CORS headers at all. I called the preflight with an origin that is in neither rule, asking for a method and a header that no rule allows:
curl -i -X OPTIONS \
-H 'Origin: https://other.example.test' \
-H 'Access-Control-Request-Method: DELETE' \
-H 'Access-Control-Request-Headers: X-Anything' \
-H "X-IBM-Client-Id: <client-id>" -H "X-IBM-Client-Secret: <client-secret>" \
"https://<gateway-host>/1.0.0/nano-traffic/cors/allowed"
HTTP/2 204
access-control-allow-methods: DELETE
access-control-allow-headers: X-Anything
access-control-allow-origin: https://other.example.test
vary: origin
The gateway echoed back the origin, the method and the header exactly as asked. An origin with no matching rule is allowed everything. The only way to refuse an origin is an explicit deny rule, so an allow-list of origins is not enforced by listing the ones you want.
I ran this once, for GET and for DELETE. I did not test credentials. I did not find anything in the product reference that describes this default.
The reverse case also behaves as a refusal. The listed origin https://app.example.test asking for DELETE, which its rule does not allow, got 200 and OK with no CORS headers, the same as the denied origin.
If the request has no Origin header, it reaches the assembly:
HTTP/2 200
{"cors":"handled by the API-level policy"}
Example 4: CountLimit
CountLimit is two resources. A CountLimitDef holds the number, and the policy references it:
kind: CountLimitDef
spec:
max: 2
autoDecrement: false
extensions:
dp-nano-gateway:
apiVersion: api.ibm.com/v1
spec:
dynamicValue: $queryParameter('request', 'client')
kind: CountLimit
spec:
limits:
- limitDef:
name: calls-per-window
definition:
$ref: 'nanogw-policy-samples:nano-traffic-limit-def:1.0.0'
operation: increment
A Set policy follows it. That wording turns out to be misleading, and I come back to it.
curl -i -H "X-IBM-Client-Id: <client-id>" -H "X-IBM-Client-Secret: <client-secret>" \
"https://<gateway-host>/1.0.0/nano-traffic/limit/count?client=test1"
Three calls on the same client value, then one on a different value:
client |
Call | Status |
|---|---|---|
test1 |
1 | 200 |
test1 |
2 | 200 |
test1 |
3 | 429 |
test2 |
1 | 200 |
Calls 1 and 2:
HTTP/2 200
{"error":"count limit exceeded","limit":"calls-per-window","allowed":2}
Call 3:
HTTP/2 429
Too Many Requests
Read those two again. The JSON that says count limit exceeded came back on the calls that succeeded. The Set policy only runs when CountLimit lets the call through, so the wording in my sample is wrong. The refusal is the gateway’s plain text Too Many Requests, with no Content-Type and no Retry-After. Treat the body of a Set after a limit as the success response.
dynamicValue selects the bucket. test2 had its own two calls. A request with no client parameter returned 500 Internal Server Error, because the expression produced nothing.
What I did not re-run:
autoDecrement: true, the default. From the reference and my project notes, it decrements at the end of the transaction, so it bounds concurrent calls, not call volume. A client that calls one at a time never trips it. That is rarely what anyone wants.- The object form
operation: {increment: {}}. From my project notes, lint accepts it and the gateway refuses to publish it withparsing action countLimit: invalid type: map, expected unit. dynamicValuewritten at the top level of the definition. From my project notes, lint accepts it and the publish drops it, leaving one counter for everyone.- That the count never expires.
CountLimitDefhas no window. From my project notes, a key stays exhausted until the gateway’s store is cleared. I did not wait long enough to test it.
Example 5: Cache
A Cache policy wraps a list of actions. On a miss it runs them and stores the named outputs. On a hit it skips them and restores the outputs:
kind: Cache
spec:
inputs:
- custom:
expression: "$relativeUrl('request')"
outputs:
- messageBody:
name: response
expire:
static:
seconds: 60
execute:
- $ref: 'nanogw-policy-samples:nano-traffic-set-cache-response:1.0.0'
The wrapped Set builds a body from the URL and a request header:
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
{
"cacheKey": $relativeUrl('request'),
"version": $header('request', 'X-Version')
}
inputs and outputs are single-key maps: custom: {expression: ...} and messageBody: {name: response}. From my project notes, the - name: cacheKey shape that the lint schema allows is read by lint and ignored by the gateway, so the cache never hits. I did not re-run that.
The test is to change an input that is not part of the key and see whether the old answer comes back. First call with X-Version: v1, second with X-Version: v2, same key:
curl ... -H 'X-Version: v1' "https://<gateway-host>/1.0.0/nano-traffic/cache/read?key=test1"
curl ... -H 'X-Version: v2' "https://<gateway-host>/1.0.0/nano-traffic/cache/read?key=test1"
| Call | Header | Response body |
|---|---|---|
| 1 | v1 |
{"cacheKey":"/cache/read?key=test1","version":"v1"} |
| 2 | v2 |
{"cacheKey":"/cache/read?key=test1","version":"v1"} |
The second caller sent v2 and got v1 back. The assembly did not run. A third call with a different key and v2 ran normally and returned v2.
The cache key here is the whole relative URL including the query string. The same key with an extra &x=1 is a different entry, and ran the assembly again.
I also checked the expiry. A call with v1, another with v2 after 20 seconds, and one with v3 after about 65 seconds:
| Elapsed | Header | version returned |
|---|---|---|
| 0s | v1 |
v1 |
| ~20s | v2 |
v1 |
| ~65s | v3 |
v3 |
That matches static: {seconds: 60}.
expire takes one of four forms. I used static. The others are fromMessageHeader, fromVariable and fromCacheControl. I did not run those three.
I cached messageBody only. From my project notes, a cached response can then carry the previous caller’s headers, because headers are only restored when they are listed in outputs. I did not test that.
Anything stateful in the cached actions happens once per entry. A counter or an audit event inside execute is skipped on every hit.
Example 6: SQLInjectionFilter
The filter looks at the request before the rest of the assembly and refuses what looks like SQL:
kind: SQLInjectionFilter
spec:
filterOn: uri
injectionRules:
predefined:
- likeMatch
- escapeSequence
- keywordInjection
- metacharacters
- oracleBufferOverflow
- simpleMetacharacters
custom: []
message: request
A Set policy then returns the name parameter so I can see what survived. I asked for six rule families. From my project notes, the lint schema accepts a longer list than the gateway knows, and a name the gateway does not know makes it fail to start. These six are the ones I found safe in both. I did not re-run that.
Seven payloads, sent through the same call:
curl ... "https://<gateway-host>/1.0.0/nano-traffic/security/sqli?name=<payload>"
name as sent |
Status | Body |
|---|---|---|
ada |
200 | {"filter":"passed","query":"ada"} |
ada%27+OR+1%3D1-- |
500 | Internal Server Error |
ada%27%20OR%201%3D1-- |
200 | {"filter":"passed","query":"ada%27%20OR%201%3D1--"} |
x%27%3B+DROP+TABLE+users-- |
500 | Internal Server Error |
x%27%3BDROP%20TABLE%20users-- |
500 | Internal Server Error |
1+UNION+SELECT+password+FROM+users |
200 | passed |
1%20UNION%20SELECT%20password%20FROM%20users |
200 | passed |
Four results matter:
- A block is a
500, not a400. It lands in your server-error dashboards, and the body is the genericInternal Server Error. - The same payload written with
+for the spaces was blocked. Written with%20it passed. The rule appears to read the URI after+becomes a space and before%20does.' OR 1=1--got past the filter in the%20form. UNION SELECTpassed in both forms. The six families caught payloads that contain a quote. A payload with no quote is not caught by this set.- The filter only reads the URI. A header carrying
' OR 1=1--went through and the call returned200. I sent that header on a cleanname.
filterOn is uri, body or bodyAndUri. body needs a Parse policy first. From my project notes, the runtime refuses to filter a body it has not parsed. I did not run a body filter.
I would treat this policy as one layer. Validate parameters against the schema in the OpenAPI definition, and use parameterised queries in whatever sits behind the gateway.
Summary
| Policy | What I saw |
|---|---|
CORS |
A listed origin got a 204 with the allow headers. A denied origin, or a listed origin asking for an unlisted method, got 200 OK and no CORS headers. An origin with no rule was allowed anything it asked for. |
CountLimit |
The third call on a key returned 429 with the plain text Too Many Requests. Keys are independent. A missing key returned 500. |
Cache |
The second caller got the first caller’s body. The key is the full relative URL. The entry expired inside 65 seconds. |
SQLInjectionFilter |
Quoted payloads were blocked with 500. The %20 form of the same payload passed, and so did UNION SELECT with no quote. |
Limitations and Notes
- I ran these against one real gateway on a lab cluster, with TLS verified against the cluster’s CA. Every response is from a live call. Hostnames, credentials and the upstream details are placeholders.
- Claims marked as from my project notes come from files I wrote earlier. I did not re-run them.
- The CORS results come from a single gateway version. The no-rule behaviour contradicts what I wrote down earlier and I found nothing in the product reference to explain it. Check it on your own gateway before relying on either.
- I did not test
allowCredentials: true, wildcard origins,backend: true, or CORS on a path that has a real backend. CountLimitdoes not reset. If you need a window, useRateLimitor a plan-level limit.- The SQL filter result is a test of six rule families and a handful of payloads. It is not a security assessment.
