Chapter 16 of 27 · Part 8: Cross-cutting concerns

Security, configuration and the chassis

Code that passes every test can still leak data, trust the wrong caller, or need a rebuild for each environment. This chapter makes FTGO's services safe to expose and easy to configure, without every team writing the same plumbing again.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 15 we tested how FTGO's services work together: integration tests, consumer-driven contracts, component tests, a few end-to-end journeys, and checks in production. That left one problem open: tested code is still not production-ready. It must also be secure and configurable.

This chapter

What does each FTGO service need, beyond correct business logic, before real customers and real attackers reach it? By the end you can pass a user's identity from the API Gateway to every service, protect credentials and data in layers, decide how far services trust each other, run one build in every environment, and get all of this from a shared chassis.

The session is gone: who is the user?

Problem

FTGO's Order Service passes all its tests and is ready to go live. Then someone asks: when GET /orders/77 arrives, how does Order Service know which customer is asking, and whether that customer may see order 77? In the monolith that question never came up.

A service needs more than working code before it goes to production. It must be secure, configurable and observable. This chapter covers the first two. Chapter 17 covers the third.

Three quality attributes Production-ready service more than working code Secure who can do what Configurable settings at runtime Observable see what it does

Authentication asks who the caller is; authorization asks what that caller may do. In the monolith, login creates a session and returns a cookie (JSESSIONID). On each request an interceptor loads the session into an in-memory security context, where the handler checks roles.

Security in a monolith Client Login handler Interceptor Request handler POST /login JSESSIONID cookie GET + cookie load session → context check roles, handle The session and the in-memory security context do not carry over to separate services.

Split FTGO into services and both pieces break. The session lives in one process, and the security context lives in one thread's memory. Order Service, Kitchen Service and Accounting each receive requests in their own process, with no shared session to look up. Letting every service run its own login would be worse.

Solution · Authenticate at the gateway

Let the API Gateway from chapter 12 authenticate every request, once, in one place. It passes the result to the services as a token. The gateway can block whole URLs by role; only Order Service knows that order 77 belongs to consumer 1234, so each service applies its own per-record rules.

Who checks what Authentication API gateway one place to get it right Authorization Gateway role-based URL access Each service roles + per-record rules
Cost

The gateway becomes security-critical, and every service now depends on what the gateway passes along. What exactly is that token, and how does Order Service check it without asking someone else every time?

Carry the identity along: access tokens and OAuth 2.0

The gateway knows who the user is. Now it has to tell every service in a way they can trust.

Problem

The first design gives each logged-in customer a random token. To place an order, Order Service must call a security service to ask "who owns this token?", and so must Kitchen Service and Accounting further down. At, say, 200 orders a second that is hundreds of extra calls a second, and when the security service is slow, every order is slow.

An opaque token, such as a UUID, means nothing by itself. A transparent token carries the information inside it.

Access token pattern Opaque token Random id like a UUID Service must call to check it Adds latency, lowers availability Transparent token (JWT) Signed: identity, roles, expiry Service checks it locally Cannot be revoked: keep it short-lived
Solution · Access token (JWT)

The gateway passes a JSON Web Token (JWT) with every request. It holds the user's identity, roles and an expiry time, and it is signed. Each service checks the signature locally and reads the user from the token, with no extra call.

The weakness: nobody asks a server about a JWT, so a stolen one cannot be revoked. Keep access tokens short-lived and renew them with a longer-lived, revocable refresh token. OAuth 2.0 is the standard protocol for this, and frameworks such as Spring OAuth provide an authorization server.

OAuth 2.0 vocabulary OAuth 2.0 term In FTGO Authorization server issues tokens (Spring OAuth) Access token short-lived JWT Refresh token long-lived, revocable Resource server each service Client the API gateway

At login, the gateway exchanges the customer's credentials with the authorization server (the OAuth "password grant") for both tokens and returns them as cookies. On GET /orders it forwards the access token to Order Service in an Authorization: Bearer header, and refreshes it when it expires.

