System Design Part 8 Security

After BOLA Gets Past the BFF: How Microservices Pass Along Who Is Calling and for Whom

Bill.Lin 20 min read

System Design series Part 8-3 | Previous: Authorization Models and the OWASP API Top 10 | Next: Encryption in Transit and at Rest, and Secrets Management | Series map

Read first: Part 7-2 Service Discovery, Part 8-2 Authorization Models and the OWASP API Top 10.

Scenario and problem

The talk platform’s request path now looks like this:

text
Browser → BFF → Sign-up service → Payment service
                               ↘ Notification service

The BFF confirmed that the user is logged in; following the approach in the previous post, the sign-up service checked that “this sign-up belongs to you”. Next, the sign-up service calls the payment service to issue a refund. When the payment service receives the request, it has to answer two questions:

  1. Which service is calling me? The sign-up service, a compromised recommendation service, or an attacker inside the internal network?
  2. Which user is it acting for? Does this refund belong to that user?
Whom should the payment service trust?1 / 4
Whom should the payment service trust?BrowserBFFSign-up svcIntruderPayment svcBrowserBFFSign-up svcLogged inUser requestThis sign-up is yoursSign-up svcPayment svcRefundWho calls? For whom?Sign-up svcPayment svcRefundFrom inside, so trustedIntruderPayment svcRefund directlyRefunds any payment
  1. The outer layer checked everythingThe BFF confirmed that the user is logged in; the sign-up service checked that "this sign-up belongs to you".
  2. The sign-up service calls paymentsThe sign-up service calls the payment service for a refund. The payment service has to answer two questions: which service is calling me, and which user is it acting for?
  3. Trust whatever comes from insideWhat if the payment service's answer is "the request comes from the internal network, so it must be the sign-up service, and the sign-up service must have checked"...
  4. Going around from the insideIf any machine in the internal network is compromised, the attacker can call the refund API directly and refund any payment. However thorough the authorization checks at the outer layer are, BOLA gets around them from the inside.

If the payment service’s answer is “the request comes from the internal network, so it must be the sign-up service, and the sign-up service must have checked”, then as soon as any machine in the internal network is compromised, an attacker can call POST /v1/refunds directly and refund any payment. However thorough the authorization checks at the outer layer are, BOLA gets around them from the inside.

The simplest approach and its limits

Trust the internal network: a firewall keeps out the outside world, and internal services do not verify each other’s identity.

  • An attacker who gets into any one point of the internal network (a vulnerable service, a phished employee laptop, SSRF) can call every internal API. This is lateral movement

The gateway verifies the token, then passes an X-User-Id header downstream:

  • The downstream service sees X-User-Id: 123 and believes it. But any program that can reach the downstream service can add this header itself and impersonate any user

Pass the user’s access token downstream unchanged:

  • Downstream services can verify the signature, which is better than a header. But the token’s aud must include every service at once (sign-up, payment, notification, and so on), and its scope must cover every permission the whole call chain needs
  • If any downstream service that receives the token is compromised, the attacker gets a token that can call every service, and can reuse it until it expires
  • The permission model of internal services is tied to the format of the external token

Core mechanism

You need both identities

Identity Question it answers How it is proven
Workload identity Which service is calling me? mTLS certificates, tokens obtained with client credentials, Kubernetes service account tokens
User context (subject) Which user is this call acting for, and what is it doing? Exchanged tokens, Transaction Tokens

With only workload identity, the payment service knows “the sign-up service is calling” but not who the user is, so it can only trust the sign-up service. With only user context, the payment service knows who the user is but cannot confirm that the service passing this context along can be trusted.

Workload identity: mTLS and SPIFFE

In ordinary TLS only the server presents a certificate; mTLS has the client present one too, so each side can verify the other’s identity (for the basics of certificates and trust chains, see Web certificate trust).

The service’s identity has to be written into the certificate. SPIFFE defines a uniform format, spiffe://lectures.example.com/ns/lectures/sa/registration, placed in the certificate’s SAN (URI type). Systems such as SPIRE and Istio are responsible for:

  • Confirming that a workload really is the service it claims to be (based on the Kubernetes namespace and service account, the cloud host’s identity, and so on)
  • Issuing short-lived certificates (often around one hour) and rotating them automatically

