Sikau

Project: A secure API gateway · Day 1 · about 40 min

Signed requests and replays

HMAC-sign each request's canonical form; reject stale, forged and replayed ones.

Three courses, one secure service

This combined project brings Computer networks, WebAssembly and Security together: an API gateway that accepts signed, encrypted HTTP requests carrying formulas, and runs them as sandboxed WebAssembly. First: prove each request came from a trusted client — and wasn't recorded and replayed.

  • Day 1: signed requests with replay protection
  • Day 2: encrypted payloads with AES-GCM
  • Day 3: sandboxed wasm plugins
  • Day 4: the secure gateway

Sign the canonical request

const canonical = (r) => `${r.method}\n${r.path}\n${r.timestamp}\n${r.nonce}\n${r.body}`;

async function signRequest(req, secret) {
  return { ...req, signature: await hmacHex(secret, canonical(req)) };
}

function createVerifier(secret, { windowSeconds = 300 } = {}) {
  const seen = new Set();
  return {
    async verify(req, now) {
      if (!(Math.abs(now - req.timestamp) <= windowSeconds)) return { ok: false, error: "Stale request" };
      if (!safeEqual(await hmacHex(secret, canonical(req)), req.signature)) return { ok: false, error: "Bad signature" };
      if (seen.has(req.nonce)) return { ok: false, error: "Replay" }; // only remember nonces of genuine requests
      seen.add(req.nonce);
      return { ok: true };
    },
  };
}

The rest of this lesson

  • Why a canonical formexplain
  • Freshness and replaysexplain
  • Why each check?order
  • Attack and defencematch
  • Sign and verifywrite code
  • Badge quizquiz
  • What you builtrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 4 lessons of Project: A secure API gateway