Login with OAuth 2.0 Client API gateway Auth server Order svc POST /login + creds password grant access + refresh token tokens as cookies GET /orders + cookie Bearer access token Expired? Gateway uses the refresh token to get a new one.
Cost

Tokens must be issued, signed, renewed and validated, and a stolen token works until it expires. Worse, a token only guards the front door. If an attacker gets in some other way, for example through a hole in a library that Restaurant Service uses, the tokens do not slow them down at all.

One wall is not enough: least privilege and defense in depth

Tokens and encrypted connections are only part of security. Two older principles matter more.

Problem

Restaurant Service uses an open-source web library with a known hole that nobody has patched. An attacker uses it to run code inside the service. Restaurant Service connects to its database with an account that can read and write every table, and the network lets it reach every other service and database. One unpatched library gives the attacker most of FTGO.

Solution · Least privilege and defense in depth

Least privilege: give each party the minimum access it needs, for the shortest time, so a stolen credential is worth little. A read-only account for a read-only job. Defense in depth: never rely on a single barrier. Like a castle with a hill, a moat and two walls, an attacker who gets past one layer meets the next.

Layers of protection Network: segments and firewalls Host or container: patched, least privilege Service: authenticate, authorize, validate input Data encrypted in transit and at rest

Protection is also only one of five functions in the NIST cybersecurity model. If nobody detects the attacker in Restaurant Service, nobody responds or recovers.

Five functions of cybersecurity Identify who attacks? Protect guard assets Detect spot attacks Respond limit damage Recover rebuild/learn NIST model. Teams often stop at Protect and forget the other four.

"Identify" starts with threat modeling: think like an attacker about the whole system. A perfect Accounting next to an unpatched Restaurant Service is a strong front door beside an open window. Three foundations cover much of protect and recover:

FoundationWhat to do
PatchingThe 2017 Equifax breach used an unpatched library. Scan dependencies on every CI build (for example with Snyk or GitHub code scanning) and fail the build on known holes.
BackupsRestore them regularly: an untested backup is a "Schrödinger backup" that may or may not work. Keep them isolated, such as in a separate cloud account, and encrypted.
RebuildAutomate the environment so you can rebuild a compromised system from scratch on demand.
Cost

Security becomes part of every team's delivery work, not a review at the end. Least privilege also multiplies credentials: dozens of services, each with its own database accounts, keys and certificates, on many machines. Each one is a secret that can leak.

Fewer shared secrets, protected data

Least privilege only works if credentials are cheap to create and cheap to throw away.

Problem

All twenty instances of Order Service connect to the order database with the same password. One instance writes it to a log by mistake. To change the password, the team must redeploy all twenty instances at once, and nobody can tell which instance, or which person, leaked it.

Solution · Per-instance credentials from a secret store

Give each instance its own short-lived credential, issued by a secret store such as HashiCorp Vault. A leaked credential can be revoked alone, and the log tells you exactly where it came from.

Sharing one credential versus one per instance One shared password Every instance uses it Rotating means redeploying Hard to trace a leak Credential per instance Each instance has its own Revoke just one A secret store (Vault) issues them Fine-grained credentials only work with automation.
Keep secrets out of code and scripts. A CD workflow should read them from the CI system's secret store, such as GitHub secrets, even a Base64-encoded kubeconfig file. Avoid Terraform outputs for sensitive values: they end up in plain text in the state file.

The data needs protection too. For data in transit there are four concerns:

Four concerns for data in transit Server identity TLS cert who is server? Client identity mTLS or key who is calling? Visibility HTTPS no eavesdropping Manipulation HTTPS or HMAC no tampering HMAC signs a request so the receiver can detect changes, even if the data is not hidden.

