From 3fba614e50f5041c5a3cd5ccca8e036a0a04977f Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Tue, 20 Oct 2026 05:12:02 +0000 Subject: [PATCH 1/2] Add Spring Kafka consumer reliability skill --- skillbook/skills.json | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/skillbook/skills.json b/skillbook/skills.json index c616b0d..4f03c5f 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -655,6 +655,27 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/entra-service-auth.instructions.md` with applyTo for `**/*Security*Config*.java`, `**/*Jwt*Converter*.java`, `**/*Client*Config*.java`, `**/application*.{yml,yaml,properties}`, and `**/configmap*.yaml`/`**/values*.yaml`. Optional `.github/skills/entra-id-spring-service-auth-guardrails/SKILL.md`. Claude Code: `.claude/skills/entra-id-spring-service-auth-guardrails/SKILL.md` plus a CLAUDE.md fact that the audience comes from the API registration, not the URL, and in-cluster calls still authenticate. Codex: an Entra service-auth section in root `AGENTS.md` or nested `src/main/java/**/security/AGENTS.md`. Builds on spring-security-oauth2-resource-server (generic JWT validation); pair with aks-workload-identity-guardrails for secretless federation, azure-key-vault-app-integration for any remaining certificate/secret, and aks-networkpolicy-zero-trust for in-cluster reachability. This skill covers Entra-specific roles, groups, client credentials, and URL handling.", "body": "# Skill: Entra ID Spring Service-to-Service Auth Guardrails\n\n## Goal\nMake Spring Boot services call each other with Microsoft Entra ID tokens the boring, correct way: callers get app-only tokens with the client credentials grant (secretless on AKS where possible), receivers validate issuer, audience, and tenant, then authorize on **app roles**, never on \"has a valid token\". User access goes through Entra app roles or a config-driven group map, with group overage handled on purpose. The same rules hold whether the target is an external HTTPS URL or an in-cluster `*.svc.cluster.local` address.\n\n## When to apply\n- A Spring Boot API that must accept calls from other services, daemons, or jobs registered in Entra ID (app registration or enterprise app)\n- A Spring Boot service that calls another Entra-protected API with `client_credentials` (RestClient / WebClient / HTTP interface clients)\n- Mapping Entra `roles` / `groups` / `scp` claims into Spring `GrantedAuthority` for `@Secured`, `@PreAuthorize`, or `hasRole`\n- Moving pod-to-pod calls on AKS from shared secrets or \"trusted network\" assumptions to token-based auth\n- Reviews where downstream URLs switch between public hostnames and `svc.cluster.local`, or where tokens appear in logs\n\n## Baseline rules\n1. **One API registration, one audience.** Each receiving API has its own app registration with an Application ID URI (for example `api://orders-api`) and `requestedAccessTokenVersion: 2` in the manifest. In v2 access tokens `aud` is the API's client ID GUID. Validate `aud` explicitly. If v1 tokens are still in flight during migration, allowlist the exact v1 `aud` (`api://…`) and issuer (`https://sts.windows.net/{tid}/`) for a dated window, then remove them.\n2. **Pin issuer and tenant.** Single-tenant: `issuer-uri: https://login.microsoftonline.com/{tenant-id}/v2.0`. Multi-tenant APIs keep an explicit allowlist of `tid` values with one issuer per tenant. Never accept any `iss` that merely looks like Entra. JWKS comes from discovery and stays cached locally, so validation is in-memory on the hot path.\n3. **Service permissions are app roles with `allowedMemberTypes: [\"Application\"]`.** Define roles like `Orders.Read.All` / `Orders.Write.All` on the receiving API. Grant them to the calling app (Entra admin consent). Turn on **Assignment required** on the API's enterprise app so Entra refuses to mint tokens for callers that hold no role. Keep service role names separate from user role names so a user assignment can never satisfy a service-only rule.\n4. **Callers request `{api}/.default`.** With client credentials the scope is always `api://orders-api/.default` (or `{client-id}/.default`). Individual roles cannot be requested. Every granted role arrives in the `roles` claim. App-only tokens have no `scp`.\n5. **Map claims to authorities on purpose.** Use a `JwtAuthenticationConverter` that turns `roles` into `ROLE_` (so `@Secured(\"ROLE_Orders.Write.All\")` and `hasRole(\"Orders.Write.All\")` both work) and `scp` into `SCOPE_`. Put the claim names and prefixes in config, not code. A token with no recognised role gets **no** authorities. It is authenticated, not authorized.\n6. **Tell app-only and delegated tokens apart.** Delegated tokens carry `scp`. App-only tokens carry `roles` and no `scp`. `idtyp=app` is an optional claim, so use it only as a hint. When an endpoint is service-only, require the service role **and** the absence of `scp`. Treat `azp` (v2) / `appid` (v1) as a second check: allowlist the calling client IDs per route group from config.\n7. **Users: prefer app roles over raw groups.** Assign Entra groups to the API's user app roles so tokens carry stable `roles` values. If you must use `groups`, map group **object IDs** (never display names) to roles through a ConfigMap/properties map. Emit only groups assigned to the application to stay under the 200-group JWT limit.\n8. **Group overage fails closed.** When `groups` is missing and `_claim_names` contains `groups` (or `hasgroups` is present), the user is over the limit. Either look up `transitiveMemberOf` through Microsoft Graph with a short-TTL cache, a tight timeout, and `GroupMember.Read.All` consented, or deny with 403. Never fall back to \"no groups means default role\".\n9. **Outbound tokens via Spring's authorized-client machinery.** Register each downstream API as a `spring.security.oauth2.client.registration.` with `authorization-grant-type: client_credentials` and the `/.default` scope. Use `AuthorizedClientServiceOAuth2AuthorizedClientManager`, which works outside request threads (schedulers, consumers) and caches tokens until shortly before expiry. Attach `OAuth2ClientHttpRequestInterceptor` (Spring Security 6.4+) to a RestClient for **that** downstream only. Do not mint a token per request.\n10. **Secretless on AKS.** Prefer AKS Workload Identity: a federated credential on the calling app's registration or managed identity, with the token exchange using the projected service-account token as `client_assertion`. Read the path from `AZURE_FEDERATED_TOKEN_FILE` every time, never hard-code or cache the file contents. Customise the client-credentials token request to send the assertion, or use azure-identity `WorkloadIdentityCredential` behind a small interceptor. Fallback order: certificate (`private_key_jwt`) from Key Vault, then client secret from Key Vault with rotation. Never put a secret in Git, an image, or a plain ConfigMap.\n11. **URLs are config; audience is not derived from the URL.** Downstream base URLs live in ConfigMap/properties per environment, e.g. external `https://api.example.com/orders` or in-cluster `http://orders.orders.svc.cluster.local:8080`. The token audience and scope stay the same whichever URL you use. Bind URLs with `@ConfigurationProperties`, validate them at startup, and never build audiences from `Host` headers.\n12. **Tokens only go to their own downstream.** Put the OAuth2 interceptor on a dedicated RestClient whose base URL is the configured downstream. Do not add it through a global `RestClient.Builder` customiser, because that sends Entra tokens to every third-party host the app calls. Do not follow redirects to other hosts with the `Authorization` header.\n13. **In-cluster is not trusted by default.** Calls to `svc.cluster.local` still carry and validate bearer tokens. NetworkPolicy (see **aks-networkpolicy-zero-trust**) narrows who can reach the port but does not replace auth. Use mesh mTLS or TLS for bearer traffic inside the cluster where the platform provides it. Do not hairpin in-cluster calls through the public ingress just to reuse TLS.\n14. **Fast and bounded.** JWKS cached locally with a refresh-on-unknown-`kid` policy. Outbound token cached and renewed ahead of expiry (default clock skew 60s). Explicit connect/read timeouts on the token endpoint and the downstream call. On a downstream 401, evict the cached token once and retry once. Retries never loop on 401/403.\n15. **Boring errors, no token leakage.** 401 for missing/invalid tokens, 403 for missing role. Never log raw tokens, `Authorization` headers, client secrets, or client assertions. Log `azp`/`appid`, `tid`, the role decision, and a correlation ID instead.\n16. **Test both flows with real claim shapes.** Cover: app-only token with the right role (200), app-only token without the role (403), delegated token hitting a service-only route (403), wrong `aud` / wrong `tid` / expired (401), group-overage user (Graph path or 403), and an outbound call that attaches a cached token from a stubbed token endpoint. `jwt()` from spring-security-test with Entra-shaped claims is fine for slices. Integration tests should run through the real converter and validators.\n\n## Workflow\n1. Inventory: receiving APIs, calling apps, current auth (secrets, API keys, network trust), token versions, existing converters and `@Secured`/`@PreAuthorize` usage, outbound HTTP clients and their base URLs.\n2. Entra model: per API, the Application ID URI, `requestedAccessTokenVersion: 2`, Application-only service roles, user roles assigned to groups, and Assignment required on. Per caller, a granted role set, admin consent, and a credential type (workload identity, then certificate, then secret).\n3. Receiver: issuer + audience + tenant validators, a config-driven `roles`/`scp`/`groups` converter, a service-only rule (role + no `scp` + optional `azp` allowlist), and an overage policy.\n4. Caller: a client registration per downstream, `AuthorizedClientServiceOAuth2AuthorizedClientManager`, a dedicated RestClient with `OAuth2ClientHttpRequestInterceptor`, base URLs from ConfigMap, timeouts, and a single 401 retry.\n5. Platform: workload identity wiring (see **aks-workload-identity-guardrails**), NetworkPolicy for in-cluster paths, Key Vault for any remaining secret or certificate (see **azure-key-vault-app-integration**).\n6. Tests for the matrix in rule 16. PR notes cover audiences, the role matrix (caller → roles → endpoints), the URL map per environment, and residual risks.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/entra-service-auth.instructions.md` with `applyTo` for `**/*Security*Config*.java`, `**/*Jwt*Converter*.java`, `**/*Client*Config*.java`, `**/application*.{yml,yaml,properties}`, and `**/configmap*.yaml` / `**/values*.yaml`.\n- Always-on line in `.github/copilot-instructions.md`: \"Service-to-service calls use Entra client credentials (`/.default`) with app roles; receivers validate iss/aud/tid and authorize on roles, never on token presence.\"\n- Optional `.github/skills/entra-id-spring-service-auth-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/entra-id-spring-service-auth-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Audience comes from the API registration, not the URL. In-cluster svc.cluster.local calls still send and validate bearer tokens.\"\n- Before claiming done, show the role matrix, the converter config, and the passing 401/403 test cases.\n\n### Codex\n- Entra service-auth section in root `AGENTS.md`, or nested `src/main/java/**/security/AGENTS.md` (or linked `docs/agents/entra-service-auth.md`).\n- State: issuer/tenant allowlist, the audience per API, the claim→authority map, service-only rule, overage policy, outbound registration names, URL keys per environment, and banned patterns (global token interceptor, logged tokens, secrets in ConfigMaps).\n\n## Anti-patterns\n- Any valid Entra token passes because only the signature and `iss` are checked, with no `aud` or role check\n- Service roles that also allow `User`, so a user assignment opens a service-only endpoint\n- Requesting individual scopes such as `api://orders-api/Orders.Read` with client credentials and wondering why it fails\n- Mapping group **display names** to roles, or treating a missing `groups` claim as \"no groups\" during overage\n- A new token request on every outbound call, or a token cache keyed per request thread\n- `RestClientCustomizer` adding the OAuth2 interceptor to every client, so tokens leak to third-party hosts\n- Deriving the audience from the target hostname, so `svc.cluster.local` and external URLs get different (or wrong) audiences\n- Skipping auth for in-cluster callers because \"only our pods can reach it\"\n- Client secrets in ConfigMaps, images, or `application.yml` in Git, or a hard-coded workload identity token path\n- Logging `Authorization` headers or full JWTs while debugging, and shipping that to prod\n\n## Done when\n- [ ] Each API has its own audience, `requestedAccessTokenVersion: 2`, and a validated `iss` + `aud` (+ `tid` allowlist if multi-tenant)\n- [ ] Service roles are Application-only and Assignment required is on for the API's enterprise app\n- [ ] The converter maps `roles` → `ROLE_`, `scp` → `SCOPE_`, groups by object ID from config, and overage is handled or fails closed\n- [ ] Service-only routes require role + no `scp` (+ `azp`/`appid` allowlist where used)\n- [ ] Callers use `client_credentials` with `/.default` through a cached authorized-client manager and a dedicated RestClient per downstream\n- [ ] Credentials are workload identity (or a Key Vault certificate/secret), and nothing secret is in Git or ConfigMaps\n- [ ] External and `svc.cluster.local` base URLs come from config, use the same audience, and in-cluster calls still authenticate\n- [ ] Timeouts, a single 401 retry, and no token or secret in logs\n- [ ] Tests cover the rule 16 matrix and pass in CI\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: entra-id-spring-service-auth-guardrails\ndescription: Use when wiring or reviewing Microsoft Entra ID service-to-service auth in Spring Boot — client credentials callers, app-role and group-to-role mapping, iss/aud/tid validation, workload identity on AKS, and external vs svc.cluster.local URLs.\n---\n\nFollow Entra ID Spring Service-to-Service Auth Guardrails: one audience per API (v2 tokens), pinned issuer/tenant, Application-only app roles with assignment required, `/.default` client credentials through a cached authorized-client manager on a dedicated RestClient, roles→ROLE_ and scp→SCOPE_ from config, groups by object ID with fail-closed overage, service-only routes need role + no scp, workload identity before secrets, URLs from ConfigMap with the audience unchanged, in-cluster calls still authenticated, and no tokens in logs.\n```\n" + }, + { + "id": "spring-kafka-consumer-reliability-guardrails", + "title": "Spring Kafka Consumer Reliability Guardrails", + "whenToUse": "Writing or reviewing Spring for Apache Kafka consumers — at-least-once idempotent handlers, ack modes, DefaultErrorHandler backoff and retryable vs non-retryable exceptions, DLT and @RetryableTopic, poison pills, poll sizing, concurrency vs partitions, rebalance and shutdown, lag metrics, tests, and SASL/TLS.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "spring-kafka", + "kafka", + "messaging", + "reliability", + "idempotency", + "java" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-kafka-consumer.instructions.md` with applyTo for `**/*Listener*.java`, `**/*Consumer*.java`, `**/*Kafka*Config*.java`, `**/application*.{yml,yaml,properties}`, and topic manifests (`**/kafkatopic*.yaml`, `**/topics/**`). Optional `.github/skills/spring-kafka-consumer-reliability-guardrails/SKILL.md`. Claude Code: `.claude/skills/spring-kafka-consumer-reliability-guardrails/SKILL.md` plus a CLAUDE.md fact that every record may arrive twice and nothing is acked before the side effect is durable. Codex: a Kafka consumer section in root `AGENTS.md` or nested `src/main/java/**/messaging/AGENTS.md`. Pair with spring-boot-testcontainers for the Kafka test harness, spring-boot-micrometer-prometheus-guardrails for metric conventions, k8s-probes-graceful-shutdown-guardrails for the shutdown timeout chain, aks-hpa-requests-limits-guardrails for KEDA/HPA caps, and azure-key-vault-app-integration for SASL credentials. This skill owns consumer delivery semantics, error handling, and DLTs.", + "body": "# Skill: Spring Kafka Consumer Reliability Guardrails\n\n## Goal\nMake Spring for Apache Kafka consumers safe to run in production. Kafka delivers at least once, so every handler has to be idempotent. Offsets are committed only after the work is done. Transient failures retry with bounded backoff, while bad data and poison pills go straight to a dead-letter topic you own. Rebalances and rolling restarts must not lose or double-apply side effects, and lag is visible before users notice it.\n\n## When to apply\n- New `@KafkaListener` consumers, or reviews of an existing `ConcurrentKafkaListenerContainerFactory` / `spring.kafka.consumer.*` / `spring.kafka.listener.*` setup\n- Incidents involving duplicates, lost messages, stuck partitions, rebalance storms, or a consumer that \"looks healthy\" but stopped consuming\n- Adding retries, a DLT, or `@RetryableTopic` non-blocking retries\n- Consumers that write to a database, call HTTP APIs, or produce to other topics (side effects that must not run twice)\n- AKS / Kubernetes deployments where scaling, rolling updates, or KEDA change the number of consumer instances\n\n## Baseline rules\n1. **Design for at-least-once.** Assume every record can arrive more than once: after a rebalance, a crash before commit, a retry, or a DLT replay. Exactly-once is only real for Kafka-to-Kafka read-process-write with transactions (`transactional.id` on the producer, `isolation.level=read_committed` on downstream consumers). A database write or HTTP call is never covered by Kafka transactions.\n2. **Idempotent handlers with a dedupe key.** Pick a stable key per message: a producer-assigned event ID header, or a business key such as order ID plus version. Fall back to `topic-partition-offset` only when the source can't give you one, because a producer retry creates a new offset. Use an **inbox** table with a unique constraint on (consumer group, message key) and write it in the same DB transaction as the side effect. A duplicate then becomes a no-op insert conflict. When the handler also emits events, write them to an **outbox** table in that same transaction instead of calling `KafkaTemplate` inline.\n3. **Commit after work, never before.** Keep `enable.auto.commit=false` (Spring's default). The container default `AckMode.BATCH` commits after the whole poll is processed. `RECORD` commits after each record and costs more broker round trips. Use `MANUAL` / `MANUAL_IMMEDIATE` only when the handler finishes asynchronously, and acknowledge only after the side effect is durable. Never acknowledge, then hand off to another thread and hope.\n4. **One error handler, owned by the container.** Register a single `DefaultErrorHandler` bean (Boot wires it into the auto-configured factory). Give it a bounded `BackOff`, such as `ExponentialBackOffWithMaxRetries` (for example 1s, 2s, 4s, capped at 10s, 4 to 6 retries). Do not wrap the listener body in a Resilience4j / Spring Retry loop as well, because that multiplies attempts and hides the delivery count.\n5. **Classify exceptions explicitly.** Retryable means transient: timeouts, 503s, deadlocks, broker unavailable. Non-retryable means it will never succeed: validation failures, unknown schema version, business rule violations, 4xx from a downstream. Add your own types with `addNotRetryableExceptions(...)`. The framework already treats `DeserializationException`, `MessageConversionException`, `ClassCastException` and similar as fatal. Application exceptions must extend `RuntimeException`: anything extending `Error` bypasses the handler and kills the consumer thread.\n6. **Dead-letter on exhaustion, with a real DLT.** Use `DeadLetterPublishingRecoverer` as the recoverer. The default destination is `-dlt` on the same partition, so the DLT needs **at least as many partitions** as the source (or use a resolver that returns a negative partition). Provision DLTs with IaC, set retention, and name an owner. Alert on DLT publish rate and document a replay path. Exclude the stack-trace header (`excludeHeaders(EX_STACKTRACE)`) when exception messages could carry payload data or PII.\n7. **Blocking vs non-blocking retries are a choice about ordering.** `DefaultErrorHandler` retries in place and keeps per-partition order, but it blocks that partition. `@RetryableTopic` moves the record to `-retry` topics and finally `-dlt` (default suffixes; Spring Kafka 4.1+ reuses one retry topic per interval). That frees the partition but **breaks per-key ordering**, and it is not supported for batch listeners. Use it only when ordering doesn't matter, pre-create the retry topics where broker auto-create is off, and keep non-blocking fatal exceptions aligned with rule 5.\n8. **Poison pills never loop.** Wrap both key and value deserializers in `ErrorHandlingDeserializer` (`spring.deserializer.key.delegate.class` / `spring.deserializer.value.delegate.class`). A record that can't be deserialized then reaches the error handler as a fatal `DeserializationException` and goes to the DLT with its original bytes, instead of failing at `poll()` forever. For JSON, configure explicit type mappings or a narrow trusted-packages list, never `*`. Batch listeners must check for `null` values and throw `BatchListenerFailedException` with the failing record or index.\n9. **Size the poll loop against `max.poll.interval.ms`.** Rough budget: `max.poll.records` × p99 handling time + worst-case blocking backoff, with at least 2x headroom under `max.poll.interval.ms` (default 5 minutes). Lower `max.poll.records` (default 500) for slow handlers instead of raising the interval to hours. When backoff delays approach the poll interval, use `ContainerPausingBackOffHandler` or non-blocking retries. Missing the interval triggers a rebalance and redelivery, which is how duplicates start.\n10. **Concurrency follows partitions.** Each container thread owns whole partitions, so `concurrency` × replicas above the partition count leaves idle consumers. Set `concurrency` ≤ partitions per instance and plan the partition count for peak parallelism. With KEDA or HPA, cap max replicas at partitions ÷ concurrency (see **aks-hpa-requests-limits-guardrails**). Per-key ordering holds only within a partition, so key records by the entity whose order matters.\n11. **Gentle rebalances and graceful shutdown.** Use `CooperativeStickyAssignor` (`partition.assignment.strategy`) so a rebalance moves only the partitions that need to move. If brokers support the newer consumer group protocol (`group.protocol=consumer`, Kafka 4.x), prefer it. Consider static membership (`group.instance.id` from the pod name) so rolling restarts within `session.timeout.ms` don't rebalance at all. On shutdown, let the container finish the in-flight batch and commit: keep the container `shutdownTimeout` and `spring.lifecycle.timeout-per-shutdown-phase` below the pod `terminationGracePeriodSeconds` (see **k8s-probes-graceful-shutdown-guardrails**). Flush pending work in a `ConsumerAwareRebalanceListener` when you hold state per partition.\n12. **Lag and failure metrics through Micrometer.** Boot binds Kafka client metrics to Micrometer, so you get `kafka.consumer.fetch.manager.records.lag.max` and friends, plus `spring.kafka.listener` timers for handler duration and outcome. Add counters for retries (a `RetryListener` on the error handler), DLT publishes, and dedupe hits. Keep tags bounded (listener ID, topic, outcome), never keys or payload fields. Client-side lag disappears when the consumer is down, so also alert on consumer group lag from the broker side (an exporter or your managed Kafka's metrics). Dashboard conventions: **spring-boot-micrometer-prometheus-guardrails**.\n13. **Liveness tells the truth.** A dead listener thread must not report healthy. Watch `ConsumerStoppedEvent` / `ListenerContainerIdleEvent` or use a small health contributor on container state. Keep broker reachability out of **liveness** so a broker blip doesn't restart every pod.\n14. **Security: TLS + SASL, no credentials in code.** Use `security.protocol=SASL_SSL` with SCRAM or OAUTHBEARER (for example Entra ID for Azure Event Hubs' Kafka endpoint). The JAAS config, passwords, and connection strings come from Kubernetes secrets or Key Vault through environment placeholders (see **azure-key-vault-app-integration**). Never put them in `application.yml` in Git, a ConfigMap, or Java code. Mount truststores from secrets. Never log record values or full headers: log topic, partition, offset, key hash, and a correlation ID.\n15. **Test failure paths, not only the happy path.** Use Testcontainers Kafka with `@ServiceConnection` for integration tests (see **spring-boot-testcontainers**), or `@EmbeddedKafka` for fast in-JVM slices. Cover: the same record delivered twice gives one side effect; a transient failure retries and then succeeds; a non-retryable exception goes to the DLT on the first failure; a poison-pill payload reaches the DLT with its original bytes; shutdown or rebalance mid-batch loses no committed work. Use Awaitility for assertions, never fixed sleeps.\n\n## Workflow\n1. Inventory: listeners (record vs batch), container factories, ack mode, current error handler and backoff, deserializers, retry/DLT topics, transaction usage, side effects per handler, and partitions vs concurrency vs replicas.\n2. Delivery semantics: for each handler, write down the dedupe key and where it is enforced (inbox table, upsert, natural idempotency). Add inbox/outbox where a side effect is not idempotent.\n3. Error path: one `DefaultErrorHandler` with bounded backoff, explicit non-retryable exceptions, a `DeadLetterPublishingRecoverer`, and `ErrorHandlingDeserializer` on key and value. Decide blocking vs `@RetryableTopic` per listener based on ordering.\n4. Poll loop and scaling: check the `max.poll.records` / `max.poll.interval.ms` budget, the cooperative-sticky assignor (or the new group protocol), static membership, concurrency ≤ partitions, and replica caps.\n5. Ops: the shutdown timeout chain, lag/retry/DLT metrics and alerts, the liveness signal, and SASL/TLS settings sourced from secrets.\n6. Tests for the rule 15 matrix. PR notes cover the dedupe key per handler, the exception classification table, DLT names and owners, the poll-budget math, and residual risks.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spring-kafka-consumer.instructions.md` with `applyTo` for `**/*Listener*.java`, `**/*Consumer*.java`, `**/*Kafka*Config*.java`, `**/application*.{yml,yaml,properties}`, and topic manifests (`**/kafkatopic*.yaml`, `**/topics/**`).\n- Always-on line in `.github/copilot-instructions.md`: \"Kafka consumers are at-least-once: handlers are idempotent on a dedupe key, offsets commit after work, one DefaultErrorHandler with bounded backoff routes non-retryable and poison records to the DLT.\"\n- Optional `.github/skills/spring-kafka-consumer-reliability-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/spring-kafka-consumer-reliability-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Every Kafka record may arrive twice. Never ack before the side effect is durable, and never retry around the container's error handler.\"\n- Before claiming done, show the exception classification table, the DLT topic list with partition counts, and the passing duplicate / poison-pill / non-retryable tests.\n\n### Codex\n- Kafka consumer section in root `AGENTS.md`, or nested `src/main/java/**/messaging/AGENTS.md` (or linked `docs/agents/spring-kafka-consumer.md`).\n- State: ack mode policy, dedupe-key convention and inbox table, error handler and backoff defaults, retryable vs non-retryable lists, DLT naming and ownership, poll-budget rule, concurrency ≤ partitions, shutdown timeouts, and banned patterns (auto-commit, ack-before-work, nested retry loops, credentials in config).\n\n## Anti-patterns\n- `enable.auto.commit=true`, or acknowledging as soon as the record arrives \"so we don't block\"\n- Handlers that insert, charge, or email without any dedupe check because \"Kafka is exactly-once\"\n- Wrapping the listener in `@Retryable` or a Resilience4j retry on top of `DefaultErrorHandler`\n- `FixedBackOff` with unlimited attempts, so one bad record blocks a partition forever\n- No `ErrorHandlingDeserializer`, so a malformed payload fails at `poll()` in a tight loop\n- `@RetryableTopic` on a stream where per-key order matters, or on a batch listener\n- A DLT with fewer partitions than the source, auto-created with no retention, owner, or alert\n- Raising `max.poll.interval.ms` to hours instead of shrinking `max.poll.records` or fixing slow handlers\n- `concurrency=20` on a 6-partition topic, or KEDA scaling to more pods than partitions\n- Business exceptions that extend `Error`, or liveness that stays green after the listener thread died\n- SASL passwords in `application.yml`, ConfigMaps, or code; record payloads in logs or metric tags\n\n## Done when\n- [ ] Every handler has a documented dedupe key and an enforced idempotency mechanism (inbox, upsert, or natural)\n- [ ] Auto-commit is off, the ack mode is deliberate, and nothing is acknowledged before the side effect is durable\n- [ ] One `DefaultErrorHandler` with bounded backoff, explicit non-retryable exceptions, and a `DeadLetterPublishingRecoverer`\n- [ ] `ErrorHandlingDeserializer` wraps key and value, and JSON type trust is explicit (no `*`)\n- [ ] DLT (and any retry topics) are provisioned with partitions ≥ source, retention, an owner, alerts, and a replay note\n- [ ] The `max.poll.records` × p99 + backoff budget fits under `max.poll.interval.ms` with headroom\n- [ ] Concurrency × max replicas ≤ partitions; cooperative-sticky (or the new group protocol) and shutdown timeouts fit the pod grace period\n- [ ] Lag, retry, DLT, and dedupe-hit metrics are exported with bounded tags, and broker-side group lag is alerted\n- [ ] SASL_SSL/TLS configured, with credentials from secrets or Key Vault only and no payloads in logs\n- [ ] Tests cover the rule 15 matrix and pass in CI\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-kafka-consumer-reliability-guardrails\ndescription: Use when writing or reviewing Spring for Apache Kafka consumers — at-least-once idempotent handlers, ack modes, DefaultErrorHandler backoff and exception classification, DLT and @RetryableTopic, poison pills, poll sizing, concurrency vs partitions, rebalance/shutdown, lag metrics, tests, and SASL/TLS.\n---\n\nFollow Spring Kafka Consumer Reliability Guardrails: assume at-least-once and make every handler idempotent on a dedupe key (inbox/outbox), commit after work with auto-commit off, one DefaultErrorHandler with bounded backoff and explicit non-retryable exceptions, DeadLetterPublishingRecoverer to an owned DLT with partitions ≥ source, ErrorHandlingDeserializer for poison pills, @RetryableTopic only when ordering doesn't matter, max.poll.records sized under max.poll.interval.ms, concurrency × replicas ≤ partitions, cooperative-sticky rebalances with shutdown inside the pod grace period, Micrometer lag/retry/DLT metrics with bounded tags, failure-path tests on Testcontainers or EmbeddedKafka, and SASL_SSL with credentials only from secrets.\n```\n" } ] } From c95f530f2e22e3bb12e5d0d508992b075462f5c8 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Tue, 20 Oct 2026 05:12:02 +0000 Subject: [PATCH 2/2] Add harden Spring Kafka consumer prompt --- promptbook/prompts.json | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 59637a3..215621e 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -657,6 +657,27 @@ ], "formatNotes": "All three. Point the tool at `application.yml`/`application.properties`, the `SecurityFilterChain` and JWT converter, outbound RestClient/WebClient config, and the ConfigMap/Helm values that hold downstream URLs. Keep generic JWT validation aligned with spring-security-oauth2-resource-server. Copilot: entra-service-auth path instructions plus those files in agent mode. Claude Code: the entra-id-spring-service-auth-guardrails skill plus the security config and deploy values. Codex: AGENTS.md Entra service-auth section, then the diff.", "body": "Task: Wire or harden Microsoft Entra ID service-to-service auth for the Spring Boot service(s) I specify. The receiving side should validate Entra tokens and authorize on app roles. The calling side should get cached client-credentials tokens without secrets in Git. Both should work for external HTTPS URLs and in-cluster `svc.cluster.local` URLs. Finish with a minimal diff I can open as a PR.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service root / module: {{APP_PATH}}\n- Role of this service: {{SERVICE_ROLE}} (receiver | caller | both)\n- Spring Boot / Spring Security version: {{BOOT_VERSION}} (e.g. 3.4 / 6.4 | unknown)\n- Tenant ID(s): {{TENANT_IDS}} (single GUID | allowlist | unknown)\n- This API's Application ID URI and client ID (receiver): {{API_APP_ID_URI}} / {{API_CLIENT_ID}}\n- Token version today: {{TOKEN_VERSION}} (v2 | v1 | mixed | unknown)\n- Service app roles → endpoints (receiver): {{SERVICE_ROLE_MATRIX}} (e.g. Orders.Read.All → GET /api/orders/**)\n- User authorization source (receiver): {{USER_AUTHZ}} (app-roles | groups-map | none)\n- Allowed caller client IDs (optional): {{ALLOWED_CALLERS}}\n- Downstream APIs (caller): {{DOWNSTREAMS}} (name, Application ID URI, base URL per env — e.g. external https://api.example.com/orders, in-cluster http://orders.orders.svc.cluster.local:8080)\n- Caller credential: {{CREDENTIAL}} (aks-workload-identity | certificate | client-secret | unknown)\n- Environments / config source: {{ENVIRONMENTS}} (e.g. aks-dev, aks-prod via ConfigMap + Key Vault)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}} build file, `application*.yml|properties`, `SecurityFilterChain` config, any `JwtAuthenticationConverter`, and `@Secured` / `@PreAuthorize` usage\n - List outbound HTTP clients (RestClient, WebClient, HTTP interface clients, RestTemplate), their base URLs, and how tokens are attached today\n - Find secrets, API keys, or \"trusted network\" shortcuts on service-to-service paths, and any Authorization header or JWT logging\n - Note ConfigMap / Helm values / Key Vault references under deploy paths\n\n2. Findings (rank by risk: missing aud/role checks > token sent to wrong host > secrets in Git/ConfigMap > unauthenticated in-cluster path > overage/role-mapping gaps > hygiene)\n - Tokens accepted on signature + issuer alone, with no `aud`, `tid`, or role check\n - Service-only routes reachable with delegated (user) tokens, or service roles that also allow users\n - Group display names used for roles, or a missing `groups` claim treated as \"no groups\"\n - Per-request token minting, or the OAuth2 interceptor added to every client globally\n - Audience or scope derived from the target URL, or different behaviour for `svc.cluster.local` vs external\n - Client secrets in Git, images, or plain ConfigMaps, or a hard-coded workload identity token path\n\n3. Fix — receiver (skip if {{SERVICE_ROLE}} = caller)\n - `spring.security.oauth2.resourceserver.jwt.issuer-uri: https://login.microsoftonline.com/{{TENANT_IDS}}/v2.0` (or a per-tenant issuer allowlist), plus an audience validator for {{API_CLIENT_ID}}. If {{TOKEN_VERSION}} is mixed, allowlist the exact v1 issuer/audience with a removal date\n - A converter driven by properties: `roles` → `ROLE_`, `scp` → `SCOPE_`, optional group object ID → role map from ConfigMap when {{USER_AUTHZ}} = groups-map\n - Group overage: detect `_claim_names.groups` / `hasgroups`. Either do a Graph `transitiveMemberOf` lookup with a cache and timeout, or return 403. Never assign a default role\n - Service-only rule for {{SERVICE_ROLE_MATRIX}}: required role and no `scp`, plus an `azp`/`appid` allowlist from {{ALLOWED_CALLERS}} when given\n - Recommend manifest changes as notes (don't apply them): `requestedAccessTokenVersion: 2`, Application-only service roles, Assignment required on the enterprise app\n\n4. Fix — caller (skip if {{SERVICE_ROLE}} = receiver)\n - One `spring.security.oauth2.client.registration.` per entry in {{DOWNSTREAMS}}: `authorization-grant-type: client_credentials`, `scope: /.default`, and a provider `token-uri: https://login.microsoftonline.com//oauth2/v2.0/token`\n - An `AuthorizedClientServiceOAuth2AuthorizedClientManager` bean, plus a **dedicated** RestClient per downstream with `OAuth2ClientHttpRequestInterceptor` and the registration ID. No global customiser\n - Base URLs bound with `@ConfigurationProperties` from ConfigMap keys per environment (external and `svc.cluster.local`), validated at startup. The audience/scope stays the same whichever URL is used\n - Credential per {{CREDENTIAL}}. Workload identity: a federated client assertion read from `AZURE_FEDERATED_TOKEN_FILE` on each exchange. Certificate/secret: from Key Vault, never inline\n - Connect/read timeouts on the token endpoint and the downstream. On a 401, evict the token and retry once. No retry loops on 401/403\n\n5. Tests\n - Receiver: app token with role → 200; app token without role → 403; delegated token on service-only route → 403; wrong `aud` / wrong `tid` / expired → 401; overage user → Graph path or 403\n - Caller: a stubbed token endpoint is called once for several downstream calls (cached), the token goes only to the configured host, and 401 → one refresh + retry\n - Use Entra-shaped claims (`roles`, `scp`, `azp`, `tid`, `ver`) through the real converter and validators\n\n6. Verification\n - Role matrix table: caller client ID → granted roles → endpoints\n - URL map per environment (external vs in-cluster) showing the same audience\n - Confirm there are no tokens or secrets in logs, ConfigMaps, or Git, and list NetworkPolicy / mTLS expectations for in-cluster paths\n\nConstraints:\n- Minimal diff. Extend the existing `SecurityFilterChain` and clients; don't add a second permissive chain.\n- Don't invent tenant IDs, client IDs, secrets, or hostnames. Use placeholders if unknown.\n- Don't disable auth for in-cluster callers or for any prod profile.\n- Optimize for GitHub Copilot, Claude Code, and Codex: give concrete diffs and a checklist.\n- Leave Entra portal / IaC changes as explicit follow-up notes unless the repo already manages them.\n\nOutput format:\n1. Findings table: severity | location | issue | fix\n2. Patch (config + converter/validators + security rules + client registrations/RestClients + ConfigMap keys)\n3. Tests added and their results\n4. Role matrix, URL map, and follow-ups (manifest changes, workload identity federation, NetworkPolicy)\n\nStart from {{APP_PATH}}. Close missing aud/role checks and token-to-wrong-host leaks before anything else.\n" + }, + { + "id": "harden-spring-kafka-consumer", + "title": "Harden a Spring Kafka Consumer", + "whenToUse": "Make a Spring for Apache Kafka consumer production-safe (idempotent handlers with a dedupe key, commit after work, bounded DefaultErrorHandler retries with exception classification, owned DLT, poison-pill handling, poll sizing, concurrency vs partitions, graceful rebalance and shutdown, lag metrics, SASL/TLS from secrets) and produce a minimal diff with failure-path tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "spring-kafka", + "kafka", + "messaging", + "reliability", + "idempotency", + "java" + ], + "formatNotes": "All three. Point the tool at `application.yml`/`application.properties` (`spring.kafka.*`), the `@KafkaListener` classes, container factory and error-handler config, any inbox/outbox migrations, and the topic manifests or IaC for source, retry, and DLT topics. Keep test harness conventions aligned with spring-boot-testcontainers. Copilot: spring-kafka-consumer path instructions plus those files in agent mode. Claude Code: the spring-kafka-consumer-reliability-guardrails skill plus the listener, config, and topic files. Codex: AGENTS.md Kafka consumer section, then the diff.", + "body": "Task: Harden the Spring for Apache Kafka consumer(s) I specify for production. Make handlers idempotent under at-least-once delivery, commit offsets only after work, retry transient failures with bounded backoff, and route non-retryable and poison records to an owned dead-letter topic. Rebalances and shutdowns should not lose or double-apply work. Finish with a minimal diff I can open as a PR, plus tests for the failure paths.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service root / module: {{APP_PATH}}\n- Spring Boot / Spring Kafka version: {{BOOT_VERSION}} (e.g. 3.5 / 3.3, 4.0 / 4.0 | unknown)\n- Listeners in scope: {{LISTENERS}} (listener id → topic(s), record | batch)\n- Topic partitions and consumer group: {{PARTITIONS}} (e.g. orders.v1: 12 partitions, group orders-svc)\n- Replicas / autoscaling: {{REPLICAS}} (fixed N | HPA min-max | KEDA min-max)\n- Side effects per handler: {{SIDE_EFFECTS}} (db-write | http-call | produce-to-topic | email | none)\n- Dedupe key available: {{DEDUPE_KEY}} (event-id header | business key | none | unknown)\n- Ordering requirement: {{ORDERING}} (per-key order required | order irrelevant)\n- Retry/DLT today: {{RETRY_TODAY}} (none | DefaultErrorHandler defaults | custom | @RetryableTopic)\n- Broker / security: {{BROKER}} (e.g. Confluent Cloud SASL_SSL SCRAM | Azure Event Hubs Kafka OAUTHBEARER | Strimzi mTLS)\n- Pain points: {{PAIN}} (duplicates | lost-messages | stuck-partition | rebalance-storm | lag | poison-pill | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}} build file, `application*.yml|properties` (`spring.kafka.*`), every `@KafkaListener`, container factories, and any `CommonErrorHandler`, `RetryTopicConfiguration`, or `@RetryableTopic` usage\n - Record per listener: ack mode, record vs batch, concurrency, deserializers, transaction use, and what each side effect does\n - Find retry wrappers around listener bodies (`@Retryable`, Resilience4j, hand-written loops), auto-commit settings, and early or async acknowledgements\n - Note topic manifests or IaC for source, retry, and DLT topics; consumer metrics and alerts; SASL/TLS config and where credentials come from\n\n2. Findings (rank by risk: non-idempotent side effects > ack-before-work / auto-commit > poison-pill loops or unbounded retries > missing or unowned DLT > poll-interval / rebalance risks > concurrency vs partitions > observability and test gaps > hygiene)\n - Side effects with no dedupe key or inbox, so duplicates double-charge, double-insert, or double-send\n - `enable.auto.commit=true`, acknowledging before the side effect is durable, or acks from another thread without ordering care\n - Missing `ErrorHandlingDeserializer`, `FixedBackOff` with unlimited attempts, or nested retry loops on top of the container error handler\n - No exception classification: validation and business errors retried like timeouts\n - DLT missing, auto-created, with fewer partitions than the source, or with no owner, alert, or replay path\n - `@RetryableTopic` where {{ORDERING}} = per-key order required, or on a batch listener\n - `max.poll.records` × p99 handling time + backoff near or above `max.poll.interval.ms`\n - Concurrency × max replicas above {{PARTITIONS}}, eager assignor, or shutdown timeouts longer than the pod grace period\n - Credentials in Git, ConfigMaps, or code; record payloads in logs or metric tags\n\n3. Fix\n - Idempotency: for each handler in {{SIDE_EFFECTS}}, use {{DEDUPE_KEY}} (or propose one). Add an inbox table with a unique (consumer group, message key) constraint written in the same DB transaction as the side effect, or an upsert keyed on the business key. Route outbound events through an outbox where the handler also produces\n - Commits: `enable.auto.commit=false`. Keep `AckMode.BATCH` unless the handler completes asynchronously; then `MANUAL_IMMEDIATE` with the ack after the durable write\n - Error handler: one `DefaultErrorHandler` bean with `ExponentialBackOffWithMaxRetries` (start around 1s, ×2, cap 10s, 4 to 6 retries unless the SLO says otherwise), `addNotRetryableExceptions(...)` for validation / business / 4xx types, and a `DeadLetterPublishingRecoverer`. Remove nested retry wrappers. Make sure application exceptions extend `RuntimeException`\n - DLT: name `-dlt` (or the repo's convention), partitions ≥ source, retention and owner in the topic manifest or IaC, and exclude the stack-trace header if messages can carry PII\n - Non-blocking retries: only if {{ORDERING}} = order irrelevant and the listener is record-based. `@RetryableTopic` with bounded attempts and backoff, retry and DLT topics pre-provisioned, and fatal exceptions matching the blocking classification\n - Poison pills: `ErrorHandlingDeserializer` around key and value delegates, explicit JSON type mapping or narrow trusted packages, and for batch listeners a `null` check that throws `BatchListenerFailedException` with the record or index\n - Poll loop: set `max.poll.records` so `max.poll.records` × p99 + max blocking backoff fits under half of `max.poll.interval.ms`. Use `ContainerPausingBackOffHandler` if backoffs are long\n - Scaling and rebalance: `concurrency` ≤ partitions per instance and max replicas ≤ partitions ÷ concurrency for {{REPLICAS}}; `CooperativeStickyAssignor` (or `group.protocol=consumer` when the broker supports it); optional `group.instance.id` from the pod name; container `shutdownTimeout` and `spring.lifecycle.timeout-per-shutdown-phase` below `terminationGracePeriodSeconds`\n - Observability: keep Boot's Kafka client metrics and `spring.kafka.listener` timers on, and add counters for retries (`RetryListener`), DLT publishes, and dedupe hits with bounded tags. Note the broker-side consumer-group lag alert to add. Log topic/partition/offset/key hash, never payloads\n - Security per {{BROKER}}: `SASL_SSL` (or mTLS) with the JAAS config, passwords, and connection strings from Kubernetes secrets or Key Vault via environment placeholders, and truststores mounted from secrets\n\n4. Tests\n - Integration on Testcontainers Kafka with `@ServiceConnection` (or `@EmbeddedKafka` for a fast slice), with assertions through Awaitility and no fixed sleeps\n - Same record delivered twice → exactly one side effect\n - Transient failure → retries, then succeeds, offset committed once\n - Non-retryable exception → DLT on first failure with original topic/partition/offset headers\n - Malformed payload → DLT with the original bytes, and the partition keeps moving\n - Container stop mid-batch → restart reprocesses only uncommitted records with no duplicate side effects\n\n5. Verification\n - Exception classification table: exception → retryable? → blocking / non-blocking / DLT\n - Topic table: source, retry, and DLT names with partitions, retention, and owner\n - Poll-budget math and the concurrency × replicas ≤ partitions check for {{PARTITIONS}} and {{REPLICAS}}\n - Metrics and alerts list (lag, retry rate, DLT rate, dedupe hits), and confirmation that no credentials or payloads appear in config, logs, or tags\n\nConstraints:\n- Minimal diff. Extend the existing container factory and listeners; don't introduce a second factory or a new messaging framework.\n- Don't invent topic names, broker URLs, credentials, or partition counts. Use placeholders if unknown.\n- Don't claim exactly-once for DB or HTTP side effects. Use Kafka transactions only for Kafka-to-Kafka flows that already need them.\n- Optimize for GitHub Copilot, Claude Code, and Codex: give concrete diffs and a checklist.\n- Leave topic creation and alert rules as follow-up notes unless the repo already manages them.\n\nOutput format:\n1. Findings table: severity | location | issue | fix\n2. Patch (config + error handler/recoverer + deserializers + idempotency/inbox migration + listener changes + topic manifests)\n3. Tests added and their results\n4. Classification table, topic table, poll-budget math, and follow-ups (alerts, broker-side lag, DLT replay runbook)\n\nStart from {{APP_PATH}}. Fix non-idempotent side effects and ack-before-work before tuning retries or metrics.\n" } ] }