Short-lived certificates make “revocation” unimportant: once a certificate leaks, it stops working within an hour at most, with no need to rely on CRLs or OCSP.

With workload identity, the payment service can set a policy: accept calls only from the sign-up service and the checkout coordinator. A compromised recommendation service cannot even complete the TLS handshake, or is rejected at the authorization check.

How user context is passed downstream

Approach What the downstream service gets Pros Problems
Pass the original access token The externally issued token, whose aud covers every service No extra components The token has too much permission; any compromised downstream service can reuse it
Header + mTLS X-User-Id, accepted only when sent by specific workloads Simple, no extra latency Once the allowed upstream service is compromised, it can impersonate any user
Token exchange (RFC 8693) A new token at every hop: aud is only the next service, with a narrower scope Already a standard; every token has the least privilege Every hop calls the authorization server (cacheable)
Transaction Token (IETF draft) An internal token exchanged once at the entry point and unchanged along the whole call chain Exchanged only once; carries the transaction context Still a draft; needs an issuing service

Token exchange: narrowing permissions at every hop

sequenceDiagram
    participant F as BFF
    participant R as Sign-up service
    participant A as Authorization server
    participant P as Payment service
    F->>R: access token (aud = sign-up service, sign-up scopes)
    R->>R: Verify the token, check the sign-up belongs to the user
    R->>A: token exchange (subject_token = the received token, authenticates itself with mTLS)
    A->>A: Check that the sign-up service may get a payment service token for this user
    A-->>R: New token (same sub, aud = payment service, refund scope only)
    R->>P: New token, over mTLS
    P->>P: Verify aud and client_id, then check the refunded sign-up belongs to sub
  • The new token’s sub is still the user, its aud is only the payment service, and its scope has only the permissions this hop needs. Even if the payment service is compromised, the token it gets cannot be used to call other services
  • The authorization server can set a policy: only the sign-up service may exchange for a payment service token. The client_id (RFC 9068) in the new token records which client did the exchange; the act claim from RFC 8693 can further record the full delegation chain
  • The cost is one extra call to the authorization server at every hop. A rough estimate: at the peak when sign-ups open there are about 800 sign-up requests per second, and each one exchanges for a payment service token once, so the authorization server takes on an extra 800 token exchanges per second, each adding 5 to 20 milliseconds of latency. Exchanged tokens can be cached per (user, target service) until they expire, but for an operation like signing up, which “each user does only once”, the cache hit rate is very low

Transaction Token (IETF draft)

The IETF OAuth working group’s Transaction Tokens (draft-ietf-oauth-transaction-tokens-11, July 30, 2026; still a working group draft, not yet an RFC, and its content may change) addresses exactly this scenario:

  • When an external request enters at the entry point of a trust domain, the entry point hands the external access token to the Transaction Token Service (TTS) and exchanges it for a Txn-Token. The exchange uses RFC 8693 token exchange, with requested_token_type set to urn:ietf:params:oauth:token-type:txn_token
  • A Txn-Token is a signed JWT whose typ header is txntoken+jwt. Its claims include: a unique ID for the transaction (txn), the user (sub), the trust domain (aud), the purpose of this transaction (scope), the immutable transaction context (tctx, for example “refund, sign-up 1002”), the request environment (rctx, for example the source IP), and the workload that requested the token (req_wl)
  • The draft requires it to be short-lived (minutes or less) and passed in the Txn-Token HTTP header, not the Authorization header, because that header is reserved for service-to-service authentication. Each service that receives it verifies the signature, aud, and expiry, and passes it along unchanged when it calls further downstream
  • The draft states explicitly that a Txn-Token must not be used as an OAuth access token, nor to prove the workload’s own identity: it describes “this transaction”, and workload identity still relies on mechanisms such as mTLS. When a Txn-Token needs to be replaced, the replacement can only narrow permissions, never widen them, and txn, sub, and aud cannot change

Compared with token exchange, a Txn-Token is exchanged only once at the entry point, however deep the call chain goes. The cost is that the token has the same permissions along the whole chain, and it does not prevent replay; it relies only on a short lifetime and deduplication by txn. Until it becomes an RFC, you can treat it as a design reference: exchange once at the entry point, pass immutable transaction context internally, and prove workload identity separately.