For data at rest, such as card details in Accounting: use well-known, reviewed encryption and never invent your own. Hash passwords with a salt. Encrypt data when you first receive it, decrypt it only on demand, and encrypt backups. Be frugal: data you never store cannot be stolen, so keep sensitive values out of logs.

Cost

A secret store is one more critical system to run, and encryption adds key management. Even with TLS everywhere, one question remains: when Accounting receives a request from inside FTGO's network, should it believe it?

Do not trust a call just because it is internal

So far we protected the edge and the data. Now look at the calls between services.

Problem

Accounting accepts any request that comes from inside FTGO's network, on the grounds that only FTGO's own services live there. The attacker who got into Restaurant Service is now inside that network. They send Accounting a refund request, and Accounting pays it.

This is implicit trust: the network perimeter is the only wall. The opposite is zero trust: assume an attacker is already inside, and check every call. Real systems sit somewhere on a spectrum between the two, and zero trust is a way of thinking, not a product you buy.

Implicit trust versus zero trust Implicit trust Inside the network is safe Services accept internal calls One breach exposes all Zero trust Assume attackers are inside Check every inbound call Encrypt all traffic It is a spectrum, and zero trust is a mindset, not a product.
Solution · Service-to-service authentication (mutual TLS)

Make each service prove who it is on every call. With mutual TLS (mTLS), both the client and the server present a certificate, so Accounting knows the caller is Order Service and Order Service knows it is talking to the real Accounting. API keys are a simpler alternative.

Mutual TLS between two services Order svc Accounting hello + client certificate server certificate encrypted request encrypted reply Both sides prove who they are: service-to-service authentication. API keys also work.

Knowing which service calls is not enough, though. A trusted service can still be tricked into acting for the wrong user. This is the confused deputy problem. A logged-in customer asks FTGO's consumer web app for "the orders of user B". The web app is a trusted caller, so Order Service returns B's orders without asking whether the customer is B.

The confused deputy problem Attacker Web app Order svc show orders of user B orders of B (app is trusted) B's orders B's orders Order svc trusted the app, not the user. Fix: pass a signed token (JWT) with the user.

The fix is the JWT from earlier in this chapter: pass the signed user identity along with every call, so Order Service can decide based on the user, not just on the calling service. That raises the question of where to authorize:

Where to authorizeIdeaCatch
Upstream (gateway)Check once, trust everything downstreamImplicit trust again; the gateway must know every service's rules
In each serviceThe service decides using the claims in the JWTServices need the user's identity and roles on every call

Keep the roles in the token coarse-grained and shaped like your organization, such as CUSTOMER, RESTAURANT_OWNER or SUPPORT_AGENT. A role like CALL_CENTER_50_DOLLAR_REFUND pushes one service's business rule into the central user directory and ties that service's changes to another team. Let Accounting decide how large a refund a support agent may give.

Cost

Every service now needs certificates, a secret store address, token signing keys, database credentials and the addresses of the services it calls. Those values are different in test, staging and production, and some of them change while the service runs.

One build, many environments: externalized configuration

Security made each service depend on many settings. Where do those settings live?

Problem

Order Service has the database URL, the Accounting address and the Kafka broker list in a properties file inside its build. To run it in staging, the team edits the file and builds again. The binary that reaches production is not the one that passed the tests, and changing the database password means a new release.

Solution · Externalized configuration

Build each service once and deploy that same build to every environment. Supply the settings from outside at runtime, so only the settings change between test and production.

There are two ways to deliver the settings:

Externalized configuration Push model Env vars, config file set at deploy time Hard to change later spread across services Pull model Config server service asks at startup Central, dynamic decrypts secrets Config servers: Git, Spring Cloud Config, HashiCorp Vault, AWS Parameter Store.
Pull-based configuration Deploy infra sets CONFIG_URL Service starts reads env var Config server returns settings Service runs Kafka, DynamoDB set Same build, many environments: only the settings change.
Cost

