Six policies decide what happens when an assembly is not a straight line: If, Throw, Return, Try, Or and Block. This post runs each one against a real gateway, with the YAML from API Studio code view and the response that came back.

The companion posts cover the switch policy, for choosing between several cases, and JSONata, where $error is the quick way to fail.

The test project

One API Studio project, one API called nano-flow, one operation per policy. There is no backend. A set policy builds each response.

ExtractIdentity, Authenticate and Authorize check client credentials, then an OperationSwitch sends each operation to its own policies.

Every call goes to the published product URL with the client credentials of a subscribed application:

curl -s \
  -H "X-IBM-Client-Id: <client-id>" \
  -H "X-IBM-Client-Secret: <client-secret>" \
  "https://<product>-<catalog>-<org>.nanogw.<ingress-domain>/1.0.0/nano-flow/guard/if"

Which policy for which job:

Need Policy What the caller sees
Run a block when a condition holds If Nothing. The block is skipped
Fail with a status and body you choose Throw That status and body
Stop early with a success Return The response built so far
Recover from a failure Try The response from the catch block
Try a second option Or The first option that succeeds
Reject an attacker Block 403, no backend call

Example 1: If

If has a JSONata condition and an execute list that runs when it is true. There is no else. For two branches use switch.

kind: If
spec:
  condition: $exists($header('request', 'X-Mode'))
  execute:
    - $ref: nanogw-policy-samples:nano-flow-set-guard:1.0.0

The policy in the block copies the X-Mode header into a new X-Guard-Mode request header:

kind: Set
spec:
  valueType: jsonata
  messageHeader:
    messageName: request
    action: set
    headerName: X-Guard-Mode
    value: $header('request', 'X-Mode')

A second set after the If builds the response and reports whether the block ran:

kind: Set
spec:
  valueType: jsonata
  messageBody:
    messageName: response
    value: |
      {
        "mode": $header('request', 'X-Mode'),
        "guarded": $exists($header('request', 'X-Guard-Mode')),
        "assemblies": "if condition true -> block executed"
      }

With the header:

curl ... -H 'X-Mode: strict' "https://<gateway-host>/1.0.0/nano-flow/guard/if"
HTTP/2 200

{"mode":"strict","guarded":true,"assemblies":"if condition true -> block executed"}

Without it:

HTTP/2 200

{"guarded":false,"assemblies":"if condition true -> block executed"}

The condition was false, so the block did not run and guarded is false. Nothing failed. The set after the If ran regardless, which is why the static text assemblies is still there and is now wrong. A skipped If is silent, and anything after it still runs.

Example 2: Throw

Throw ends the assembly with an error you define. CustomError takes a status and a message. The message becomes the response body.

kind: Throw
spec:
  error:
    CustomError:
      message: amount must be greater than zero
      messageType: plain
      status: 422

An If on the parsed body decides whether to throw:

kind: If
spec:
  condition: $exists($body('request').amount) and $number($body('request').amount) < 0
  execute:
    - $ref: nanogw-policy-samples:nano-flow-throw-amount:1.0.0

The operation runs a parse policy first, then this If, then a set that answers when the amount is fine.

curl ... -X POST -H 'Content-Type: application/json' -d '{"amount":-5}' \
  "https://<gateway-host>/1.0.0/nano-flow/error/custom"
HTTP/2 422

amount must be greater than zero

With {"amount":10}:

HTTP/2 200

{"amount":10,"accepted":true}

messageType: plain sent the string as the body, not JSON. This is what Throw gives you that $error does not. $error always returned a plain 500 in the JSONata post. The reference also lists BadRequestError, ConnectionError, LimitExceededError and ValidateError. A Throw with no error re-throws the current error. That is only useful inside a catch block, and I did not test it.

Example 3: Return

Return ends the assembly with a success at the point it runs. Anything after it is skipped, including the policy that would have produced the normal response.

kind: If
spec:
  condition: $queryParameter('request', 'skip') = 'true'
  execute:
    - $ref: nanogw-policy-samples:nano-flow-set-early:1.0.0
    - $ref: nanogw-policy-samples:nano-flow-return:1.0.0
kind: Return
spec:
  level: 2

After the If comes the normal response:

kind: Set
spec:
  valueType: jsonata
  messageBody:
    messageName: response
    value: |
      { "path": "normal", "tail": "reached" }
