System Architecture · Insper · Lab 4

Lab 4 — Gateway & identity

An auth service that signs JSON Web Tokens (JWTs), and a Spring Cloud Gateway that validates them once

The story so far

lab 3 · edge3 replicas; the mix stuck on PostgreSQL
→
chapters 4–5 · lab 4auth + gateway: identity, once
→
next · lab 5a cache in front of the database

The edge limits 20 requests/s per key, but the key is a header the client picks. How do 2 million fans prove who they are — once, for every service?

  • No replica keeps a session: the token travels with each request.

Who are you, and what may you do?

Anyone can delete events in the catalog today. Should every service learn to check passwords?

  • Authentication — who is calling.
  • Authorization — what they may do.
  • Solve it once, at the front door: the application programming interface (API) gateway.

What you will build

fans · k6
:80 →
edgeNginx · rate limit · /actuator → 404
→
gateway :8080JWT, rules, routes, lb://catalog
→
services
auth :8081users, BCrypt, signs tokens
catalog-1..3 :8082trust X-User-* from the gateway
  • Two load balancers: the edge spreads over gateways, the gateway over service instances.
  • Only the edge is public; port 8080 is published only for the measurements.

Sessions vs tokens

Session id JWT
Client holds random id signed claims
Check lookup in a store verify signature locally
Revocation immediate wait for exp
Scales with the session store central processing unit (CPU) only

RS256 and the JSON Web Key Set (JWKS)

authprivate key · signs
token →
clientsends Bearer on every request
→
gatewaypublic key · verifies locally
← once
/auth/.well-known/jwks.jsondownloaded again only for an unknown kid
  • RS256 = a Rivest–Shamir–Adleman (RSA) signature over SHA-256: only auth can mint; anyone can verify.
  • With HS256, a hash-based message authentication code (HMAC), one secret signs and verifies: every holder could forge tokens.

Signed ≠ encrypted: anyone can read the payload.

The token

{ "iss": "boxoffice-auth", "aud": "boxoffice",
  "sub": "0b9d8a6e-…", "email": "ana@example.com",
  "scope": "user", "iat": 1795000000, "exp": 1795003600 }
  • Gateway checks signature, exp, iss, aud.
  • scope → authorities SCOPE_user, SCOPE_admin.

The auth service

  • POST /auth/register — BCrypt (cost 10), never the password.
  • POST /auth/login — same 401 for unknown user and wrong password.
  • GET /auth/me — trusts X-User-Id from the gateway.
  • Admin created at startup from ADMIN_EMAIL / ADMIN_PASSWORD.
  • New RSA key pair at every start: old tokens die (see A new key, below).

Gateway routes

routes:
  - id: auth
    uri: http://auth:8081
    predicates: [ Path=/auth/** ]
  - id: catalog
    uri: lb://catalog          # catalog-1..3, health-checked
    predicates: [ Path=/catalog/** ]
  • Timeouts: connect 1 s, response 5 s. Retry a failed GET once, on another instance.
  • Health check: probe each /actuator/health/readiness every 5 s, skip the ones not UP.

Who may call what

.pathMatchers("/auth/register", "/auth/login", "/auth/.well-known/**").permitAll()
.pathMatchers(HttpMethod.GET, "/catalog/**").permitAll()
.pathMatchers("/catalog/**").hasAuthority("SCOPE_admin")
.anyExchange().authenticated()
token sent?validated first, even on an open route
→
first rule that matchesin order
→
permitted → route
no / bad token401
valid, wrong scope403
  • Deny by default: new routes are protected automatically.

Identity headers

clientBearer (Ana) + X-User-Id: admin
→
gatewaystrip X-User-* · validate · sub = Ana
→
authX-User-Id: Ana
  • Strip X-User-* from the client — always; then set them from the validated JWT.
  • Services trust them because they are reachable only through the gateway.

What changes in a zero-trust network?

Try it end to end

Request Answer Who answered
POST /auth/register 201 auth
POST /auth/login 200 + token auth
GET /auth/me with the token 200 Ana auth (via the gateway)
GET /auth/me without a token 401 gateway
DELETE /catalog/events/2 as Ana 403 gateway
PUT /catalog/events/2 as admin 200 a catalog replica
  • The rejections never reach a service: they cost the gateway microseconds.

A new key at every restart

restart authnew key pair, kid B
→
old token (kid A)200: the gateway still has kid A cached
→
first token with kid Bunknown kid → download the JWKS
→
old token (kid A)401: not in the JWKS any more
  • The gateway caches the JWKS and downloads it again only for an unknown kid.
  • Production: the key lives in a key management service (KMS); the JWKS lists current and previous keys.
  • Expired tokens: the gateway tolerates 60 s of clock skew past exp.

Measure it

Path What it adds
catalog alone baseline
gateway → catalog + the gateway hop
edge → gateway → catalog + the edge hop
same, with a token + JWT validation
# k6 inside the compose network: catalog replicas publish no port
docker run --rm -i --network boxoffice_default -v "$PWD":/w -w /w \
  grafana/k6 run -e RATE=50 load/gateway.js

Login is slow on purpose

  • BCrypt cost 10 → tens of ms of CPU per check.
  • auth on 1 CPU: roughly 10–20 logins/s.
  • Measured: 10 logins/s kept p99 < 200 ms (~80% CPU); 20 logins/s → 504 at the 5 s timeout.
  • Consequences: reuse tokens, rate-limit /auth/login, log in before 10:00.
for r in 5 10 20 40; do k6 run -q -e RATE=$r --summary-export results/lab4/rate-$r.json load/login.js; done

Without Docker: the simulator

Try it end to end201, 200, 200, 401, 403 · one JWKS download
Failure casesforged header, edited payload, new key, 60 s skew
Edge and replicas/actuator 404, a retried GET, 41 pass and 9 get 429
  • The overview embeds lab 4's stack as a simulator: same requests, same answers.
  • The path lights up as far as each request got; the box that answered shows the status.

What breaks next

lab 4 · the front doorhop + JWT: ms or less; login: 10–20/s per core
→
all state in PostgreSQLpages read ~100× more than they change
→
lab 5 · cachingRedis answers the repeated question
  • Fans log in before 10:00 and reuse the token.

Takeaways

  1. Authenticate once at the gateway; authorize fine-grained where the data lives.
  2. RS256 + JWKS: only auth signs, everyone verifies locally.
  3. Validate exp, iss, aud — not only the signature.
  4. Deny by default; strip identity headers from clients.
  5. The gateway hop and JWT checks are cheap; password hashing is not.

Chapters 4 and 5 of the story. Outline: (1) authn vs authz; (2) sessions vs JWT; (3) RS256 and JWKS; (4) auth service; (5) gateway routes and LB; (6) security rules; (7) identity headers; (8) measurements: hop, JWT, login.

The story of the course (2027.1 overview, "The story of the course"): every chapter opens with the number the previous one left. Lab 4 closes chapter 4 (identity) and builds the front door of chapter 5 (stateless services).

Like the cloud: a public layer-7 load balancer → a fleet of API gateways → internal service load balancing. The page draws the same topology under "What you will build".

The simulator sits right after the failure cases in "Try it end to end".