Tutorial 3: Make your backend accept signed calls
Verified against gamewarden v0.2.0 (see the changelog). About 20 minutes.
The script 03-accept-signed-calls.sh runs the eleven language
examples, checks that this page quotes them correctly, and replays a signed request against
the Go, Python, TypeScript, C#, Java, PHP and Elixir pet shops. CI runs that script.
The gateway signs every call it makes to your backend. Your backend must check that signature before it trusts anything in the request, most of all the player. You will build the check in Go, Python, TypeScript, C#, Java, PHP, Ruby, Elixir, Rust, Dart or Swift (pick yours), test it against a published vector, and watch it refuse a forged request and an idempotent replay.
Prerequisites
Section titled “Prerequisites”- Docker with Compose v2, and the repository cloned.
- Tutorial 2 for the pet shop manifest.
1. What the gateway sends
Section titled “1. What the gateway sends”Five headers on every request:
| Header | Meaning |
|---|---|
X-AG-Key-Id |
which shared secret signed it (so you can rotate) |
X-AG-Timestamp |
Unix seconds when it was signed |
X-AG-Player |
the player this call is for |
X-AG-Idempotency-Key |
unique per call. A repeat must give the same result |
X-AG-Signature |
hex HMAC-SHA256 over the request |
The signature covers a string of eight lines joined by \n: v1, the timestamp, the key id, the
upper-case method, the path with its query, exactly as sent, the player, the idempotency
key, and the hex SHA-256 of the body. The full rules are in the protocol.
2. Four rules for the verifier
Section titled “2. Four rules for the verifier”- Verify before you trust. Treat
X-AG-Playeras the player only after the signature checks out. The signature covers it, so nobody can swap it. - Check the timestamp. Refuse anything more than five minutes from your clock, in either direction. This is what stops an old captured request from working forever.
- Compare in constant time. A plain
==on two strings can leak, through timing, how many leading characters matched. Use the library’s constant-time compare. - Honor the idempotency key. If the gateway retries a call, or someone replays a captured one inside the five minutes, run the action once and return the stored answer. Keep each answer for at least ten minutes, because a timestamp up to five minutes in the future is accepted. Look the key up only after the signature passed, and keep a failed (5xx) call out of the store so a retry can run.
When a request is refused, answer 401 and say nothing about why. Do not tell an attacker which
check failed.
3. The test vector
Section titled “3. The test vector”Every implementation must reproduce this request exactly. It is also in
examples/signing/vector.json and in the protocol:
key id dev-1secret dev-secrettimestamp 1767268800method POSTpath and query /api/v1/pets/feed?src=agentplayer player-7idempotency key idem-0001body {"pet":"rex","food":"fish","amount":2}signature a706e2b8923961ede4fc119424fe81125533df9ca469cdd5ec86663eefbba6deEach example below has a small test that checks this vector, then refuses a tampered signature, player, body and path, an unknown key, a missing header, and a timestamp six minutes off in either direction, then proves that a repeated idempotency key runs the action once.
4. Pick your language
Section titled “4. Pick your language”Each example is one file with no dependencies beyond the language’s standard library (Go also
uses pkg/agentsig from this repository, Rust uses the hmac and sha2 crates, Dart uses the crypto package, and Swift uses swift-crypto). Copy the
file into your backend. The excerpts show the heart of each; the files have the rest. Each sig-* command pulls its language’s image the
first time you run it, so run only the one for your language.
examples/signing/go/sigverify.go. agentsig.Verify checks the timestamp skew, the key, and
compares in constant time.
player, err := agentsig.Verify(r, body, m.SecretFor, m.now(), agentsig.DefaultMaxSkew) if err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) // say nothing about why return } key := r.Header.Get(agentsig.HeaderKeyID) + "/" + r.Header.Get(agentsig.HeaderIdempotency) entry, first := m.claim(key) if !first { <-entry.done // a concurrent first call is still running: wait for its answerdocker compose run --rm sig-goPython
Section titled “Python”examples/signing/python/sigverify.py. Standard library only.
if abs(self.now() - ts) > MAX_SKEW: raise Rejected("timestamp outside the allowed skew") secret = self.secrets.get(h["x-ag-key-id"]) if secret is None: raise Rejected("unknown key") want = sign(secret, ts, h["x-ag-key-id"], method, path, h["x-ag-player"], h["x-ag-idempotency-key"], body) # Constant time: a plain == would leak how many leading characters matched. if not hmac.compare_digest(want, h["x-ag-signature"]): raise Rejected("signature mismatch")docker compose run --rm sig-pythonTypeScript
Section titled “TypeScript”examples/signing/typescript/sigverify.ts. Node’s standard library only. The test runs on Node
22 with its built-in type stripping, so there is no build step.
if (Math.abs(this.now() - ts) > MAX_SKEW) throw new Rejected("timestamp outside the allowed skew"); const secret = this.secrets[h["x-ag-key-id"]]; if (!secret) throw new Rejected("unknown key"); const want = Buffer.from(sign(secret, ts, h["x-ag-key-id"], method, path, h["x-ag-player"], h["x-ag-idempotency-key"], body)); const got = Buffer.from(h["x-ag-signature"]); // Constant time, and only on equal lengths (timingSafeEqual throws otherwise). if (want.length !== got.length || !timingSafeEqual(want, got)) throw new Rejected("signature mismatch");docker compose run --rm sig-typescriptC# (.NET)
Section titled “C# (.NET)”examples/signing/csharp/SigVerify.cs. .NET standard library only. The test is a small console
program, so it needs no NuGet packages and runs offline. It was run with the .NET 8 SDK image.
if (Math.Abs(clock() - ts) > MaxSkew) throw new Rejected("timestamp outside the allowed skew"); if (!secrets.TryGetValue(h["x-ag-key-id"], out var secret)) throw new Rejected("unknown key"); var want = Encoding.ASCII.GetBytes(Sign(secret, ts, h["x-ag-key-id"], method, path, h["x-ag-player"], h["x-ag-idempotency-key"], body)); var got = Encoding.ASCII.GetBytes(h["x-ag-signature"]); // Constant time. FixedTimeEquals returns false for different lengths. if (!CryptographicOperations.FixedTimeEquals(want, got)) throw new Rejected("signature mismatch");docker compose run --rm sig-csharpexamples/signing/java/SigVerify.java. Java 21 standard library only. The test is a plain
main, so it needs no build tool. It was run with the eclipse-temurin:21-jdk image.
if (Math.abs(now.getAsLong() - ts) > MAX_SKEW) throw new Rejected("timestamp outside the allowed skew"); byte[] secret = secrets.get(h.get("x-ag-key-id")); if (secret == null) throw new Rejected("unknown key"); String want = sign(secret, ts, h.get("x-ag-key-id"), method, path, h.get("x-ag-player"), h.get("x-ag-idempotency-key"), body); // Constant time: String.equals would leak how many leading characters matched. if (!MessageDigest.isEqual(want.getBytes(StandardCharsets.UTF_8), h.get("x-ag-signature").getBytes(StandardCharsets.UTF_8))) { throw new Rejected("signature mismatch"); }docker compose run --rm sig-javaexamples/signing/php/SigVerify.php. PHP 8.2 or later, standard library only. PHP usually starts
fresh for every request, so stored answers for repeated idempotency keys cannot live in memory:
implement its IdempotencyStore interface with your database, Redis or APCu.
$secret = $this->secrets[$h['x-ag-key-id']] ?? null; if ($secret === null) { throw new Rejected('unknown key'); } $want = self::sign($secret, $ts, $h['x-ag-key-id'], $method, $path, $h['x-ag-player'], $h['x-ag-idempotency-key'], $body); // Constant time: === would leak how many leading characters matched. if (!hash_equals($want, $h['x-ag-signature'])) {docker compose run --rm sig-phpexamples/signing/ruby/sigverify.rb. Ruby standard library only (openssl). The test uses
minitest, which ships with Ruby.
raise Rejected, "timestamp outside the allowed skew" if (@now.call - ts).abs > MAX_SKEW secret = @secrets[h["x-ag-key-id"]] raise Rejected, "unknown key" if secret.nil? want = SigVerify.sign(secret, ts, h["x-ag-key-id"], method, path, h["x-ag-player"], h["x-ag-idempotency-key"], body) # Constant time: == would leak how many leading characters matched. raise Rejected, "signature mismatch" unless OpenSSL.secure_compare(want, h["x-ag-signature"])docker compose run --rm sig-rubyElixir
Section titled “Elixir”examples/signing/elixir/sigverify.ex. Elixir 1.18 or later, Erlang/OTP only (:crypto). The
stored answers live in a small GenServer. The test uses ExUnit and runs as a plain script, no Mix.
not Map.has_key?(v.secrets, h["x-ag-key-id"]) -> {:error, "unknown key"}
not signature_ok?(v.secrets[h["x-ag-key-id"]], method, path, h, body) -> {:error, "signature mismatch"} want = sign(secret, ts, key_id, method, path, player, idem, body) got = h["x-ag-signature"] # Constant time: == would leak how many leading characters matched. # :crypto.hash_equals/2 raises on unequal sizes, so compare the sizes first. byte_size(want) == byte_size(got) and :crypto.hash_equals(want, got)docker compose run --rm sig-elixirexamples/signing/rust/src/lib.rs. A small Cargo crate. Rust’s standard library has no HMAC, so
this example uses two crates, hmac and sha2, and nothing else. verify_slice from hmac
compares in constant time. The versions are pinned in Cargo.toml and Cargo.lock. The test is
cargo test, run with the rust:1.91-slim-bookworm image.
if ((self.now)() - ts).abs() > MAX_SKEW { return Err(Rejected("timestamp outside the allowed skew")); } let secret = self.secrets.get(get("x-ag-key-id")).ok_or(Rejected("unknown key"))?; let signed = signed_string(ts, get("x-ag-key-id"), method, path, get("x-ag-player"), get("x-ag-idempotency-key"), body); let got = unhex(get("x-ag-signature")).ok_or(Rejected("signature mismatch"))?; // Constant time: verify_slice does not stop at the first differing byte, and it // refuses a signature of the wrong length. mac(secret, &signed).verify_slice(&got).map_err(|_| Rejected("signature mismatch"))?;docker compose run --rm sig-rustexamples/signing/dart/lib/sigverify.dart. A small Dart package. Dart’s core libraries have no
HMAC, so this example uses one package, crypto, and nothing else. It compares in constant time
itself: equal lengths, then XOR every byte. The versions are pinned in pubspec.yaml and
pubspec.lock. The test uses package:test, run with the dart:3.10 image.
if ((now() - ts).abs() > maxSkew) throw Rejected('timestamp outside the allowed skew'); final secret = secrets[get('x-ag-key-id')]; if (secret == null) throw Rejected('unknown key'); // Constant time: == would leak how many leading characters matched. if (!constantTimeEquals(utf8.encode(want), utf8.encode(get('x-ag-signature')))) { throw Rejected('signature mismatch'); }bool constantTimeEquals(List<int> a, List<int> b) { if (a.length != b.length) return false; var diff = 0; for (var i = 0; i < a.length; i++) { diff |= a[i] ^ b[i]; } return diff == 0;}docker compose run --rm sig-dartexamples/signing/swift/Sources/SigVerify/SigVerify.swift. A small Swift package. CryptoKit is
Apple-only, so this example uses swift-crypto (import Crypto), the same API on Linux, and
nothing else. The signature is decoded from hex by hand, and a wrong length is refused before
isValidAuthenticationCode compares in constant time. The stored answers live in an actor. The
version is pinned in Package.swift and Package.resolved. The test is swift test, run with the
swift:6.3.3-bookworm image.
// Refuse a signature that is not hex or not exactly one SHA-256 long. guard let got = unhex(get("x-ag-signature")), got.count == SHA256.byteCount else { throw Rejected(reason: "signature mismatch") } // Constant time: isValidAuthenticationCode does not stop at the first differing byte. guard HMAC<SHA256>.isValidAuthenticationCode(got, authenticating: Data(signed.utf8), using: key) else { throw Rejected(reason: "signature mismatch") }docker compose run --rm sig-swiftAll eleven print passing tests. If you use another language, the signed string and the four rules above are all you need, and the vector tells you when you got it right.
5. Put it in a real backend
Section titled “5. Put it in a real backend”examples/pet-backend-go, examples/pet-backend-python, examples/pet-backend-typescript,
examples/pet-backend-csharp, examples/pet-backend-java, examples/pet-backend-php and
examples/pet-backend-elixir are the pet shop from tutorial 2, each with the verifier in front of
every route. Run one behind a gateway:
docker compose -f examples/pet-backend-go/compose.yml up --build -dThe gateway is on 127.0.0.1:8090 and the backend on 127.0.0.1:9190 (loopback only, so you
can poke it directly). A tool call works end to end because the gateway signs it:
curl -s -X POST -H 'X-Dev-Player: p1' \ -d '{"arguments":{"pet":"rex","food":"fish","amount":2}}' \ http://127.0.0.1:8090/v1/tools/feed_pet/call{"ok":true,"data":{"coins":96,"hunger":60,"pet":"rex"}}Now go around the gateway. An unsigned request to the backend is refused, and so is one that only pretends to be a player:
curl -s -o /dev/null -w '%{http_code}\n' -X POST -d '{"pet":"rex","food":"fish","amount":9}' \ http://127.0.0.1:9190/api/v1/pets/feedcurl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'X-AG-Player: p1' -d '{"pet":"rex","food":"fish","amount":9}' \ http://127.0.0.1:9190/api/v1/pets/feed401401Replay a signed request
Section titled “Replay a signed request”The helper docs/tutorials/sign-request.py signs a request with the Python verifier’s sign
function, so you can play the gateway. It runs in a container, so you need no Python on your
machine. Sign one feed request and send it twice:
body='{"pet":"rex","food":"fish","amount":1}'headers=$(docker run --rm -v "$PWD/examples/signing/python:/sig:ro" -v "$PWD/docs/tutorials:/t:ro" \ python:3.13-slim python /t/sign-request.py POST /api/v1/pets/feed p1 replay-1 "$body")args=(); while IFS= read -r h; do args+=(-H "$h"); done <<< "$headers"
curl -si -X POST "${args[@]}" -d "$body" http://127.0.0.1:9190/api/v1/pets/feedcurl -si -X POST "${args[@]}" -d "$body" http://127.0.0.1:9190/api/v1/pets/feedBoth answers carry the same body. The second adds X-Idempotent-Replay: true, and the coins
dropped once, not twice. Change one character of $body after signing and you get 401: the
signature covers the body.
The idempotency key replay-1 is fixed, so on a second run of this block the first call is already
a replay. Change replay-1 to a new key to see the first call run for real.
Clean up with docker compose -f examples/pet-backend-go/compose.yml down. The other
backends work the same way with their own compose.yml. The PHP one keeps its state and its
stored answers in SQLite, because PHP starts fresh for every request. The C# one is an ASP.NET
Core minimal API that reads the body as raw bytes before it checks the signature. The Elixir
one runs on OTP’s built-in :httpd, which hands it the raw path and body, with no Mix
dependencies.
What you learned
Section titled “What you learned”- Verify the signature and the timestamp before you trust the player, compare in constant time,
and answer
401with no detail. - Store the answer per idempotency key for at least ten minutes and return it on repeats.
- A published test vector lets you check any implementation, in any language.