curl ... "https://<gateway-host>/1.0.0/nano-flow/flow/early-return?skip=true"
HTTP/2 200

{"path":"short-circuit","tail":"not reached"}

Without skip:

{"path":"normal","tail":"reached"}

With skip=true the first set wrote its body, Return stopped the assembly and the normal set never ran. This is how a cache hit, a health probe or a deprecation notice answers without going further.

level is optional. The reference describes it only as a hierarchical level and says no more. I used 2, because the Return sits inside an If inside the operation switch case, and it ended the whole request. I did not test other values.

Example 4: Try, catch and finally

Try runs execute. If a policy in it fails, the matching catch block runs. finally runs either way.

kind: Try
spec:
  execute:
    - $ref: nanogw-policy-samples:nano-flow-throw-unavailable:1.0.0
  catch:
    - errors:
        - CustomError
      execute:
        - $ref: nanogw-policy-samples:nano-flow-set-recovered:1.0.0
  finally:
    - $ref: nanogw-policy-samples:nano-flow-set-finally-header:1.0.0

The execute block throws a CustomError with status 503. The catch block writes the recovery response. The finally block sets a request header so a later policy can prove it ran:

kind: Set
spec:
  messageHeader:
    messageName: request
    action: set
    headerName: X-Finally
    value: 'ran'

A last set builds the final response and reads the header back:

kind: Set
spec:
  valueType: jsonata
  messageBody:
    messageName: response
    value: |
      {
        "recovered": true,
        "caught": "CustomError",
        "finallyRan": $exists($header('request', 'X-Finally'))
      }
HTTP/2 200

{"recovered":true,"caught":"CustomError","finallyRan":true}

The caller got 200, not the 503. errors lists the error types to handle. Leave it out and the block catches everything. That is the usual shape for turning any backend failure into a friendly response.

I used the finally block for bookkeeping only. If a set in finally wrote the response body, it would overwrite whatever execute or catch produced.

Example 5: Or

Or runs its options in order and keeps the first one that does not fail. Each option is a list of policies, so an option can be a small assembly.

kind: Or
spec:
  options:
    - - $ref: nanogw-policy-samples:nano-flow-throw-primary:1.0.0
    - - $ref: nanogw-policy-samples:nano-flow-set-fallback:1.0.0

The first option throws a ConnectionError:

kind: Throw
spec:
  error:
    ConnectionError:
      cause: primary source unavailable
      causeType: plain

The second option is a set that answers:

HTTP/2 200

{"source":"fallback","attempts":2}

The source and attempts values are written by the second set. Or does not tell you which option won. Record that in the options themselves if you need it. The reference says options needs at least two entries.

Use Or for a choice between equivalent sources, like two backends. Use Try when you need to handle the failure itself.

Example 6: Block

Block filters out attackers, not bad contracts. The reference is clear that Validate is for contract checks, such as a header that must be present.

kind: Block
spec:
  header:
    denyList:
      - name: X-Attack
        value: '1'

Choose one target per policy: ip, header, queryParam or cookie. Inside it, choose one mode:

Mode Behaviour
denyList Block when a key and value match. Unknown keys pass. An empty list blocks nothing
allowList Allow only the keys listed. Anything else is blocked. An empty list blocks everything

The reference page also describes a third mode, constraints. I did not use it.

The Block is first in the sequence, and a set that builds the allowed response follows it:

curl ... -H 'X-Attack: 1' "https://<gateway-host>/1.0.0/nano-flow/security/block"
HTTP/2 403

Forbidden

A normal request:

HTTP/2 200

{"allowed":true,"note":"no attack signature present"}

The attacker gets a bare Forbidden. There is no JSON body and nothing to say which rule matched. The backend is never reached. Block only protects what comes after it in the sequence, so put it first.

Summary

  • If has no else and a skipped block is silent. Anything after it still runs.
  • Use Throw when the client needs a specific status and body. Use Return when the answer is a success.
  • Use Try to handle a failure and Or to choose between equivalent options.
  • Put Block before everything else in the sequence.

Limitations and Notes

  • Tested on a DataPower Nano Gateway with the API Connect 12.1 documentation set. Check the version you run.
  • Not tested: Throw with BadRequestError, LimitExceededError or ValidateError, a bare Throw, a catch block that itself throws, Return with other level values, Block on ip, queryParam or cookie, allowList and regex values.
  • I did not look at the gateway log, so I cannot show what it records for a blocked request.