Skip to Content
App AttestationChecking tokens at the gateway

Checking tokens at the gateway

For whoever runs the API gateway: nginx, Envoy, Kong, Cloudflare Workers or AWS API Gateway (HTTP API). At the end of this page, your gateway refuses requests without a valid attestation token on the routes you choose, passes the others to your API with the device key in a header, and you have tested it with a valid and an invalid token.

The recipes apply the same verification steps as Verifying tokens in your API. Read that page’s token format and binding sections first.

Gateway or API

Gateway checks (recipes)API checks
Requests without the headerAlways refusedYour rule, per endpoint
tp.result fail (monitor mode)Passed to the API, not checkedLogged, then your rule
Monitor phaseNot suitable as shipped: it refuses every app version without attestationSuitable
Assertions (POST /v1/assertion)Not handledHandled
One place for many servicesYesOne check per service

A common setup: check in the API while the policy is in monitor mode, and add the gateway recipe on a route once you refuse unattested requests there. See Rolling out.

Before you start

  • A verifier serving your published policy. See Deploying the verifier.
  • The values from the project’s Attestation page, Go-live guide tab, Step by step, step Verify tokens in your backend (pick the Environment first if you have several):
    • Issuer (iss): the verifier’s TRUSTPIN_TOKEN_ISSUER, which the deployment bundle sets to the environment’s public URL, for example https://attest.example.com; tprn::attest::<organization id>::<project id> if no URL is set;
    • Audience (aud): the verifier’s TRUSTPIN_TOKEN_AUDIENCE, by default tprn::project::<organization id>::<project id>;
    • Project (tp.prj): the same tprn::project::… name;
    • JWKS URL: <verifier URL>/.well-known/jwks.json.
  • A network path from the gateway to the JWKS URL. Cloudflare and AWS Lambda fetch it over the internet unless you route them otherwise.
  • Apps that bind tokens to the Authorization header, or don’t bind. The recipes hash Authorization; for any other bound value, change the recipe or check in the API.

What every recipe checks

  • An ES256 signature with a key from the verifier’s JWKS, chosen by kid. The JWKS is cached for 5 minutes and fetched again when an unknown kid arrives, at most once every 30 seconds, with a 5-second timeout. Envoy refreshes on a schedule instead; see its section.
  • The header typ is trustpin-attest+jwt.
  • iss, aud, and exp with 60 seconds of leeway.
  • tp.prj is your project. By default it is taken from the audience when the audience has the tprn::project:: form.
  • No token with tp.env == "debug".
  • bind, when present, equals base64url(SHA-256(<Authorization header value>)). With require-binding on, for policies with Require token binding, a token without bind is refused.

A request that passes reaches your API with an X-TrustPin-Sub header, the device key (sub), set by the gateway over any value the client sent. The TrustPin-Attestation header is passed on too. On AWS, sub is in the authorizer context instead of a header.

What the recipes don’t do:

  • They refuse a request without the header, on every route they cover, whatever the policy’s mode.
  • They don’t read tp.result. A verified token with tp.result fail, issued in monitor mode, reaches your API like any other. To log it, or to cut such tokens off right after switching to enforce, read tp.result in the API from the forwarded header (safe without re-verifying only if the API can’t be reached except through the gateway), or add the check to the recipe.
  • They don’t verify assertions. Do that in the API; see Assertions for sensitive operations.
  • They always refuse debug tokens, so simulator and emulator builds can’t pass them.

Never put a recipe in front of the verifier’s own routes. The SDK’s calls to the verifier carry no token, so they would all be refused. Apply the recipe only to your API’s routes.

Downloads

GatewayHowFilesTested
nginxauth_request to an njs module (WebCrypto)nginx.conf, trustpin_attest.jsIn Docker (nginx:1.31-alpine), in the verifier’s CI
Envoyjwt_authn for the signature, iss, aud and exp; a Lua filter for typ, tp.prj, debug tokens and bindingenvoy.yaml, trustpin_attest.luaIn Docker (envoyproxy/envoy:v1.39-latest), in the verifier’s CI
Kong (open source, 3.9)A pre-function plugin using Kong’s bundled OpenSSL bindingskong.yml, trustpin_attest.lua, render.pyIn Docker (kong:3.9), in the verifier’s CI
CloudflareA Worker on the API route (WebCrypto)worker.mjs, wrangler.tomlThe Worker’s check under Node; deployment untested
AWS API Gateway (HTTP API)A Lambda REQUEST authorizer (jose), with a SAM templateindex.mjs, template.yaml, package.json, package-lock.jsonThe handler under Node; deployment untested

