A payment API has one rule that matters more than the rest: a client that retries must not pay twice. This post builds bank-payments, a payment initiation API on the DataPower Nano Gateway that handles that rule, plus the usual bank checks, with nothing but policies.

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. The earlier posts in this series, such as rate limits and control flow, were measured on a live gateway. This one was not.

What I did check, offline:

  • apic lint passes on the project.
  • The Lua script runs under Lua 5.5 and LuaJIT (the gateway uses Lua 5.1 semantics) against a small test harness.
  • Every JSONata expression passes a subset check for the features the gateway supports, and the ones in this project have unit tests (34 assertions for this API).
  • The live test script, tests/bank-payments.sh, passes a bash syntax check and a smoke run against a stub server.

What I did not check is how the gateway behaves. The list of things I am assuming is at the end. Treat the YAML as a worked design, not a tested one.

The API

Two operations:

Operation What it does
POST /payments Starts a payment. Needs an Idempotency-Key header and a bearer token.
GET /payments/{paymentId} Returns the status of a payment.

The backend is a stand-in for a core banking system, the echo service from the earlier posts. It returns whatever it was sent, which is enough to prove what the gateway forwarded.

The sequence is the same shape as every other project in the series: ExtractIdentity, Authenticate, Authorize, then an OperationSwitch. The POST branch runs eleven policies in a fixed order:

- parse-request
- validate-request
- guard-idempotency-key     # 400
- guard-bearer              # 401
- payment-checks            # Lua, sets headers
- guard-debtor-iban         # 422
- guard-creditor-iban       # 422
- guard-same-account        # 422
- guard-amount-precision    # 422
- guard-approval            # 428
- idempotent-payment        # Cache: velocity limit, forward bearer, invoke, receipt

The order is the design. Cheap checks come first. Anything that costs the client an allowance comes last.

Step 1: validate the shape

ValidateAPISpecification checks the body against the OpenAPI schema. The spec asks for two IBANs of at most 42 characters, an amount of at least 0.01, a currency of GBP, EUR or USD, and a reference of at most 35 characters. A body that breaks any of that returns a plain 400, as the shape post showed.

The test script sends nine bad bodies and expects 400 for each: a missing field, a negative amount, zero, "ten", JPY, a long reference. A body that is not JSON is the tenth.

Step 2: the header guards

Each guard is two small policies. An If holds the condition. A Throw holds the response. The If points at the Throw:

kind: If
spec:
  condition: $not($exists($header('request', 'Idempotency-Key')))
  execute:
    - $ref: bank-payments:bank-payments-guard-idempotency-key-throw:1.0.0
---
kind: Throw
spec:
  error:
    CustomError:
      message: Idempotency-Key header is required
      messageType: plain
      status: 400

The bearer guard is the same with Authorization and a 401. The test script sends a body with a bad IBAN and no key, and expects 400. That proves the key check runs before the IBAN check.

The bearer guard only checks that a header is present. It does not validate the token. The gateway already authenticated the client with its ID and secret. The bearer token belongs to the end user and is passed on to the core system, which is the one that can judge it.

Step 3: IBAN checks in Lua

JSONata cannot do the IBAN checksum. It has no loop and no modulo over a 30-digit number. Lua can, as the Lua post showed for other checks. The core of the script:

local function iban_ok(value)
  if type(value) ~= 'string' then return false end
  local s = string.upper((value:gsub('%s', '')))
  if #s < 15 or #s > 34 then return false end
  if not s:match('^%a%a%d%d%w+$') then return false end
  local r = s:sub(5) .. s:sub(1, 4)
  local rem = 0
  for i = 1, #r do
    local c = r:sub(i, i)
    if c:match('%d') then
      rem = (rem * 10 + tonumber(c)) % 97
    elseif c:match('%u') then
      rem = (rem * 100 + (string.byte(c) - 55)) % 97
    else
      return false
    end
  end
  return rem == 1
end

It moves the first four characters to the end, turns letters into numbers and keeps a running remainder, so the number never gets too big for a double. Lower case and spaces are tolerated: gb82 west 1234 5698 7654 32 passes.

The script writes its results onto the request as headers:

req.headers:set('X-Debtor-Iban-Valid', flag(iban_ok(body.debtorIban)))
req.headers:set('X-Creditor-Iban-Valid', flag(iban_ok(body.creditorIban)))
req.headers:set('X-Same-Account', flag(...))
req.headers:set('X-Amount-Precision-Valid', flag(two_decimals))
req.headers:set('X-Payment-Band', amount > 10000 and 'high' or 'standard')

The two-decimal check multiplies by 100 and compares with the nearest whole number, with a tolerance. 19.99 passes and 10.123 fails.

The script always uses set, never a conditional add. That matters. A caller who sends X-Payment-Band: standard with a 50,000 payment has the header replaced. The test script sends exactly that and expects 428, and sends a forged X-Debtor-Iban-Valid: true with a bad IBAN and expects 422.

The If policies then read the headers. Each failure has its own message, for example debtorIban failed the IBAN checksum:

condition: $not($header('request', 'X-Debtor-Iban-Valid') = 'true')

This form is deliberate. The obvious $header(...) != 'true' fails open. In JSONata, comparing a missing value with != gives false, so a request with no header would sail past the guard. $not(... = 'true') fails closed. My offline JSONata unit tests caught this exact bug in an earlier draft of this project. I have not confirmed the behaviour on the gateway itself.

The approval guard needs a high band and no approval token:

condition: $header('request', 'X-Payment-Band') = 'high' and $not($exists($header('request', 'X-Approval-Token')))

