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 header | Always refused | Your rule, per endpoint |
tp.result fail (monitor mode) | Passed to the API, not checked | Logged, then your rule |
| Monitor phase | Not suitable as shipped: it refuses every app version without attestation | Suitable |
Assertions (POST /v1/assertion) | Not handled | Handled |
| One place for many services | Yes | One 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 examplehttps://attest.example.com;tprn::attest::<organization id>::<project id>if no URL is set; - Audience (aud): the verifier’s
TRUSTPIN_TOKEN_AUDIENCE, by defaulttprn::project::<organization id>::<project id>; - Project (tp.prj): the same
tprn::project::…name; - JWKS URL:
<verifier URL>/.well-known/jwks.json.
- Issuer (iss): the verifier’s
- 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
Authorizationheader, or don’t bind. The recipes hashAuthorization; 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 unknownkidarrives, at most once every 30 seconds, with a 5-second timeout. Envoy refreshes on a schedule instead; see its section. - The header
typistrustpin-attest+jwt. iss,aud, andexpwith 60 seconds of leeway.tp.prjis your project. By default it is taken from the audience when the audience has thetprn::project::form.- No token with
tp.env == "debug". bind, when present, equalsbase64url(SHA-256(<Authorization header value>)). With require-binding on, for policies with Require token binding, a token withoutbindis 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 withtp.resultfail, issued in monitor mode, reaches your API like any other. To log it, or to cut such tokens off right after switching to enforce, readtp.resultin 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
| Gateway | How | Files | Tested |
|---|---|---|---|
| nginx | auth_request to an njs module (WebCrypto) | nginx.conf, trustpin_attest.js | In Docker (nginx:1.31-alpine), in the verifier’s CI |
| Envoy | jwt_authn for the signature, iss, aud and exp; a Lua filter for typ, tp.prj, debug tokens and binding | envoy.yaml, trustpin_attest.lua | In 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 bindings | kong.yml, trustpin_attest.lua, render.py | In Docker (kong:3.9), in the verifier’s CI |
| Cloudflare | A Worker on the API route (WebCrypto) | worker.mjs, wrangler.toml | The Worker’s check under Node; deployment untested |
| AWS API Gateway (HTTP API) | A Lambda REQUEST authorizer (jose), with a SAM template | index.mjs, template.yaml, package.json, package-lock.json | The 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.
-
Download
nginx.confandtrustpin_attest.js. Puttrustpin_attest.jsin/etc/nginx/njs/, thejs_path. -
Merge
nginx.confinto your configuration:load_moduleat the top level;- in
http:js_path,js_import,js_shared_dict_zone,resolverand thetrustpin_verifierupstream; - in your
server: the foursetlines and the/_trustpin_checkand/_trustpin_jwkslocations; - in each location you protect:
auth_request,auth_request_setandproxy_set_header X-TrustPin-Sub.
-
Set the values:
Directive Value set $trustpin_issuerIssuer (iss) set $trustpin_audienceAudience (aud) set $trustpin_projectProject (tp.prj), or ""to take it from the audienceset $trustpin_require_bindonwhen Require token binding is on, elseoffupstream trustpin_verifierYour verifier’s public listener, for example server attest.internal:8080;resolverYour DNS resolver (the recipe has Docker’s) -
Run
nginx -t, thennginx -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
- Download
envoy.yamlandtrustpin_attest.lua. The Lua file is read from/etc/envoy/trustpin_attest.lua; changedefault_source_code.filenameif you put it elsewhere. - In
envoy.yaml, under thejwt_authnprovidertrustpin, setissuerto Issuer (iss),audiencesto Audience (aud), andremote_jwks.http_uri.urito the JWKS URL. Point thetrustpin_verifiercluster at your verifier and theapicluster at your API. For anhttpsJWKS URL, givetrustpin_verifiera TLStransport_socket. - In
trustpin_attest.lua, setPROJECTto Project (tp.prj). It is preset to the placeholder audience, so if you leave it, every token is refused aswrong project. SetREQUIRE_BIND = truewhen Require token binding is on. - 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.
-
Download
kong.yml,trustpin_attest.luaandrender.pyinto one folder. -
At the top of
trustpin_attest.lua, setJWKS_URL,ISSUER,AUDIENCE,PROJECT(""to take it from the audience) andREQUIRE_BIND. -
In
kong.yml, set the serviceurlto your API, and the routepathsto the routes you protect. -
Run
python3 render.py. It embeds the Lua intokong.yml; run it again after every change to the Lua. -
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
-
Download
worker.mjsandwrangler.tomlinto one folder. -
In
wrangler.toml, set the[vars]:Variable Value TRUSTPIN_JWKS_URLJWKS URL (public https://)TRUSTPIN_ISSUERIssuer (iss) TRUSTPIN_AUDIENCEAudience (aud) TRUSTPIN_PROJECTProject (tp.prj), or ""to take it from the audienceTRUSTPIN_REQUIRE_BIND"true"when Require token binding is on -
Uncomment
[[routes]]and setpatternandzone_nameto your API’s protected routes, or add the route in the Cloudflare dashboard. -
Run
npx wrangler deploy. Watch refusals withnpx wrangler tail; they are logged astrustpin 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)
-
Download
index.mjs,template.yaml,package.jsonandpackage-lock.jsoninto one folder. -
Run
npm install --omit=dev. -
Run
sam deploy --guided, and answer the parameters:Parameter Value JwksUrlJWKS URL IssuerIssuer (iss) AudienceAudience (aud) ProjectProject (tp.prj), or empty to take it from the audience RequireBindtruewhen Require token binding is onBackendUrlYour 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-AttestationandAuthorizationare the authorizer’s identity sources, so API Gateway answers401without calling the authorizer when either is missing. A failed check gets403.- The authorizer must not be cached (
ReauthorizeEvery: 0), because the binding depends on theAuthorizationheader. - The device key is returned in the authorizer context (
sub, andresult), 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
| Symptom | Likely cause | Fix |
|---|---|---|
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’s | Copy 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 log | The gateway can’t reach the JWKS URL, or the token comes from another environment’s verifier | Check the upstream or URL with curl from the gateway’s host |
Envoy answers 403 | The token’s audience isn’t the one configured | Set audiences to Audience (aud) |
| Envoy refuses tokens just after a key rotation | The JWKS refreshes on its schedule only | Wait for the next refresh, or lower cache_duration |
| The app can’t get a token once the recipe is deployed | The recipe sits in front of the verifier’s routes | Exclude the verifier’s host or paths |
bound to another session | The gateway hashes a different value from the one the app bound | Bind to Authorization in the app, and pass that header to the gateway unchanged |
AWS answers 401 to a request with a token | The request has no Authorization header | Send one, or change the identity sources |
| Older app versions are refused while the policy is in monitor mode | The recipes refuse requests without the header | Check tokens in the API during monitor |
Next steps
- Rolling out: monitor to enforce: measure, switch the policy to enforce, and refuse endpoint by endpoint.
- Verifying tokens in your API, for monitor-mode logging,
tp.resultand assertions.