Confused deputy: every service checks for itself

To be able to issue refunds, the sign-up service was granted permission to “call the payment service for refunds”. If the payment service checks only that “the caller is the sign-up service”, the sign-up service becomes a deputy that holds refund permission:

  • If some new entry point into the sign-up service (a support tool, a batch job) forgets the ownership check, it can be exploited to refund other people’s payments
  • If the sign-up service is compromised, the attacker uses its identity to refund any payment

This is the confused deputy: a highly privileged service is tricked into doing, for a less privileged user, something that user has no right to do. The fix is for the payment service to check both identities: the caller is the sign-up service (workload), and the sign-up being refunded belongs to this token’s sub (user context). Even though upstream has already checked, downstream still checks, because downstream cannot assume that every entry point of every upstream service is correct.

Asynchronous messages

Messages in a Saga and in Pub/Sub have the same problem:

  • The producer’s identity: the broker authenticates producers with mTLS or SASL and uses ACLs to restrict who can write to which topic. Only the payment service can write to payment-results
  • The user in the message: the memberId in the message body is data, not a credential. Consumers process the message according to its meaning (“this sign-up has been paid”), and must not treat it as “this user authorized me to do anything”
  • Do not put access tokens in messages: a message may be processed long after the token has expired, and it gets stored, replayed, and shows up in the DLQ and in logs

Zero trust

Taken together, these practices are what NIST SP 800-207 calls a zero trust architecture: a request is not trusted just because it comes from the internal network; every request has its identity verified and is authorized with least privilege; trust is decided for each access, not by network location.

Comparing options

Option Good for Cost
Trusting the internal network Only a monolith, or internal tools with no sensitive operations at all One compromised point and everything falls
mTLS + passing the original token downstream Few services, short call chains, all services owned by the same team When a downstream service is compromised, the token can be used to call every service
mTLS + token exchange Highly sensitive downstream services (payments, personal data), call chains that are not deep Latency at every hop and load on the authorization server
mTLS + an internal token exchanged once at the entry point (the Txn-Token approach) Many services, deep call chains Needs an issuing service; the Txn-Token standard is not final yet
A service mesh handles mTLS Many services, with certificates and policies managed centrally Operating the control plane (Service Discovery)

The talk platform’s choice:

  • Workload identity: an internal CA issues short-lived certificates, and all service-to-service calls use mTLS. There are not many services yet, so no service mesh for now
  • User context: the BFF calls the sign-up service with the user’s access token; when the sign-up service calls the payment service, it uses token exchange to get a token whose aud is only the payment service. The notification service needs to know only “whom to send to”, so it is called with an ordinary service identity (client credentials) and does not need the user’s token
  • Payment service: checks both the caller’s client_id and ownership of the refund

In Java

1. mTLS between services

yaml
# Payment service: accept only connections that present a certificate issued by the internal CA
server:
  ssl:
    bundle: payment-server
    client-auth: need

spring:
  ssl:
    bundle:
      pem:
        payment-server:
          reload-on-update: true                       # certificates rotate hourly; reload automatically when the files change
          keystore:
            certificate: "file:/var/run/certs/tls.crt"
            private-key: "file:/var/run/certs/tls.key"
          truststore:
            certificate: "file:/var/run/certs/internal-ca.crt"
yaml
# Sign-up service: present its own certificate when calling the payment service
spring:
  ssl:
    bundle:
      pem:
        registration-client:
          reload-on-update: true
          keystore:
            certificate: "file:/var/run/certs/tls.crt"
            private-key: "file:/var/run/certs/tls.key"
          truststore:
            certificate: "file:/var/run/certs/internal-ca.crt"
  http:
    serviceclient:
      payment:
        base-url: https://payment.lectures.svc.cluster.local
        ssl:
          bundle: registration-client
  • The certificate files are written and periodically renewed by components such as cert-manager or SPIRE; the application only reads them. Spring Boot’s SSL bundle reloading supports the server side on Tomcat and Netty; whether client connections use the new certificate depends on the HTTP client implementation you use, so verify it yourself
  • The private key lives only in the container’s in-memory file system, never in the image or the config repository (8-4)

