From c89b95fcdbb75961b7432ff17a947f389b8d3c93 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Mon, 19 Oct 2026 05:13:19 +0000 Subject: [PATCH 1/2] Add Entra ID Spring service-to-service auth skill --- skillbook/skills.json | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/skillbook/skills.json b/skillbook/skills.json index db4e3d9..c616b0d 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -633,6 +633,28 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-micrometer-prometheus.instructions.md` with applyTo for `**/application*.{yml,yaml,properties}`, `**/*Meter*Config*.java`, `**/*Metrics*.java`, `**/pom.xml`/`**/build.gradle*`, and scrape manifests (`**/servicemonitor*.yaml`, `**/podmonitor*.yaml`, `**/values*.yaml`). Optional `.github/skills/spring-boot-micrometer-prometheus-guardrails/SKILL.md`. Claude Code: `.claude/skills/spring-boot-micrometer-prometheus-guardrails/SKILL.md` plus a CLAUDE.md fact that URI templates (not raw paths) and bounded labels keep Prometheus cardinality safe. Codex: a Micrometer/Prometheus section in root `AGENTS.md` or nested `src/main/AGENTS.md`. Pair with spring-boot-actuator-hardening for endpoint lockdown; otel-aks-observability and spring-boot-structured-logging-guardrails for traces/logs — this skill owns metrics design and scrape hygiene only.", "body": "# Skill: Spring Boot Micrometer Prometheus Guardrails\n\n## Goal\nShip durable RED/SLI metrics from Spring Boot via Micrometer's Prometheus registry: histograms that support p95/p99 and SLO burn alerts, low and stable cardinality, clear common tags, and a scrape path that works on AKS — without turning `/actuator` into a public dump of secrets or exploding Prometheus series count.\n\n## When to apply\n- New Spring Boot 2.x/3.x services adding `micrometer-registry-prometheus` (or reviewing an existing scrape)\n- Reviews of `management.metrics.*`, `management.endpoints.web.exposure`, or HTTP server timer buckets\n- AKS / Kubernetes workloads that need ServiceMonitor, PodMonitor, or annotation-based Prometheus scrape\n- Dashboards or alerts that cannot compute latency percentiles, or Prometheus cardinality alerts firing\n- Custom business meters about to take unbounded label values (user id, order id, exception message, raw URI)\n\n## Baseline rules\n1. **Prometheus registry on Actuator, not on the public API surface by accident.** Add `spring-boot-starter-actuator` and `micrometer-registry-prometheus`. Expose `prometheus` (and usually `health`) on the management endpoints. Prefer a separate `management.server.port` so scrapes and probes never share the user-facing listener. Security lockdown of Actuator belongs in **spring-boot-actuator-hardening** — reference it; do not re-open `env` / `heapdump` / `include=*`.\n2. **Expose only what the scraper needs.** Typical production include set: `health,prometheus` (add `info` only if it carries no secrets). Keep `metrics` JSON endpoint off public/management exposure unless authenticated ops tooling needs it. Never ship `include=*`.\n3. **Common tags on every series.** Set `management.metrics.tags.application` (service name) and `management.metrics.tags.environment` (or equivalent) so PromQL can filter by service and env without relying on scrape job labels alone. Keep the tag set small and stable across the fleet.\n4. **Cardinality is a product decision.** Use route / URI **templates** (`/api/orders/{id}`), never raw path params, query strings, user ids, session ids, or free-text exception messages as label values. Prefer Spring MVC / WebFlux's built-in `http.server.requests` tagging (method, uri template, status, outcome, exception class name only when bounded). Cap or deny custom tags that can grow without bound.\n5. **RED first: Rate, Errors, Duration.** Drive dashboards and alerts from `http.server.requests`: request rate, 5xx (and optionally 4xx where product-defined) error ratio, and latency percentiles from **histograms** — not from sparse summary snapshots alone. Enable percentile-histogram (or explicit SLO buckets) for `http.server.requests` so Prometheus can compute `histogram_quantile` for p95/p99 and multi-window burn rates.\n6. **Choose histogram buckets for your SLOs.** Default Micrometer/Prometheus buckets are a starting point; override with service-appropriate SLO boundaries (for example 50ms / 100ms / 250ms / 500ms / 1s / 2.5s / 5s / 10s for an HTTP API). Document the SLO the buckets support. Avoid enabling every timer as a full histogram — prefer HTTP server and a few critical outbound/client timers.\n7. **Custom business meters stay bounded.** Counters and timers for domain events use a fixed vocabulary of labels (status enum, payment method enum, region code). Never put customer id, email, free-text reason, or stack-trace snippets on labels. Prefer exemplars / traces for per-request drill-down (see **otel-aks-observability**).\n8. **Client and dependency timers, carefully.** Instrument outbound HTTP, JDBC, messaging with Micrometer Observation or existing binders, but apply the same URI-template and bounded-tag rules. Prefer one meter name per dependency with a `client`/`peer` tag rather than a new meter name per endpoint.\n9. **AKS scrape hygiene (light touch).** Prefer scraping the **management port** only: NetworkPolicy / Service that exposes management to the Prometheus namespace (or private scrape network), not to the Ingress. Use Prometheus Operator `ServiceMonitor` / `PodMonitor` with `path: /actuator/prometheus` (or your management base-path), the management port name, and sensible scrape / timeout intervals. Pod annotations (`prometheus.io/scrape`, `prometheus.io/port`, `prometheus.io/path`) are fine for simpler clusters — keep them pointed at management, not the public container port. Do not require a full Helm rewrite for a metrics PR.\n10. **Auth and network for scrape.** If the management port is reachable beyond the scrape mesh, require auth or mTLS consistent with platform standards; otherwise keep it ClusterIP-private and NetworkPolicy-restricted. Do not put bearer tokens in Git — use platform secrets / workload identity patterns already approved for the cluster.\n11. **Naming and units.** Stick to Micrometer naming (dot-separated names become Prometheus `snake_case` with `_total` / `_seconds` / `_bucket` suffixes). Prefer base units (seconds, bytes). Do not invent parallel metric names for the same signal.\n12. **Pair the three pillars, don't duplicate them.** Metrics = this skill. Traces / sampling / W3C context = **otel-aks-observability**. Request logs with `trace_id` and no PII = **spring-boot-structured-logging-guardrails**. Correlate via exemplars or shared trace ids; do not try to encode full request payloads into metric labels.\n13. **Verify with scrape + PromQL, not only `/actuator/metrics`.** Hit `/actuator/prometheus` (management port), confirm `http_server_requests_*` histogram buckets and common tags, run a sample `histogram_quantile` and error-rate query, and check Prometheus TSDB / cardinality for unexpected series growth after traffic.\n\n## Workflow\n1. Inventory: current Actuator exposure, management port, existing Micrometer registries, scrape config (ServiceMonitor / annotations), and any cardinality or missing-percentile complaints.\n2. Dependencies and config: ensure prometheus registry, expose `health`+`prometheus` only, set common tags, enable HTTP server histogram/SLO buckets.\n3. Audit meters: list custom `MeterRegistry` / `@Timed` / Observation usage; remove or rewrite unbounded labels; convert raw-URI tags to templates.\n4. Scrape path: point Prometheus at the management port/path; confirm NetworkPolicy / private Service; leave public Ingress alone.\n5. Cross-check Actuator lockdown with **spring-boot-actuator-hardening**; leave traces/logs to their skills.\n6. PR notes: meter inventory, cardinality before/after, PromQL examples for RED, scrape manifest diff, residual risks (auth on management, bucket choices).\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spring-micrometer-prometheus.instructions.md` with `applyTo` covering application config, Meter/Metrics config classes, build files, and scrape manifests.\n- Always-on line in `.github/copilot-instructions.md`: \"Micrometer metrics use URI templates and bounded labels; Prometheus scrapes management-port `/actuator/prometheus` with histograms for http.server.requests.\"\n- Optional `.github/skills/spring-boot-micrometer-prometheus-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/spring-boot-micrometer-prometheus-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Never put user ids or raw request paths on Micrometer tags; scrape only the management prometheus endpoint.\"\n- Before claiming done, show `/actuator/prometheus` sample lines for `http_server_requests` and the ServiceMonitor (or annotation) diff.\n\n### Codex\n- Micrometer / Prometheus section in root `AGENTS.md` or nested `src/main/AGENTS.md` (or linked `docs/agents/spring-micrometer-prometheus.md`).\n- State: required dependencies, allowed exposed endpoints, banned label patterns, histogram/SLO bucket policy, management-port scrape convention, and which sibling skills cover Actuator security vs OTel vs logging.\n\n## Anti-patterns\n- `management.endpoints.web.exposure.include=*` so prometheus works \"for now\"\n- Scraping the public app port / Ingress for `/actuator/prometheus`\n- Labeling timers with `uri=/orders/12345` or `userId=...`\n- Using exception **messages** (or stack traces) as tag values instead of bounded exception class names\n- Summaries only, then wondering why Grafana cannot show stable p99 or SLO burn\n- A new custom counter per customer, tenant-without-bound, or free-text \"reason\"\n- Duplicating the same RED signal under three meter names\n- Putting secrets or connection strings into `info` or metric tags\n- Ignoring Actuator hardening while opening prometheus (or the reverse: locking Actuator so hard scrapes break with no scrape auth plan)\n\n## Verification checklist\n- [ ] `micrometer-registry-prometheus` on the classpath; Prometheus scrape returns data\n- [ ] Management port (preferred) exposes `health` + `prometheus` only; no `include=*`\n- [ ] Common tags include application and environment (or platform equivalent)\n- [ ] `http.server.requests` uses URI templates; no raw ids in uri/path labels\n- [ ] Percentile histogram or explicit SLO buckets enabled for HTTP server (and critical clients)\n- [ ] Custom meters use bounded enums/codes only — no user/order ids or free text\n- [ ] AKS scrape targets management port via ServiceMonitor/PodMonitor or equivalent annotations\n- [ ] Network path for scrape is private; Actuator lockdown still matches **spring-boot-actuator-hardening**\n- [ ] Sample PromQL for rate, 5xx ratio, and `histogram_quantile` documented in the PR\n- [ ] Traces/logs left to OTel / structured-logging skills — not stuffed into labels\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-boot-micrometer-prometheus-guardrails\ndescription: Use when wiring or reviewing Micrometer + Prometheus for a Spring Boot service — actuator prometheus registry, RED/SLI histograms, cardinality control, common tags, and AKS scrape hygiene.\n---\n\nFollow Spring Boot Micrometer Prometheus Guardrails: prometheus registry on a separate management port exposing health+prometheus only, common application/environment tags, URI templates not raw paths or user ids, histograms/SLO buckets for http.server.requests, bounded labels on custom meters, private AKS scrape (ServiceMonitor or annotations on the management port), and pair with spring-boot-actuator-hardening for lockdown plus otel-aks-observability / structured-logging for traces and logs.\n```\n" + }, + { + "id": "entra-id-spring-service-auth-guardrails", + "title": "Entra ID Spring Service-to-Service Auth Guardrails", + "whenToUse": "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 the same rules for external URLs and in-cluster svc.cluster.local calls.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "spring-security", + "entra-id", + "oauth2", + "jwt", + "service-to-service", + "aks", + "java" + ], + "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" } ] } From 71a0f07f67f649e7cbe66c02035cf1bc8d862550 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Mon, 19 Oct 2026 05:13:19 +0000 Subject: [PATCH 2/2] Add wire Entra service-to-service auth prompt --- promptbook/prompts.json | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index b1f54f5..59637a3 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -635,6 +635,28 @@ ], "formatNotes": "All three. Point the tool at `application.yml`/`application.properties`, Meter/Metrics config, the build file, and any ServiceMonitor/PodMonitor or Prometheus annotation manifests; keep Actuator security changes aligned with spring-boot-actuator-hardening. Copilot: spring-micrometer-prometheus path instructions plus those files in agent mode. Claude Code: the spring-boot-micrometer-prometheus-guardrails skill plus the config and scrape manifests. Codex: AGENTS.md Micrometer section, then the diff.", "body": "Task: Wire or harden Micrometer + Prometheus metrics for the Spring Boot service I specify. Deliver RED-ready histograms, cardinality-safe tags, and a private management-port scrape path — then give me a minimal diff I can open as a PR.\n\nContext placeholders (fill from the repo or ask only if missing):\n- App module / root: {{APP_PATH}}\n- Spring Boot version: {{BOOT_VERSION}} (2.x | 3.x | unknown)\n- Build tool: {{BUILD_TOOL}} (maven | gradle)\n- Current Actuator exposure: {{ACTUATOR_EXPOSURE}} (e.g. health,info | include=* | unknown)\n- Management port today: {{MANAGEMENT_PORT}} (number | same-as-server | unknown)\n- Scrape style: {{SCRAPE_STYLE}} (servicemonitor | podmonitor | pod-annotations | none | unknown)\n- Cluster / env: {{ENVIRONMENT}} (e.g. aks-dev, aks-prod)\n- Service name for tags: {{SERVICE_NAME}}\n- Latency SLO targets (optional): {{SLO_BUCKETS_MS}} (e.g. 100,250,500,1000,2500,5000)\n- Pain points: {{PAIN}} (no-percentiles | cardinality | scrape-404 | public-actuator | missing-red | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}} build file and `application*.yml|properties` for Actuator, Micrometer, and management server settings\n - List existing meters (`MeterRegistry` beans, `@Timed`, Observations) and any custom tags\n - Locate scrape manifests or annotations under deploy/Helm paths; note whether scrape hits the public or management port\n - Note overlap with Actuator security config (do not weaken lockdown)\n\n2. Findings (rank by risk: public sensitive Actuator > unbounded cardinality > scrape on public Ingress > missing histograms > hygiene)\n - `include=*` or sensitive endpoints exposed alongside prometheus\n - Raw URI / user id / exception message labels\n - Summaries without histogram buckets where p95/p99 or SLO burn is required\n - Scrape targeting the public Service/Ingress\n - Missing common tags (`application`, `environment`)\n - Custom meters with unbounded label values\n\n3. Fix\n - Dependencies: ensure `spring-boot-starter-actuator` and `micrometer-registry-prometheus` for {{BUILD_TOOL}}\n - Config: separate `management.server.port` when the app has a public HTTP surface; `management.endpoints.web.exposure.include=health,prometheus` (add `info` only if safe); set `management.metrics.tags.application={{SERVICE_NAME}}` and `management.metrics.tags.environment={{ENVIRONMENT}}`\n - HTTP server metrics: enable percentile-histogram (or distribution SLO deadlines / buckets from {{SLO_BUCKETS_MS}}) for `http.server.requests` so Prometheus can compute percentiles\n - Cardinality: ensure URI tags use route templates; strip or deny tags that carry ids or free text; rewrite custom meters to bounded enums\n - Scrape: for {{SCRAPE_STYLE}}, point path at `/actuator/prometheus` (honor any `management.endpoints.web.base-path`) on the **management** port; Prefer ServiceMonitor/PodMonitor selectors over scraping Ingress. Keep changes surgical — no full Helm rewrite unless required\n - Security: keep Actuator lockdown consistent with spring-boot-actuator-hardening; if scrape needs auth, document the platform mechanism without inventing secrets in Git\n - Do not invent OTel collectors or logging pipelines here — link to otel-aks-observability / structured-logging if gaps exist\n\n4. Verification\n - Show sample lines from `/actuator/prometheus` for `http_server_requests_*` including bucket series and common tags\n - Provide PromQL sketches: request rate, 5xx error ratio, `histogram_quantile(0.95, ...)` (and 0.99 if useful)\n - Confirm scrape config targets management port; note NetworkPolicy / private Service expectations for {{ENVIRONMENT}}\n - List residual risks (auth on management, bucket fit to SLO, remaining high-cardinality candidates)\n\nConstraints:\n- Minimal diff; do not refactor unrelated config or open extra Actuator endpoints.\n- Do not invent cluster URLs, credential values, or Helm chart names — use placeholders if unknown.\n- Do not put PII or secrets into metric tags or `info`.\n- Optimize for GitHub Copilot, Claude Code, and Codex — concrete diffs and a checklist.\n- Metrics lane only; defer traces and log shipping to their skills.\n\nOutput format:\n1. Findings table: severity | location | issue | fix\n2. Patch (build + application config + meter/tag fixes + scrape manifest/annotations)\n3. Verification: sample prometheus text, PromQL, scrape target summary\n4. Residual risks and follow-ups (Actuator auth, OTel, logging)\n\nStart from {{APP_PATH}}. Fix public Actuator exposure and unbounded labels before polishing dashboards.\n" + }, + { + "id": "wire-entra-service-to-service-auth", + "title": "Wire Entra ID Service-to-Service Auth in Spring Boot", + "whenToUse": "Add or harden Entra ID service-to-service auth on a Spring Boot receiver and/or caller (app-role authorization, group-to-role map with overage handling, cached client-credentials tokens, external and svc.cluster.local URLs from config) and produce a minimal diff with tests and a role matrix.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "spring-security", + "entra-id", + "oauth2", + "jwt", + "service-to-service", + "aks", + "java" + ], + "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" } ] }