A config server is one more piece of infrastructure, and if it is down, services cannot start. Each service also needs code to load its settings. Add token checks, health checks, metrics and tracing headers, and every team is writing the same plumbing in every service.

Stop rebuilding the plumbing: chassis and service mesh

Everything in this chapter, and much of the next two, is a cross-cutting concern: every service needs it, and it has nothing to do with orders or tickets.

Problem

The Kitchen team spends its first two weeks on a new service writing config loading, JWT validation, a health endpoint and metrics, instead of ticket logic. The Delivery team writes the same things differently, with different bugs. When the token format changes, eight teams must each find and fix their own copy.

Solution · Microservice chassis and service mesh

A microservice chassis is a framework, or a set of libraries, that handles cross-cutting concerns for every service, such as Spring Boot with Spring Cloud. A service mesh moves the networking concerns out of the code, into infrastructure that sits beside each service and handles all its traffic. Examples are Istio and Linkerd.

Chassis versus service mesh Microservice chassis Externalized config Health checks Metrics Tracing headers Service mesh Service discovery Circuit breakers, load balancing Traffic routing TLS between services The chassis (Spring Boot + Spring Cloud) is a library. A mesh (Istio, Linkerd) works outside the code.

The two work together: the chassis handles what lives inside the process, and the mesh handles what happens on the wire, including the mutual TLS from earlier in this chapter.

Cost

A chassis is tied to one language and framework, so a team that writes a service in another language needs another chassis. A mesh is powerful but adds moving parts to install, upgrade and debug. And both expose a gap: the chassis gives every service health checks and metrics, but nobody yet collects them across dozens of services to see what is going on.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Authenticate at the API gatewayNo shared session; each service would need its own loginThe gateway becomes security-critical
Access token (JWT)Services must know the user without calling a security service on every requestCannot be revoked; must be short-lived and renewed
OAuth 2.0 with refresh tokensIssuing, renewing and revoking tokens by a standard protocolAn authorization server to run
Least privilege and defense in depthOne breach gives an attacker everythingMany more credentials; security in every team's work
Per-instance credentials from a secret storeA shared password that leaks is hard to rotate or traceA secret store to run; needs automation
Encryption in transit and at restEavesdropping, tampering and stolen dataCertificates and keys to manage
Mutual TLS and zero trustAn attacker inside the network can call any serviceCertificates for every service; often needs a mesh
User identity on every callA trusted service acting for the wrong user (confused deputy)Services must read and check JWT claims
Externalized configurationA rebuild per environment; settings baked into the binaryPush is hard to change; pull adds a config server
Microservice chassis and service meshEvery team rewrites the same cross-cutting codeA chassis per language; a mesh adds operational complexity

Recap

Quick check

Why pass a JWT instead of an opaque token, and what is the catch?
Show answer

A JWT carries a signed identity and roles, so each service can check it locally without calling a security service on every request. The catch is that it cannot be revoked before it expires, so keep it short-lived and renew it with a refresh token.

FTGO's Accounting service accepts refund requests from any caller inside the network. An attacker breaks into Restaurant Service through an unpatched library. What breaks, and which practices would have limited the damage?
Show answer

The attacker can call Accounting directly and issue refunds, because Accounting trusts the network instead of the caller. Patching and dependency scanning in CI would have closed the hole. Mutual TLS would let Accounting reject calls that are not from Order Service, a JWT with the user's identity would let it check who the refund is for, and least-privilege credentials would limit what Restaurant Service's account can reach.

The team rebuilds Order Service for staging and production because the database URL is in a file inside the build. What is wrong, and what is the fix?
Show answer

The binary in production is not the one that was tested, and every settings change needs a release. Externalize the configuration: build once, and supply settings at runtime by pushing environment variables or by pulling them from a config server.

Still open

FTGO's services are now secured, configured and built on a shared chassis that exposes health checks and metrics. But when an order fails somewhere among dozens of services, nobody can see where, or why.

Next: 17 Observability →