2. Sign-up service: exchanging for a payment service token

yaml
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://id.lectures.example.com/realms/lectures
          audiences: registration-api
      client:
        registration:
          payment-on-behalf:
            client-id: registration-service
            client-secret: ${idp.registration-service.client-secret}   # read by configtree from the mounted secrets files (8-4)
            authorization-grant-type: urn:ietf:params:oauth:grant-type:token-exchange
            scope: payments.refund
        provider:
          payment-on-behalf:
            token-uri: https://id.lectures.example.com/realms/lectures/protocol/openid-connect/token
java
@Configuration
public class PaymentClientConfig {

    @Bean
    OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository registrations,
                                                          OAuth2AuthorizedClientRepository authorizedClients) {
        OAuth2AuthorizedClientProvider provider = OAuth2AuthorizedClientProviderBuilder.builder()
                .provider(new TokenExchangeOAuth2AuthorizedClientProvider())   // uses the current request's JWT as the subject token
                .clientCredentials()                                           // for calls that need no user context, such as to the notification service
                .build();
        DefaultOAuth2AuthorizedClientManager manager =
                new DefaultOAuth2AuthorizedClientManager(registrations, authorizedClients);
        manager.setAuthorizedClientProvider(provider);
        return manager;
    }

    /** Lets the HTTP service client get and attach the token automatically, based on @ClientRegistrationId. */
    @Bean
    OAuth2RestClientHttpServiceGroupConfigurer securityConfigurer(OAuth2AuthorizedClientManager manager) {
        return OAuth2RestClientHttpServiceGroupConfigurer.from(manager);
    }
}

@HttpExchange("/v1/refunds")
public interface PaymentApi {

    @PostExchange
    @ClientRegistrationId("payment-on-behalf")
    RefundResult refund(@RequestHeader("Idempotency-Key") String idempotencyKey, @RequestBody RefundRequest request);
}

@Configuration
@ImportHttpServices(group = "payment", types = PaymentApi.class)   // applies the URL and SSL bundle from spring.http.serviceclient.payment
public class PaymentApiConfig {
}
  • TokenExchangeOAuth2AuthorizedClientProvider by default takes the subject token from the current JwtAuthenticationToken, that is, the user token the sign-up service received
  • How you specify the target service (the audience or resource parameter) depends on the authorization server; you may need to add extra parameters to the token request
  • Exchanged tokens are stored per user in OAuth2AuthorizedClientService. Spring Boot’s default implementation keeps them in memory with no limit; with many users, replace it with storage that has a size limit and expiry
  • Client authentication here uses a client secret to keep things simple; together with the mTLS from the previous section, you can switch to RFC 8705 mTLS client authentication and need no shared secret

3. Payment service: check the workload, and check the user

java
@Configuration
@EnableWebSecurity
public class PaymentSecurityConfig {

    private static final Set<String> ALLOWED_CALLERS = Set.of("registration-service", "checkout-saga");

    @Bean
    JwtDecoder jwtDecoder(@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") String issuer) {
        NimbusJwtDecoder decoder = JwtDecoders.fromIssuerLocation(issuer);
        OAuth2TokenValidator<Jwt> audience = new JwtClaimValidator<List<String>>(JwtClaimNames.AUD,
                aud -> aud != null && aud.contains("payment-api"));
        // Accept only tokens exchanged by allowed services: the user's own token cannot call the payment service directly
        OAuth2TokenValidator<Jwt> caller = new JwtClaimValidator<String>("client_id",
                clientId -> clientId != null && ALLOWED_CALLERS.contains(clientId));
        decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
                JwtValidators.createDefaultWithIssuer(issuer), audience, caller));
        return decoder;
    }
}

@Service
public class RefundService {

    private final JdbcClient jdbc;

