Executive Talents · API Gateway — Getting Started

Rendered from this repo's docs/gateway/APP_INTEGRATION_GUIDE.md.

Connecting an application to the API Gateway

Audience: any Executive Talents engineer plugging their app into the gateway — either as a provider (other apps/users reach your app through it), a consumer (your app calls other apps through it), or both. Read CONTRACT.md for the authoritative wire contract; this doc is the practical "what do I actually build" walkthrough. It's written to be stack-agnostic — every code sample below is illustrative pseudocode-with-real-syntax for a specific language, not a claim that this repo ships that language. Adapt the pattern (constant-time compare, headers in, headers out) to whatever your app is actually written in.

Two separate questions

Before writing any code, answer these for each route your app exposes:

  1. Who calls this route: a logged-in human (via your own frontend/session), or another application acting on its own behalf?
  2. If it's a human — is that traffic going through the gateway at all, or hitting your app directly? (Both are valid; the gateway doesn't require every request to pass through it.)

As of ADR-GW-2 (CONTRACT.md §5), every route you declare lives at the same URL for every kind of caller — /<your-slug>/<path>, namespaced, whether it's your own frontend's session traffic or a granted external application. What used to be two different route classes with two different public URLs is now one URL with a per-request auth decision:

scope empty (passthrough) scope set (machine-preferred)
Who it's for Your own frontend / a browser session Another registered application, with an explicit grant — but composes with human traffic on the same route, see below
Auth checked by the edge? No — forwards Authorization unchanged Tries to verify a Bearer token as an EdDSA JWT, offline, via JWKS
No/invalid machine token presented N/A — never attempted Falls through to the same passthrough behavior as the left column — not rejected
Valid machine token, insufficient scope N/A Rejected outright (403 GW1003) — this is the one case that's still a hard reject
What your app receives The original Authorization header, untouched X-Gateway-Client-Id / X-Gateway-Scopes only if verified; otherwise the same as the left column
Namespaced under your app's slug? Yes — /<your-slug>/<path>, always Yes — /<your-slug>/<path>, always

A route with scope set now automatically serves both a granted machine caller and an ordinary human session at the same URL — the edge decides which, per request, by whether the presented credential actually verifies. You don't need to hand-write a "compose both checks" guard for this case anymore (see "Trust the gateway's forwarded identity" below) — just check whether X-Gateway-Client-Id is present.

The one thing you can't express anymore: "this route must only ever be reachable by a specific granted machine caller, reject anything else outright." A scope-bearing route always has a passthrough fallback now. If you genuinely need that stronger guarantee for a specific route, enforce it yourself downstream — reject if X-Gateway-Client-Id is absent — the same "compose, don't replace" pattern below, just opted into rather than automatic.

Provider side — letting other apps/gateway traffic reach you

1. Expose a manifest

GET /.well-known/gateway-manifest — a JSON document declaring your app's identity, scopes, and routes (CONTRACT.md §2):

{
  "appId": "your-app-slug",
  "name": "Your App",
  "description": "One line describing what this app does",
  "version": "1.0.0",
  "baseUrl": "https://your-app.internal",
  "documentation": "https://your-app.internal/.well-known/openapi.json",
  "owner": "Your Team",
  "contact": "your-team@company.com",
  "scopes": [
    { "key": "employee.read", "description": "Read employee records" }
  ],
  "routes": [
    { "path": "/employees", "method": "GET", "scope": "employee.read" },
    { "path": "/status" }
  ]
}

Either way: mark this endpoint (and your health check) as unauthenticated/public in your own framework — a gateway can't fetch the manifest that tells it how to authenticate if the manifest endpoint itself requires authentication first.

2. Decide, per route, whether it needs a scope

Default assumption: anything a human calls today via your own frontend, unmodified, needs no scope at all (leave scope empty) — or isn't registered with the gateway at all, if that traffic never goes through the gateway. Only declare a scope once you have an actual reason another application — not your own frontend — needs to call it on its own behalf, with its own granted scope.