The boundary is tested both sides: 10000 needs no token, 10000.01 returns 428.

Step 4: idempotency with a cache

A Cache policy keyed on the request is the idempotency store. The key combines the client, the Idempotency-Key, the debtor IBAN and the amount:

kind: Cache
spec:
  inputs:
    - custom:
        expression: "$telemetry('client_id') & '|' & $header('request', 'Idempotency-Key') & '|' & $body('request').debtorIban & '|' & $string($body('request').amount)"
  outputs:
    - messageBody:
        name: response
  expire:
    static:
      seconds: 120
  execute:
    - $ref: bank-payments:bank-payments-velocity-limit:1.0.0
    - $ref: bank-payments:bank-payments-forward-bearer:1.0.0
    - $ref: bank-payments:bank-payments-invoke-core:1.0.0
    - $ref: bank-payments:bank-payments-parse-core:1.0.0
    - $ref: bank-payments:bank-payments-receipt:1.0.0

On a miss, the execute list runs and the final response body is stored for 120 seconds. On a hit, the stored response is returned and the list is skipped. The traffic post measured that a hit skips the list. That is what makes a replay safe: the second request never reaches the core system and never spends the velocity allowance.

The amount is in the key on purpose. The same key with a different amount is a different request and gets its own payment. A stricter design would reject it with a 422. That needs a store for the first request, which a cache does not give you. I note it as a limit below.

The receipt body is built with a Set in JSONata. It masks the debtor account to the first four and last four characters:

"debtorAccount": $substring($body('core').body.debtorIban, 0, 4) & '**********' & $substring($body('core').body.debtorIban, $length($body('core').body.debtorIban) - 4, 4),

and it generates the payment ID with $gtid(). The test script checks that the full debtor IBAN does not appear anywhere in the receipt.

Step 5: velocity limit inside the cache

Three payments a minute per debtor, counted with a RateLimit whose definition uses a dynamic value:

kind: RateLimitDef
spec:
  max: 3
  intervalLen: 1
  intervalUnit: minute
  extensions:
    dp-nano-gateway:
      apiVersion: api.ibm.com/v1
      spec:
        dynamicValue: $body('request').debtorIban

It sits first in the cache’s execute list, so only a cache miss consumes it. The test script checks the consequence in an awkward order on purpose:

  1. Five payments of 50,000 with no approval token. All return 428. None of them reach the limit, because the approval guard runs earlier.
  2. Three payments of different amounts for the same debtor. All 200.
  3. A fourth payment returns 429.
  4. A replay of payment 2, with its original key and amount, returns 200 from the cache even though the debtor is now at the limit.
  5. A different debtor, 200.

Step 1 matters. A client that sends a rejected payment ten times should not run out of allowance.

Step 6: forward the bearer token

SetAuthorization with jwt: useIncoming copies the caller’s Authorization header onto the request that goes to the core system. The receipt compares what the core system received with what the client sent and reports bearerForwarded. The test script asserts that it is true.

The status operation

GET /payments/{paymentId} runs an SQLInjectionFilter on the URI, a guard that the ID starts with PAY-, and an Invoke that passes the ID to the core system as a query parameter.

The guard uses $substringBefore($pathParameter('paymentId'), '-') != 'PAY'. A path parameter is always present when the operation matches, so != is safe here.

The test script sends PAY-1001 and expects 200, ABC-1001 and expects 400, and a PAY-1'; DROP TABLE payments-- URL-encoded with %20 and expects 500 or 400. In the traffic post the filter blocked a payload with a plain 500 and missed payloads containing %20. Treat the filter as one layer. The PAY- guard is the better defence here, and the core system must still use parameterised queries.

Running the tests

export NANOGW_CLIENT_ID=<client-id>
export NANOGW_CLIENT_SECRET=<client-secret>
export NANOGW_DOMAIN=<gateway-ingress-domain>
./tests/bank-payments.sh

The script has 55 assertions across access control, the happy path, idempotency, required headers, contract validation, business rules, the approval limit, forged headers, velocity and status. It verifies TLS and has no option to turn that off. Each run uses new IBANs and new idempotency keys, so you can repeat it.

Summary

  • Put cheap checks first and anything that spends an allowance last. The approval guard runs before the velocity limit so rejected requests are free.
  • A Cache with the idempotency key in its key is a workable replay guard. A hit skips everything inside it, including the rate limit.
  • Use Lua for the checks JSONata cannot do, and have it write headers that later If policies read. Always set them, so callers cannot forge them.
  • Write guards as $not(x = 'true'), not x != 'true'.

Limitations and Notes

  • Not run on a gateway. Everything above is design plus offline checks. I expect some of it to need fixing on a first run.
  • Assumptions to confirm on the first run:
    • Invoke forwards the POST body to the backend.
    • $telemetry('client_id') works inside a Cache key and a RateLimitDef.
    • A header set by Lua is visible to a later JSONata If. I verified that Lua can set and read headers, and that a Lua resp.status ends the request. I did not verify the hand-off to JSONata.
    • A RateLimit inside a Cache is skipped on a hit. I measured that in the traffic post, but not with a dynamicValue definition.
  • The idempotency check is a cache with a 120 second lifetime, not a durable store. After that a retry pays again. A bank needs the key held for much longer, in the core system.
  • A same-key, different-amount request is treated as a new payment. A real design would reject it.
  • The bearer token guard checks presence, not validity.
  • The backend is an echo service. It proves what the gateway sent. It does not behave like a payment system.