Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions promptbook/prompts.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.<name>` per entry in {{DOWNSTREAMS}}: `authorization-grant-type: client_credentials`, `scope: <app-id-uri>/.default`, and a provider `token-uri: https://login.microsoftonline.com/<tenant>/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 `<topic>-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"
}
]
}
Loading
Loading