As of ADR-GW-2, getting this "backwards" (declaring a scope on a route your own frontend calls) is no longer the integration-breaking mistake it used to be: the edge tries to verify the caller as a machine token, fails (a session JWT doesn't verify as one), and falls through to the exact same passthrough handling your frontend traffic would get anyway (CONTRACT.md §5.2). It costs one wasted verification attempt per request, not a broken app. The reason to still get this right isn't avoiding breakage — it's correctness of intent: a scope you declare is a real claim ("another application can be granted this"), and an unused one is just noise in your manifest.

3. Trust the gateway's forwarded identity on machine routes — check the header secret, don't verify a JWT yourself

The edge already did the hard cryptographic work (EdDSA/JWKS verification) before forwarding a verified machine request — and it only stamps X-Gateway-Client-Id/X-Gateway-Scopes when that verification actually succeeded (CONTRACT.md §5.2/§7). Your app's job is simple: check for that header's presence, and when it's there, verify the accompanying header secret before trusting it. The secret is what stops someone who can reach your app directly, bypassing the gateway, from forging X-Gateway-Client-Id themselves.

X-Gateway-Client-Id: <the calling application's id>  — present ONLY on a verified machine caller;
                                                         this is what you check for "is this machine"
X-Gateway-Scopes:    <space-joined granted scopes>
X-Gateway-App-Auth:  <YOUR app's own secret, etgh1_…> — XL1 per-application secret: ONLY on verified
                                                         machine requests, current epoch only, never
                                                         on passthrough
X-Gateway-Auth:      <legacy gateway-wide secret>     — legacy, migration only: on EVERY forwarded
                                                         request, passthrough too, until rollout P7

Do not key your check off a secret header's presence. The legacy X-Gateway-Auth is stamped on ordinary passthrough traffic too (CONTRACT.md §7), so a check gated on "is X-Gateway-Auth present" would treat every gateway-forwarded request as a machine call, including your own frontend's session traffic. The header that's exclusive to a verified machine caller is X-Gateway-Client-Id.

What your app sees, by rollout step

The single gateway-wide secret is being replaced by one secret per provider application (XL1, design docs/design/xl1-per-app-gateway-secret.md; the step list is in the gateway README "Gateway header secrets"). Steps run per environment (development → staging → production) and, from P3 on, per provider app:

Step Edge sends Your app is configured with Your app accepts
Today, and P1 X-Gateway-Auth on every request GATEWAY_SHARED_HEADER_SECRET legacy
P2 (master key set on the gateway) + X-Gateway-App-Auth on verified machine requests unchanged legacy
P3 (your app ships the code below) both unchanged; GATEWAY_APP_HEADER_SECRETS unset legacy (logs matched=legacy reason=per_app_unconfigured)
P4–P5 (operator installs your secret; soak) both both variables per-app or legacy
P6 (your app goes strict) both GATEWAY_APP_HEADER_SECRETS only per-app only
P7–P8 (legacy retired) X-Gateway-App-Auth only GATEWAY_APP_HEADER_SECRETS only per-app only

Status 2026-10-06: the gateway side (W1–W3) is in open PRs #38/#39 and not merged, so every environment is at "Today". A provider app integrating from now on ships the accept-list code from day one. It takes GATEWAY_APP_HEADER_SECRETS once its environment has reached P2, and takes the legacy value only if its environment hasn't.

The check

Every stack follows the same shape: a piece of middleware that runs before your route handlers and before your session auth.

  1. X-Gateway-Client-Id absent → no-op. Your normal session/Bearer auth runs unmodified; never require or inspect a secret header on this path.
  2. Present → compare X-Gateway-App-Auth against every value in GATEWAY_APP_HEADER_SECRETS (one to three), in constant time, as bytes, with no early exit. Any match accepts (matched=per_app).
  3. Otherwise, only while your app still has GATEWAY_SHARED_HEADER_SECRET set (the overlap, until your app's P6): compare X-Gateway-Auth against it in constant time. A match accepts (matched=legacy).
  4. Anything else is a reject — 401 in your app's existing error shape. It is never a fall-through to your session auth and never "trust the headers anyway". With neither variable configured, every machine claim is rejected (fail closed).
  5. Only after accepting, read X-Gateway-Client-Id/X-Gateway-Scopes into whatever per-request context your framework uses.

Accepting more than one credential is a deliberate, temporary relaxation of the older wording "a present-but-wrong secret is always a reject": now a request is rejected unless at least one accepted credential matches (design §4 and §8 Q4). The founder's confirmation of that wording is not yet recorded in the design's §9 decisions (2026-10-06). The relaxation exists only because the overlap needs it.

Configuration — read once at start-up. Changing .env needs the container recreated, not just restarted.

Variable Holds Rules
GATEWAY_APP_HEADER_SECRETS Your app's own per-application secret(s): comma-separated, 1–3 values, each etgh1_ + 64 lowercase hex Trim each entry and drop empty ones — "a," must never produce an empty value that matches an absent header. More than three values, or a malformed entry (truncated, quoted, wrong value), means refuse to start, naming the position and never the value. One value at steady state; two during a rotation
GATEWAY_SHARED_HEADER_SECRET The legacy gateway-wide value Only until your app's P6. Unset/empty means strict (legacy refused). Delete the code path at P8

Logging (observability.md) — never a header value, only fingerprints. fp(K) is the first 8 hex characters of SHA-256 of the value, exactly what the gateway's CLI prints.

matched reason Meaning What to do
per_app – Normal –
legacy per_app_unconfigured Your app has no per-app value yet (before P4) Normal until P4
legacy per_app_absent The edge sent no per-app header: master key unset on the edge, or an older gateway Fix before your app goes strict (P6)
legacy per_app_mismatch Your values don't include what the edge sends: wrong paste, wrong environment, or the edge rotated past your list Compare your configured_fp with controlplane header-secret status
none missing / mismatch / unconfigured Rejected with 401 Find the gateway request-log row by request_id

Each snippet below is a complete module, adapted to one framework. Keep the logic; change the framework glue and the 401 body to match your app. ✅ 2026-10-06: each one was syntax-checked (node --check on Node 25, python3 -m py_compile on 3.9, gofmt + go vet on Go 1.27, ruby -c on 2.6). Each was also run against the design §6 case table: per-app match, wrong value, overlap, strict, unconfigured, X-Gateway-Client-Id absent with bogus secret headers, non-ASCII header (gives 401, not 500), an empty list entry, and a malformed or too-long config. Django and Rails were stubbed for that run.

Node/Express:

const crypto = require('crypto');

const MAX_ACCEPTED = 3;
const WELL_FORMED = /^etgh1_[0-9a-f]{64}$/;

// fp(K): first 8 hex chars of SHA-256 — the only form of a secret that is ever logged.
const fingerprint = (s) => crypto.createHash('sha256').update(s, 'utf8').digest('hex').slice(0, 8);

// Constant-time on bytes. Hashing both sides first gives equal-length buffers,
// so timingSafeEqual never throws and the time doesn't depend on lengths or content.
function ctEqual(a, b) {
  const ha = crypto.createHash('sha256').update(a, 'utf8').digest();
  const hb = crypto.createHash('sha256').update(b, 'utf8').digest();
  return crypto.timingSafeEqual(ha, hb);
}

// Read once at start-up. Throws (refuse to start) on a malformed value; the
// message names the position, never the value.
function loadGatewayAuthConfig(env = process.env) {
  const accepted = (env.GATEWAY_APP_HEADER_SECRETS || '')
    .split(',').map((s) => s.trim()).filter((s) => s !== ''); // "a," never yields a matchable ""
  if (accepted.length > MAX_ACCEPTED) {
    throw new Error(`GATEWAY_APP_HEADER_SECRETS: at most ${MAX_ACCEPTED} values, got ${accepted.length}`);
  }
  accepted.forEach((s, i) => {
    if (!WELL_FORMED.test(s)) {
      throw new Error(`GATEWAY_APP_HEADER_SECRETS entry ${i + 1} is not an etgh1_ secret (truncated, quoted, wrong value?)`);
    }
  });
  const legacy = (env.GATEWAY_SHARED_HEADER_SECRET || '').trim(); // '' = legacy off (strict)
  console.log(JSON.stringify({
    event: 'gateway_auth_config',
    configured_fp: accepted.map(fingerprint),
    legacy: legacy === '' ? 'disabled' : 'enabled',
  }));
  if (accepted.length === 0 && legacy === '') {
    console.warn(JSON.stringify({ event: 'gateway_auth_config', warning: 'no secret configured: every machine call is rejected' }));
  }
  return { accepted, legacy };
}

// Accept lines are rate-limited (<= 1/min per key); rejects are always logged.
const lastLogged = new Map();
function logRateLimited(key, warn, line) {
  const now = Date.now();
  const prev = lastLogged.get(key);
  if (prev !== undefined && now - prev < 60000) return;
  if (lastLogged.size > 1000) lastLogged.clear();
  lastLogged.set(key, now);
  (warn ? console.warn : console.log)(JSON.stringify(line));
}

function gatewayAuth(cfg) {
  return function gatewayAuthMiddleware(req, res, next) {
    const clientId = req.get('X-Gateway-Client-Id');
    if (clientId === undefined) {
      return next(); // no machine-caller claim: normal session/Bearer auth handles this request
    }
    const presented = req.get('X-Gateway-App-Auth') || '';
    const legacyPresented = req.get('X-Gateway-Auth') || '';
    let matched = -1;
    cfg.accepted.forEach((secret, i) => {
      if (ctEqual(presented, secret)) matched = i; // compare EVERY candidate: no early exit
    });
    const legacyOk = cfg.legacy !== '' && ctEqual(legacyPresented, cfg.legacy);

    const base = {
      event: 'gateway_auth',
      client_id: clientId.slice(0, 64), // unverified on a reject: truncated, never trusted
      request_id: (req.get('X-Gateway-Request-Id') || '').slice(0, 64),
    };
    if (matched >= 0) {
      logRateLimited(`${clientId}|per_app|${matched}`, false,
        { ...base, outcome: 'accept', matched: 'per_app', fp: fingerprint(cfg.accepted[matched]) });
    } else if (legacyOk) {
      let reason = 'per_app_unconfigured';
      if (cfg.accepted.length > 0) reason = presented === '' ? 'per_app_absent' : 'per_app_mismatch';
      logRateLimited(`${clientId}|legacy|${reason}`, cfg.accepted.length > 0,
        { ...base, outcome: 'accept', matched: 'legacy', reason });
    } else {
      let reason = 'mismatch';
      if (cfg.accepted.length === 0 && cfg.legacy === '') reason = 'unconfigured';
      else if (presented === '' && legacyPresented === '') reason = 'missing';
      console.warn(JSON.stringify({ ...base, outcome: 'reject', matched: 'none', reason }));
      return res.status(401).json({ error: { code: 'APP1001', message: 'invalid gateway auth' } });
    }
    req.gateway = {
      clientId,
      scopes: (req.get('X-Gateway-Scopes') || '').split(' ').filter(Boolean),
    };
    return next();
  };
}

// app.use(gatewayAuth(loadGatewayAuthConfig()));  // before your routes and your session auth
module.exports = { loadGatewayAuthConfig, gatewayAuth, fingerprint };

Python (Django middleware; the same logic ports to a Starlette/FastAPI middleware):

import hashlib
import hmac
import json
import logging
import os
import re
import threading
import time

from django.http import JsonResponse

log = logging.getLogger("gateway_auth")

MAX_ACCEPTED = 3
WELL_FORMED = re.compile(r"etgh1_[0-9a-f]{64}")


def fingerprint(secret):
    """fp(K): first 8 hex chars of SHA-256 -- the only form of a secret that is ever logged."""
    return hashlib.sha256(secret.encode("utf-8")).hexdigest()[:8]


def ct_equal(a, b):
    # Compare as bytes: a non-ASCII/latin-1 header value is "no match", never an exception.
    return hmac.compare_digest(a.encode("utf-8", "replace"), b.encode("utf-8", "replace"))


def load_gateway_auth_config(env=os.environ):
    """Read once at start-up. Raises (refuse to start) on a malformed value; never prints one."""
    accepted = [s.strip() for s in env.get("GATEWAY_APP_HEADER_SECRETS", "").split(",")]
    accepted = [s for s in accepted if s]  # "a,".split(",") yields "": it must never match an absent header
    if len(accepted) > MAX_ACCEPTED:
        raise RuntimeError("GATEWAY_APP_HEADER_SECRETS: at most %d values, got %d" % (MAX_ACCEPTED, len(accepted)))
    for i, s in enumerate(accepted, start=1):
        if not WELL_FORMED.fullmatch(s):
            raise RuntimeError("GATEWAY_APP_HEADER_SECRETS entry %d is not an etgh1_ secret (truncated, quoted, wrong value?)" % i)
    legacy = env.get("GATEWAY_SHARED_HEADER_SECRET", "").strip()  # "" = legacy off (strict)
    log.info(json.dumps({"event": "gateway_auth_config",
                         "configured_fp": [fingerprint(s) for s in accepted],
                         "legacy": "enabled" if legacy else "disabled"}))
    if not accepted and not legacy:
        log.warning(json.dumps({"event": "gateway_auth_config",
                                "warning": "no secret configured: every machine call is rejected"}))
    return accepted, legacy


# Accept lines are rate-limited (<= 1/min per key); rejects are always logged.
_last_logged = {}
_last_logged_lock = threading.Lock()


def _log_rate_limited(key, level, line):
    now = time.monotonic()
    with _last_logged_lock:
        prev = _last_logged.get(key)
        if prev is not None and now - prev < 60:
            return
        if len(_last_logged) > 1000:
            _last_logged.clear()
        _last_logged[key] = now
    log.log(level, json.dumps(line))


class GatewayAuthMiddleware:
    """Django middleware: list it before your session/auth middleware."""

    def __init__(self, get_response):
        self.get_response = get_response
        self.accepted, self.legacy = load_gateway_auth_config()

    def __call__(self, request):
        client_id = request.headers.get("X-Gateway-Client-Id")
        if client_id is None:
            return self.get_response(request)  # no machine-caller claim: normal session auth handles it

        presented = request.headers.get("X-Gateway-App-Auth", "")
        legacy_presented = request.headers.get("X-Gateway-Auth", "")
        matched = -1
        for i, secret in enumerate(self.accepted):  # compare EVERY candidate: no early exit
            if ct_equal(presented, secret):
                matched = i
        legacy_ok = bool(self.legacy) and ct_equal(legacy_presented, self.legacy)

        base = {"event": "gateway_auth",
                "client_id": client_id[:64],  # unverified on a reject: truncated, never trusted
                "request_id": request.headers.get("X-Gateway-Request-Id", "")[:64]}
        if matched >= 0:
            _log_rate_limited((client_id, "per_app", matched), logging.INFO,
                              dict(base, outcome="accept", matched="per_app",
                                   fp=fingerprint(self.accepted[matched])))
        elif legacy_ok:
            reason = "per_app_unconfigured"
            if self.accepted:
                reason = "per_app_absent" if not presented else "per_app_mismatch"
            _log_rate_limited((client_id, "legacy", reason),
                              logging.WARNING if self.accepted else logging.INFO,
                              dict(base, outcome="accept", matched="legacy", reason=reason))
        else:
            reason = "mismatch"
            if not self.accepted and not self.legacy:
                reason = "unconfigured"
            elif not presented and not legacy_presented:
                reason = "missing"
            log.warning(json.dumps(dict(base, outcome="reject", matched="none", reason=reason)))
            return JsonResponse({"error": {"code": "APP1001", "message": "invalid gateway auth"}}, status=401)

        request.gateway_client_id = client_id
        request.gateway_scopes = request.headers.get("X-Gateway-Scopes", "").split()
        return self.get_response(request)

Go (net/http):

package gatewayauth

import (
	"context"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/hex"
	"fmt"
	"log/slog"
	"net/http"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"
)

const maxAccepted = 3

var wellFormed = regexp.MustCompile(`^etgh1_[0-9a-f]{64}$`)

// Fingerprint is fp(K): the first 8 hex chars of SHA-256, the only form of a
// secret that is ever logged.
func Fingerprint(secret string) string {
	sum := sha256.Sum256([]byte(secret))
	return hex.EncodeToString(sum[:])[:8]
}

// ctEqual compares in constant time. Hashing first gives equal lengths, so
// ConstantTimeCompare never short-circuits on a length difference.
func ctEqual(a, b string) bool {
	ha, hb := sha256.Sum256([]byte(a)), sha256.Sum256([]byte(b))
	return subtle.ConstantTimeCompare(ha[:], hb[:]) == 1
}

type Config struct {
	Accepted []string // GATEWAY_APP_HEADER_SECRETS: 0..3 per-app secrets
	Legacy   string   // GATEWAY_SHARED_HEADER_SECRET: "" = legacy off (strict)
}

// LoadConfig runs once at start-up (pass os.Getenv). An error means: refuse to
// start. Errors name the position, never the value.
func LoadConfig(getenv func(string) string) (Config, error) {
	var c Config
	for _, s := range strings.Split(getenv("GATEWAY_APP_HEADER_SECRETS"), ",") {
		if s = strings.TrimSpace(s); s != "" { // "a," must never yield a matchable ""
			c.Accepted = append(c.Accepted, s)
		}
	}
	if len(c.Accepted) > maxAccepted {
		return Config{}, fmt.Errorf("GATEWAY_APP_HEADER_SECRETS: at most %d values, got %d", maxAccepted, len(c.Accepted))
	}
	fps := make([]string, len(c.Accepted))
	for i, s := range c.Accepted {
		if !wellFormed.MatchString(s) {
			return Config{}, fmt.Errorf("GATEWAY_APP_HEADER_SECRETS entry %d is not an etgh1_ secret (truncated, quoted, wrong value?)", i+1)
		}
		fps[i] = Fingerprint(s)
	}
	c.Legacy = strings.TrimSpace(getenv("GATEWAY_SHARED_HEADER_SECRET"))
	slog.Info("gateway_auth_config", "configured_fp", fps, "legacy_enabled", c.Legacy != "")
	if len(c.Accepted) == 0 && c.Legacy == "" {
		slog.Warn("gateway_auth_config: no secret configured, every machine call is rejected")
	}
	return c, nil
}

// limiter rate-limits accept lines (<= 1/min per key); rejects are always logged.
type limiter struct {
	mu   sync.Mutex
	last map[string]time.Time
}

func (l *limiter) allow(key string) bool {
	l.mu.Lock()
	defer l.mu.Unlock()
	now := time.Now()
	if t, ok := l.last[key]; ok && now.Sub(t) < time.Minute {
		return false
	}
	if l.last == nil || len(l.last) > 1000 {
		l.last = make(map[string]time.Time)
	}
	l.last[key] = now
	return true
}

type ctxKey int

const (
	ClientIDKey ctxKey = iota
	ScopesKey
)

func truncate(s string, n int) string {
	if len(s) > n {
		return s[:n]
	}
	return s
}

// Middleware wraps your router, ahead of your session/Bearer auth.
func Middleware(c Config, next http.Handler) http.Handler {
	var rl limiter
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ids := r.Header.Values("X-Gateway-Client-Id")
		if len(ids) == 0 {
			next.ServeHTTP(w, r) // no machine-caller claim: normal session auth handles this request
			return
		}
		clientID := ids[0]
		presented := r.Header.Get("X-Gateway-App-Auth")
		legacyPresented := r.Header.Get("X-Gateway-Auth")
		matched := -1
		for i, s := range c.Accepted { // compare EVERY candidate: no early exit
			if ctEqual(presented, s) {
				matched = i
			}
		}
		legacyOK := c.Legacy != "" && ctEqual(legacyPresented, c.Legacy)

		// client_id is unverified on a reject: truncated, never trusted.
		attrs := []any{"client_id", truncate(clientID, 64), "request_id", truncate(r.Header.Get("X-Gateway-Request-Id"), 64)}
		switch {
		case matched >= 0:
			if rl.allow(clientID + "|per_app|" + strconv.Itoa(matched)) {
				slog.Info("gateway_auth", append(attrs, "outcome", "accept", "matched", "per_app", "fp", Fingerprint(c.Accepted[matched]))...)
			}
		case legacyOK:
			reason, level := "per_app_unconfigured", slog.LevelInfo
			if len(c.Accepted) > 0 {
				reason, level = "per_app_mismatch", slog.LevelWarn
				if presented == "" {
					reason = "per_app_absent"
				}
			}
			if rl.allow(clientID + "|legacy|" + reason) {
				slog.Log(r.Context(), level, "gateway_auth", append(attrs, "outcome", "accept", "matched", "legacy", "reason", reason)...)
			}
		default:
			reason := "mismatch"
			if len(c.Accepted) == 0 && c.Legacy == "" {
				reason = "unconfigured"
			} else if presented == "" && legacyPresented == "" {
				reason = "missing"
			}
			slog.Warn("gateway_auth", append(attrs, "outcome", "reject", "matched", "none", "reason", reason)...)
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusUnauthorized)
			_, _ = w.Write([]byte(`{"error":{"code":"APP1001","message":"invalid gateway auth"}}`))
			return
		}
		ctx := context.WithValue(r.Context(), ClientIDKey, clientID)
		ctx = context.WithValue(ctx, ScopesKey, strings.Fields(r.Header.Get("X-Gateway-Scopes")))
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

Ruby (Rails concern):

# app/controllers/concerns/gateway_auth.rb -- `include GatewayAuth` in ApplicationController
require "digest"
require "json"

module GatewayAuth
  extend ActiveSupport::Concern

  MAX_ACCEPTED = 3
  WELL_FORMED = /\Aetgh1_[0-9a-f]{64}\z/

  # fp(K): first 8 hex chars of SHA-256 -- the only form of a secret that is ever logged.
  def self.fingerprint(secret)
    Digest::SHA256.hexdigest(secret)[0, 8]
  end

  # Constant-time on bytes: comparing equal-length digests never short-circuits
  # on length and never raises on an odd encoding.
  def self.ct_equal?(a, b)
    ActiveSupport::SecurityUtils.secure_compare(Digest::SHA256.digest(a.to_s.b), Digest::SHA256.digest(b.to_s.b))
  end

  # Read once at start-up. Raises (refuse to start) on a malformed value; never prints one.
  def self.load_config(env = ENV)
    accepted = env.fetch("GATEWAY_APP_HEADER_SECRETS", "").split(",").map(&:strip).reject(&:empty?)
    raise "GATEWAY_APP_HEADER_SECRETS: at most #{MAX_ACCEPTED} values, got #{accepted.size}" if accepted.size > MAX_ACCEPTED

    accepted.each_with_index do |s, i|
      next if WELL_FORMED.match?(s)

      raise "GATEWAY_APP_HEADER_SECRETS entry #{i + 1} is not an etgh1_ secret (truncated, quoted, wrong value?)"
    end
    legacy = env.fetch("GATEWAY_SHARED_HEADER_SECRET", "").strip # "" = legacy off (strict)
    Rails.logger.info({ event: "gateway_auth_config", configured_fp: accepted.map { |s| fingerprint(s) },
                        legacy: legacy.empty? ? "disabled" : "enabled" }.to_json)
    if accepted.empty? && legacy.empty?
      Rails.logger.warn({ event: "gateway_auth_config",
                          warning: "no secret configured: every machine call is rejected" }.to_json)
    end
    { accepted: accepted.freeze, legacy: legacy.freeze }.freeze
  end

  # Accept lines are rate-limited (<= 1/min per key); rejects are always logged.
  RATE_MUTEX = Mutex.new
  RATE_LAST = {}

  def self.log_rate_limited(key, level, line)
    now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    RATE_MUTEX.synchronize do
      prev = RATE_LAST[key]
      return if prev && now - prev < 60

      RATE_LAST.clear if RATE_LAST.size > 1000
      RATE_LAST[key] = now
    end
    Rails.logger.public_send(level, line.to_json)
  end

  CONFIG = load_config

  included do
    before_action :verify_gateway_headers
  end

  private

  def verify_gateway_headers
    client_id = request.headers["X-Gateway-Client-Id"]
    return if client_id.nil? # no machine-caller claim: normal session auth handles this request

    cfg = GatewayAuth::CONFIG
    presented = request.headers["X-Gateway-App-Auth"].to_s
    legacy_presented = request.headers["X-Gateway-Auth"].to_s
    matched = -1
    cfg[:accepted].each_with_index do |secret, i| # compare EVERY candidate: no early exit
      matched = i if GatewayAuth.ct_equal?(presented, secret)
    end
    legacy_ok = !cfg[:legacy].empty? && GatewayAuth.ct_equal?(legacy_presented, cfg[:legacy])

    base = { event: "gateway_auth",
             client_id: client_id[0, 64], # unverified on a reject: truncated, never trusted
             request_id: request.headers["X-Gateway-Request-Id"].to_s[0, 64] }
    if matched >= 0
      GatewayAuth.log_rate_limited([client_id, "per_app", matched], :info,
                                   base.merge(outcome: "accept", matched: "per_app",
                                              fp: GatewayAuth.fingerprint(cfg[:accepted][matched])))
    elsif legacy_ok
      reason = "per_app_unconfigured"
      reason = presented.empty? ? "per_app_absent" : "per_app_mismatch" unless cfg[:accepted].empty?
      GatewayAuth.log_rate_limited([client_id, "legacy", reason], cfg[:accepted].empty? ? :info : :warn,
                                   base.merge(outcome: "accept", matched: "legacy", reason: reason))
    else
      reason = if cfg[:accepted].empty? && cfg[:legacy].empty? then "unconfigured"
               elsif presented.empty? && legacy_presented.empty? then "missing"
               else "mismatch"
               end
      Rails.logger.warn(base.merge(outcome: "reject", matched: "none", reason: reason).to_json)
      render json: { error: { code: "APP1001", message: "invalid gateway auth" } }, status: :unauthorized
      return
    end
    @gateway_client_id = client_id
    @gateway_scopes = request.headers["X-Gateway-Scopes"].to_s.split
  end
end

Whatever your stack, the same rules apply:

Getting your secret

4. Register + get granted

None of the above makes you reachable by itself — an admin still has to:

  1. POST /applications {"manifestUrl": "https://your-app/.well-known/gateway-manifest"} against the control plane.
  2. POST /applications/{consumerId}/grants {"providerAppSlug": "your-slug", "scopeKey": "..."} for every other application that should be allowed to call you, and for which scope. Registration never implies a grant — this is a separate, explicit step per consuming application.

Debugging: "did my request even reach the gateway?"

Before assuming your app's own code is at fault for an unexpected error (a GW1xxx error code from the edge, or a request you expected to arrive that never did), check GET /applications/{your-app-id}/requests against the control plane — every request the edge classified for your app, machine and passthrough both, with method/status/duration/timestamp (CONTRACT.md §14). GET /requests/summary gives the same thing aggregated across every app, if you're not sure which application's traffic is actually the problem. This tells you, before you go looking anywhere else, whether the request reached the edge at all and what it decided. The edge no longer rejects a bad token with 401 (GW1001/GW1002 are retired as of contract v3; such a request falls through to passthrough, CONTRACT.md §5.2). A 401 on a machine-class row (one with a clientId) is therefore your own app's reject — most often a header-secret mismatch. Its requestId is the request_id in your app's gateway_auth reject line (§3), which says why.

5. Network exposure

The header-secret check in step 3 is what stops a caller that reaches your app directly — bypassing the gateway — from setting X-Gateway-Client-Id itself. The remaining risk is a leaked secret: your own per-application value exposes your app only, but during the overlap the legacy gateway-wide value still works against every provider app that accepts it. So also keep your app off any publicly routable address and reachable only via the gateway/shared internal network, so a leaked secret isn't your only line of defense.

Consumer side — calling another app through the gateway

Never hardcode another application's real internal address. Call the gateway's edge instead:

  1. Get a credential. An admin runs POST /applications/{yourAppId}/credentials against the control plane. The response is {"clientId", "clientSecret", "sharedHeaderSecret"?} — the clientId/clientSecret are yours alone and shown once (store them in your secrets manager, never in code). sharedHeaderSecret, if present, is the legacy gateway-wide header secret from §3 above. It is only relevant if you're also a provider whose environment hasn't reached rollout step P2, and it stops being returned at P7. Your per-application header secret never comes from this endpoint (§3 "Getting your secret").
  2. Get grants. An admin runs POST /applications/{yourAppId}/grants {"providerAppSlug": "...", "scopeKey": "..."} for every app + scope you actually need to call. Having a credential doesn't grant you anything by itself.
  3. Mint a token. POST <control-plane>/oauth/token with grant_type=client_credentials&client_id=...&client_secret=... returns a short-lived JWT (~15 min) carrying exactly the scopes you currently hold. Cache it; re-mint shortly before (or on a 401 from) expiry — don't mint a fresh token on every call.
  4. Call the edge, not the target app. <gateway-edge>/<provider-slug>/<path> with Authorization: Bearer <token>.

The token-caching step looks the same regardless of stack — cache the token and its expiry in-process, re-mint a little before it actually expires (a fixed safety margin, e.g. 30s, is enough), and on an unexpected 401 from the edge, mint once more and retry the call exactly once before giving up:

function callProvider(providerSlug, path, opts):
  token = getCachedTokenOrMint()          # mint() calls POST /oauth/token, caches token + expiry
  response = httpCall(edgeUrl + "/" + providerSlug + path, bearer=token, ...opts)
  if response.status == 401:
    token = mint()                        # force a fresh mint, bypass the cache once
    response = httpCall(edgeUrl + "/" + providerSlug + path, bearer=token, ...opts)
  return response

A frontend/SPA is a special case of "consumer" — and usually isn't one

A browser-based frontend calling its own backend with a user's login session is not a machine client, and should not be registered, credentialed, or granted a scope:

Reference implementation

Everything above is deliberately generic — if you want to see a fully worked, real (not pseudocode) integration to cross-check your own implementation against, talentscholarplus-backend-staging (NestJS) has one. It predates XL1. At origin/development e02b978, its gateway-or-jwt-auth.guard.ts keys on X-Gateway-Client-Id (XL1 design §2, checked 2026-10-06), but src/common/gateway/verify-gateway-headers.ts still checks only the single legacy secret, with no accept-list and no match/reject logging. Use §3 above for that part until the app's own XL1 change (design W9) lands, and check the current code before copying:

Nothing about the gateway's contract is NestJS- or TypeScript-specific — this is one example among however many stacks end up integrating, not the reference stack.

Checklist

Using Claude Code and not on the Executive-Talents workspace?

Fetch the org's gateway integration rule + checklist directly — no repo clone needed:

mkdir -p .claude/rules .claude/skills/gateway-integration-check
curl -fsSL https://api.gateway.etstag.net/claude/rules/api-gateway.md -o .claude/rules/api-gateway.md
curl -fsSL https://api.gateway.etstag.net/claude/skills/gateway-integration-check.md \
  -o .claude/skills/gateway-integration-check/SKILL.md