Card authorisation on the DataPower Nano Gateway: Luhn, risk scoring, a weighted limit and a stand-in fallback
Draft!!
A card authorisation has two jobs that pull in different directions. Decline anything that looks like fraud, and approve anything you can when the authorisation engine is down. This post builds bank-cardfraud, one POST /authorisations operation that does both on the Nano Gateway.
Read this first
I have not run this API on a Nano Gateway. I had no management login for the cluster, so I could not publish it. Most posts in this series were measured on a live gateway. This one was not.
Checked offline:
apic lintpasses.- The Lua script runs under Lua 5.5 and LuaJIT in a test harness.
- The JSONata expressions pass a subset check, and the guard expressions have unit tests (42 assertions for this API).
tests/bank-cardfraud.shpasses a bash syntax check and a stub-server smoke run.
Not checked: how the gateway runs any of it. The assumptions are listed at the end.
What the API does
One request carries a card, an amount, a channel and a merchant:
{
"card": { "pan": "<card number>", "expiry": "MM/YY", "cvv": "<cvv>" },
"amount": 20,
"currency": "GBP",
"channel": "pos",
"merchant": { "id": "M-100", "mcc": "5411", "country": "GB" }
}
The policy flow:
- parse-request
- validate-request # 400
- card-checks # Lua: Luhn, expiry, risk score
- guard-pan # 422
- guard-expiry-invalid # 422
- guard-expired # 422
- guard-risk # 403 "declined: risk"
- card-allowance # weighted RateLimit, 429
- remove-cvv
- redact-pan
- engine-try # Retry inside Try, with a stand-in
CORS denies every origin. This is a server-to-server API and no browser should call it.
The Lua script
One script does the Luhn check, the expiry check and the risk score. JSONata cannot loop over digits or read the clock.
Luhn:
local pan = tostring(card.pan or ''):gsub('[ %-]', '')
local pan_ok = false
if pan:match('^%d+$') and #pan >= 13 and #pan <= 19 then
local sum, double = 0, false
for i = #pan, 1, -1 do
local d = tonumber(pan:sub(i, i))
if double then
d = d * 2
if d > 9 then d = d - 9 end
end
sum = sum + d
double = not double
end
pan_ok = (sum % 10 == 0)
end
Spaces and dashes are tolerated. Letters, short numbers and a failed checksum are not. A card is valid until the end of the month on the card, so MM/YY is compared by year and month only.
The risk score is a few additions. It is a demonstration, not a fraud model:
| Signal | Points |
|---|---|
| Amount 500 or more | 2 |
| Amount 2000 or more | 4 instead |
Channel ecom |
1 |
| Merchant category 7995, 6051 or 4829 (gambling, crypto, money transfer) | 3 |
Merchant country not GB |
1 |
Score 0 to 2 is low, 3 to 5 is medium and 6 or more is high. The script maps each band to a weight of 1, 3 or 5.
The script writes the results as headers: X-Pan-Valid, X-Pan-Bin, X-Pan-Last4, X-Card-Expiry-Status, X-Risk-Score, X-Risk-Band and X-Risk-Weight. It always overwrites them, so a caller cannot send their own. The test script sends X-Pan-Valid: true with a bad number and X-Risk-Band: low with a high-risk payment, and expects the gateway to ignore both.
The full card number never goes into a header. Only the first six digits (the BIN) and the last four do, which is what a receipt may show. Headers end up in logs and in the backend request, and the number does not belong there.
Guards
Each guard is an If and a Throw. The risk guard:
kind: If
spec:
condition: $header('request', 'X-Risk-Band') = 'high'
execute:
- $ref: bank-cardfraud:bank-cardfraud-guard-risk-throw:1.0.0
---
kind: Throw
spec:
error:
CustomError:
message: "declined: risk"
messageType: plain
status: 403
The PAN guard is $not($header('request', 'X-Pan-Valid') = 'true'). I use $not(... = ...) rather than !=, because comparing a missing value with != gives false in JSONata and the guard would let the request through. See the payments post for the longer story.
The test sends a number that fails Luhn, a number made of letters, an expired card, and month 13, and expects 422 each time. It sends spaces in a valid number and expects 200.
A rate limit whose cost depends on the risk
Six units a minute per card. A low-risk authorisation costs 1. A medium one costs 3. A card making medium-risk requests runs out after two, and a card making ordinary ones after six.
kind: RateLimitDef
spec:
max: 6
intervalLen: 1
intervalUnit: minute
extensions:
dp-nano-gateway:
apiVersion: api.ibm.com/v1
spec:
weightExpr: $number($header('request', 'X-Risk-Weight'))
dynamicValue: $header('request', 'X-Pan-Bin') & $header('request', 'X-Pan-Last4')
The key is the BIN plus the last four digits, which is enough to tell cards apart without storing the number. weightExpr makes the cost of a call a number computed per request, as the rate limit post showed with X-Weight.
The RateLimit sits after the risk guard. A declined high-risk request never reaches it and costs nothing. The test script checks the order of events:
- Three medium authorisations on one card. The first two return
200(6 units used). The third returns429. - A low authorisation on the same card returns
429. The allowance is gone, whatever the weight. - A different card returns
200. - Six low authorisations on a fresh card return
200. The seventh returns429. - Three high-risk requests on another card return
403, then a low one returns200. The declined ones used nothing.
Remove the CVV, redact the PAN
Before the engine is called:
kind: Remove
spec:
message:
messageName: request
body:
captures:
jsonata:
- $.card.cvv
---
kind: Redact
spec:
message:
messageName: request
body:
captures:
jsonata:
- $.card.pan
Remove deletes the member and Redact overwrites the value with *****, as the shape post showed. After the Lua script and the guards have used the card number, nothing downstream needs it. The engine in this sample is the echo service, which returns what it received. The response includes panSeen and cvvSeen, and the test asserts ***** and false. It also asserts the response body does not contain the card number anywhere.
A real engine needs the real PAN to authorise. This sample shows where the redaction goes for a downstream that must not have it, such as a logging or analytics call. Move it if your engine does need the number.
Retry, then stand in
Try runs the engine call. A Retry inside it makes one more attempt after 200 ms. If that also fails, the catch runs a Switch:
kind: Try
spec:
execute:
- $ref: bank-cardfraud:bank-cardfraud-engine-retry:1.0.0
- $ref: bank-cardfraud:bank-cardfraud-parse-engine:1.0.0
- $ref: bank-cardfraud:bank-cardfraud-approved-response:1.0.0
catch:
- errors:
- InternalError
- ConnectionError
- TimeoutError
execute:
- $ref: bank-cardfraud:bank-cardfraud-stand-in-switch:1.0.0
---
kind: Retry
spec:
delay: 200
maxRetries: 1
retryOn:
- InternalError
- ConnectionError
- TimeoutError
execute:
- $ref: bank-cardfraud:bank-cardfraud-engine-switch:1.0.0
---
kind: Switch
spec:
cases:
- condition: $body('request').amount <= 30
execute:
- $ref: bank-cardfraud:bank-cardfraud-stand-in-response:1.0.0
otherwise:
- $ref: bank-cardfraud:bank-cardfraud-throw-unavailable:1.0.0
An amount of 30 or less is approved in stand-in mode, with "mode": "STAND_IN". Anything larger returns 503 authorisation service unavailable. A small purchase approved offline is a business decision many card schemes make. A large one is not.
The resilience post showed that an Invoke needs statusException for a 500 to count as an error, so all three engine invokes have statusException: pattern '500'.
To test failures without a broken engine, the policy has a hook. A request header X-Test-Engine selects a different invoke:
flakycalls/flaky?fail=1&key=<transaction id>. It fails the first time and works the second. The test expects200,ONLINE, andengineCallof 2.downcalls/fail. Both attempts fail. The test checks amounts of 25 and 30 approved in stand-in, and 30.01 returned as503.
That hook is a test aid. Anyone who sends the header chooses the engine. Delete the two policies and the Switch before you use this design in anything real.
Running the tests
export NANOGW_CLIENT_ID=<client-id>
export NANOGW_CLIENT_SECRET=<client-secret>
export NANOGW_DOMAIN=<gateway-ingress-domain>
./tests/bank-cardfraud.sh
44 assertions, with fresh card numbers each run (the helper builds numbers that pass Luhn). The weighted allowance tests use their own cards, so the script can be run again straight away.
Summary
- Compute risk once, in Lua, and let later policies read it. The same score drives the decline and the cost of the rate limit.
- Put the decline before the rate limit, so a declined request is free.
- Never copy a card number into a header. Keep the BIN and last four.
- A
Trywith aRetryinside is a retry-then-degrade pattern. The catch is where the business decision lives, and it can differ by amount. - Test hooks that change the route belong in samples, not in production policies.
Limitations and Notes
- Not run on a gateway. The checks above are offline.
- Assumptions to confirm on the first run:
Trycatches an error that aRetrygave up on.$gtid()is the same on the second attempt, so theflakyhook sees one key.Invokeforwards thePOSTbody to the engine, and the redacted PAN shows as*****. I measuredRedactin the shape post, but not after aLuastep.- A header set by Lua is visible to a later JSONata
If, and toweightExpranddynamicValue. weightExpranddynamicValuecan read request headers.- A catch-all
denyCORS rule leaves unlisted origins without CORS headers.
- The risk score is invented for the demonstration. It is not a fraud model.
- The expiry check uses the gateway’s clock and time zone.
- The stand-in approval has no record of the amount spent. A real stand-in needs a ceiling per card.
- The engine is the echo service, so the response only shows what the gateway sent.