The recipes come from verifier 1.0.0. The CI runs them against valid, forged, expired, foreign-project, debug, tampered, unsigned and mis-bound tokens, and a request without the header. Each file uses placeholders: https://attest.example.com for the verifier, tprn::project::org_example::prj_example for the audience, and the test host issuer:18300 for your API and the verifier. README.md comes with them.

These samples may be copied and modified freely, under the verifier licence’s Code Samples clause.

nginx

Needs nginx with the njs module (0.8 or later, for js_shared_dict_zone). The official nginx images include it.

  1. Download nginx.conf and trustpin_attest.js. Put trustpin_attest.js in /etc/nginx/njs/, the js_path.

  2. Merge nginx.conf into your configuration:

    • load_module at the top level;
    • in http: js_path, js_import, js_shared_dict_zone, resolver and the trustpin_verifier upstream;
    • in your server: the four set lines and the /_trustpin_check and /_trustpin_jwks locations;
    • in each location you protect: auth_request, auth_request_set and proxy_set_header X-TrustPin-Sub.
  3. Set the values:

    DirectiveValue
    set $trustpin_issuerIssuer (iss)
    set $trustpin_audienceAudience (aud)
    set $trustpin_projectProject (tp.prj), or "" to take it from the audience
    set $trustpin_require_bindon when Require token binding is on, else off
    upstream trustpin_verifierYour verifier’s public listener, for example server attest.internal:8080;
    resolverYour DNS resolver (the recipe has Docker’s)
  4. Run nginx -t, then nginx -s reload.

The JWKS is fetched over plain HTTP from the verifier’s public listener (port 8080 by default), which suits a gateway on the same private network. To fetch it over HTTPS, use proxy_pass https://attest.example.com/.well-known/jwks.json; in /_trustpin_jwks, with proxy_ssl_server_name on;, proxy_ssl_verify on; and proxy_ssl_trusted_certificate naming your CA bundle. The JWKS is shared by all workers; use one zone per verifier. A refused request is logged at warn as trustpin attestation rejected: <reason>.

Envoy

  1. Download envoy.yaml and trustpin_attest.lua. The Lua file is read from /etc/envoy/trustpin_attest.lua; change default_source_code.filename if you put it elsewhere.
  2. In envoy.yaml, under the jwt_authn provider trustpin, set issuer to Issuer (iss), audiences to Audience (aud), and remote_jwks.http_uri.uri to the JWKS URL. Point the trustpin_verifier cluster at your verifier and the api cluster at your API. For an https JWKS URL, give trustpin_verifier a TLS transport_socket.
  3. In trustpin_attest.lua, set PROJECT to Project (tp.prj). It is preset to the placeholder audience, so if you leave it, every token is refused as wrong project. Set REQUIRE_BIND = true when Require token binding is on.
  4. Validate with envoy --mode validate -c envoy.yaml, then restart Envoy.

jwt_authn fetches the JWKS in the background, at start and every cache_duration (5 minutes), never on a request. After the verifier’s signing keys rotate, tokens signed with the new key are refused until the next refresh; lower cache_duration if that window matters. A token for another audience gets 403; other failures get 401. The Lua filter logs its refusals as trustpin attestation rejected: <reason>; jwt_authn names its own in the response body, for example Jwt is missing.

Kong

The recipe is for open-source Kong 3.9 in DB-less mode, and needs untrusted_lua = on. Kong Enterprise’s OpenID Connect plugin can check the signature and claims natively, but the binding still needs the pre-function.

  1. Download kong.yml, trustpin_attest.lua and render.py into one folder.

  2. At the top of trustpin_attest.lua, set JWKS_URL, ISSUER, AUDIENCE, PROJECT ("" to take it from the audience) and REQUIRE_BIND.

  3. In kong.yml, set the service url to your API, and the route paths to the routes you protect.

  4. Run python3 render.py. It embeds the Lua into kong.yml; run it again after every change to the Lua.

  5. Start Kong with the file:

    docker run -d --name kong -p 8000:8000 -v "$PWD":/kong:ro \ -e KONG_DATABASE=off -e KONG_DECLARATIVE_CONFIG=/kong/kong.yml \ -e KONG_UNTRUSTED_LUA=on kong:3.9

The JWKS is kept in Kong’s cache, shared by the workers. Refused requests get 401 and are logged as trustpin attestation rejected: <reason>.