    public RefundService(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    @PreAuthorize("hasAuthority('SCOPE_payments.refund')")
    @Transactional
    public RefundResult refund(RefundCommand command, Jwt onBehalfOf) {
        // User context: this payment must belong to the token's sub; do not just trust that upstream checked
        Payment payment = jdbc.sql("SELECT * FROM payment WHERE id = :id AND member_sub = :sub FOR UPDATE")
                .param("id", command.paymentId())
                .param("sub", onBehalfOf.getSubject())
                .query(Payment.class)
                .optional()
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
        if (command.amount().compareTo(payment.refundableAmount()) > 0) {
            throw new ResponseStatusException(HttpStatusCode.valueOf(422), "Refund amount exceeds the refundable amount");
        }
        // ... deduplicate by Idempotency-Key, then submit the refund (see the idempotency post)
        return RefundResult.accepted(payment.id(), command.amount());
    }
}
  • Validating client_id puts “who can call the payment service” in the token validation layer: a user token that did not go through token exchange has the BFF as its client_id, and is rejected outright
  • JwtClaimValidator receives null for a claim that does not exist, so check for it first, because a set created with Set.of(...) throws an exception on contains(null)
  • The ownership check and the deduplication from Idempotency and Idempotency Keys both happen inside the payment service’s own transaction

The configuration and code above are written from the official Spring Boot 4.1 and Spring Security 7.1 documentation; they have not been compiled or run. The Transaction Token material follows draft-ietf-oauth-transaction-tokens-11 (2026-07-30), and the draft may change.

Pitfalls and gotchas

  • mTLS without authorization: mTLS proves “this is some service with a certificate issued by the internal CA”. If the payment service accepts any valid certificate, a compromised recommendation service can still call it. After verifying identity, you still have to authorize based on that identity
  • mTLS terminated at the ingress: once TLS terminates at the load balancer, the leg to the service is plaintext; the service cannot see the client certificate and can only trust the headers the load balancer forwards (Load Balancing in Depth)
  • Certificate rotation that does not take effect: the certificate files are updated, but the application still uses the old certificate in memory, and the moment it expires, every service-to-service call fails at once. Monitor how much validity your certificates have left
  • An unbounded token exchange cache: tokens cached per user make memory keep growing
  • Writing tokens to logs: the Txn-Token draft states explicitly that a full token must not be written to logs as-is, and the same goes for every kind of token (Observability)
  • Async messages carrying access tokens: by the time the message is consumed, the token has long expired, or it sits stored in the broker and the DLQ
  • Service accounts with too much permission: a service token that the sign-up service obtains with client credentials can refund any user. Every operation performed on behalf of a user should use a token that carries the user context

Attack scenarios

Attack How it happens Defense
Lateral movement After compromising the recommendation service, the attacker calls the internal payment API directly mTLS plus authorization based on workload identity; NetworkPolicy (Service Discovery)
Impersonating users Adding X-User-Id to an internal request to impersonate any user Pass user context in a signed token, not in a plain-text header
Token reuse A compromised downstream service takes the token passed from upstream and uses it to call other services Narrow aud and scope at every hop with token exchange
Confused deputy Using a highly privileged service to do for a user what that user has no right to do Downstream services check both workload and user context, and do their own ownership checks
Forged messages Writing a fake “payment succeeded” to payment-results The broker authenticates producers, and topic ACLs restrict who can write (Sagas and the Outbox Pattern)
Stealing workload credentials Getting a service’s private key from an image, logs, or disk Short-lived certificates rotated automatically; private keys only in in-memory file systems; certificates issued based on the workload’s actual attributes (SPIFFE)
Calling internal services directly from outside A misconfigured port or Ingress exposes an internal service to the internet Internal services require mTLS; without an internal certificate, the handshake cannot complete

When to use it, and when not to

  • Always: calls to internal services must verify workload identity and authorize based on it. “It is on the internal network” is not an excuse
  • Use token exchange: when downstream services handle highly sensitive operations such as payments or personal data, and call chains are not deep
  • Use an internal token exchanged once at the entry point: when there are many services and deep call chains, and the latency and load of exchanging a token at every hop are unacceptable. Until Transaction Tokens are standardized, you can borrow their design, but know that you are implementing a specification that is not final
  • Use the service’s own identity (client credentials): when the operation itself does not act for any user, such as scheduled jobs, reconciliation, or sending system notifications
  • Do not over-design: with only two or three services, maintained by one team, and no highly sensitive operations, mTLS plus passing the original token downstream is enough; get each service’s object-level authorization right first

References

Comments