Cloudflare Workers

  1. Download worker.mjs and wrangler.toml into one folder.

  2. In wrangler.toml, set the [vars]:

    VariableValue
    TRUSTPIN_JWKS_URLJWKS URL (public https://)
    TRUSTPIN_ISSUERIssuer (iss)
    TRUSTPIN_AUDIENCEAudience (aud)
    TRUSTPIN_PROJECTProject (tp.prj), or "" to take it from the audience
    TRUSTPIN_REQUIRE_BIND"true" when Require token binding is on
  3. Uncomment [[routes]] and set pattern and zone_name to your API’s protected routes, or add the route in the Cloudflare dashboard.

  4. Run npx wrangler deploy. Watch refusals with npx wrangler tail; they are logged as trustpin attestation rejected: <reason>.

A request that passes is forwarded to your origin with X-TrustPin-Sub; a refused one gets 401. The Worker’s check is tested; the deployment itself isn’t.

AWS API Gateway (HTTP API)

  1. Download index.mjs, template.yaml, package.json and package-lock.json into one folder.

  2. Run npm install --omit=dev.

  3. Run sam deploy --guided, and answer the parameters:

    ParameterValue
    JwksUrlJWKS URL
    IssuerIssuer (iss)
    AudienceAudience (aud)
    ProjectProject (tp.prj), or empty to take it from the audience
    RequireBindtrue when Require token binding is on
    BackendUrlYour API, for example https://api.example.com

The template creates an HTTP API whose every route requires the authorizer, proxying to BackendUrl. Its limits:

  • TrustPin-Attestation and Authorization are the authorizer’s identity sources, so API Gateway answers 401 without calling the authorizer when either is missing. A failed check gets 403.
  • The authorizer must not be cached (ReauthorizeEvery: 0), because the binding depends on the Authorization header.
  • The device key is returned in the authorizer context (sub, and result), not as a header; the template doesn’t forward it to your API.
  • Refusals are logged to the function’s CloudWatch log as trustpin attestation rejected: <reason>.
  • The handler is tested; the deployment itself isn’t.

HTTP API’s built-in JWT authorizer can check the signature, iss, aud and exp through <verifier>/.well-known/openid-configuration when the issuer is the verifier’s https:// URL, but not typ, tp.prj, debug tokens or the binding. Use the recipe instead, or add those checks in the API. The same holds for other gateways’ built-in JWT checks.

Test it

You need a token from your app on a real device: a debug build that prints the SDK’s getToken() result (Swift, Kotlin, Flutter, React Native). A simulator or emulator token is a debug token, which every recipe refuses. If the app binds tokens, note the Authorization value it sent with that token.

API=https://api.example.com/protected/path # a route behind the recipe TOKEN='<token from the app>' AUTH='Bearer <the value the app sent, or any value if the app does not bind>' # 1. No header: 401 curl -s -o /dev/null -w '%{http_code}\n' "$API" -H "Authorization: $AUTH" # 2. Invalid token: 401 (AWS: 403) curl -s -o /dev/null -w '%{http_code}\n' "$API" -H "Authorization: $AUTH" -H 'TrustPin-Attestation: not-a-token' # 3. Valid token: your API's answer, and your API sees X-TrustPin-Sub curl -s -o /dev/null -w '%{http_code}\n' "$API" -H "Authorization: $AUTH" -H "TrustPin-Attestation: $TOKEN"

Then check one failure the gateway must catch with a real token: if the app binds, repeat call 3 with another Authorization value (401, AWS 403). Otherwise, repeat it after the token expires plus 60 seconds. Each refusal appears in the gateway’s log with its reason.

Troubleshooting

SymptomLikely causeFix
Every valid token is refused with wrong iss, wrong aud or wrong project (on AWS, unexpected "iss" claim value or similar)The recipe’s issuer, audience or project differs from the verifier’sCopy them from the Go-live guide for the right environment. On Envoy, check PROJECT in the Lua
unknown kid or a JWKS fetch error in the logThe gateway can’t reach the JWKS URL, or the token comes from another environment’s verifierCheck the upstream or URL with curl from the gateway’s host
Envoy answers 403The token’s audience isn’t the one configuredSet audiences to Audience (aud)
Envoy refuses tokens just after a key rotationThe JWKS refreshes on its schedule onlyWait for the next refresh, or lower cache_duration
The app can’t get a token once the recipe is deployedThe recipe sits in front of the verifier’s routesExclude the verifier’s host or paths
bound to another sessionThe gateway hashes a different value from the one the app boundBind to Authorization in the app, and pass that header to the gateway unchanged
AWS answers 401 to a request with a tokenThe request has no Authorization headerSend one, or change the identity sources
Older app versions are refused while the policy is in monitor modeThe recipes refuse requests without the headerCheck tokens in the API during monitor

Next steps