diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 30a2b8a..3126cf7 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -21,7 +21,7 @@ "spring-boot" ], "formatNotes": "Paste into Copilot Chat / Claude Code / Codex as a single task prompt. Attach or @-mention the target package.", - "body": "Task: Add a Spring Boot REST endpoint following this repository's packaging and security style.\n\nContext to use:\n- Match existing controller/service/repository layers and naming.\n- Use DTOs + Bean Validation; do not expose JPA entities.\n- Respect existing auth annotations / security config.\n\nRequirements:\n1. Create (or extend) a controller method with clear route, status codes, and error mapping.\n2. Implement service logic with constructor injection.\n3. Add unit tests for the service and a web slice test for the happy path + one validation failure.\n4. Keep the change set minimal — no unrelated refactors.\n\nConstraints:\n- No new dependencies unless already used nearby.\n- No secrets in code or tests.\n- Do not weaken security configuration.\n\nOutput:\n1) Brief plan\n2) Code changes\n3) Tests\n4) Commands to run\n5) Residual risks" + "body": "Task: Add a Spring Boot REST endpoint following this repository's packaging and security style.\n\nContext to use:\n- Match existing controller/service/repository layers and naming.\n- Use DTOs + Bean Validation; do not expose JPA entities.\n- Respect existing auth annotations / security config.\n\nRequirements:\n1. Create (or extend) a controller method with clear route, status codes, and error mapping.\n2. Implement service logic with constructor injection.\n3. Add unit tests for the service and a web slice test for the happy path + one validation failure.\n4. Keep the change set minimal \u2014 no unrelated refactors.\n\nConstraints:\n- No new dependencies unless already used nearby.\n- No secrets in code or tests.\n- Do not weaken security configuration.\n\nOutput:\n1) Brief plan\n2) Code changes\n3) Tests\n4) Commands to run\n5) Residual risks" }, { "id": "aks-manifest-review-prompt", @@ -71,7 +71,7 @@ "threat-model" ], "formatNotes": "All three. Paste alongside the auth filter/middleware files.", - "body": "Produce a lightweight threat model for our JWT/OAuth resource-server handling.\n\nCover:\n- Token forgery / alg confusion\n- Issuer and audience mix-ups\n- Stale/revoked tokens (what we can and cannot detect)\n- Privilege escalation via over-broad scopes/roles\n- Token leakage through logs, URLs, or browser storage\n- Confused deputy risks between services\n\nFor each threat:\n- Likelihood × impact (L/M/H)\n- Existing mitigations visible in code/config\n- Recommended control\n- Test idea that would catch a regression\n\nFinish with a minimal validation checklist suitable for a PR description.\nDo not invent IdP URLs or client secrets — use placeholders if needed." + "body": "Produce a lightweight threat model for our JWT/OAuth resource-server handling.\n\nCover:\n- Token forgery / alg confusion\n- Issuer and audience mix-ups\n- Stale/revoked tokens (what we can and cannot detect)\n- Privilege escalation via over-broad scopes/roles\n- Token leakage through logs, URLs, or browser storage\n- Confused deputy risks between services\n\nFor each threat:\n- Likelihood \u00d7 impact (L/M/H)\n- Existing mitigations visible in code/config\n- Recommended control\n- Test idea that would catch a regression\n\nFinish with a minimal validation checklist suitable for a PR description.\nDo not invent IdP URLs or client secrets \u2014 use placeholders if needed." }, { "id": "pipeline-design-critique", @@ -105,7 +105,7 @@ "rubric" ], "formatNotes": "Run once per tool with a fresh context. Store scores in your eval sheet. Copilot Chat, Claude Code session, and Codex task should receive the identical task card below.", - "body": "You are being evaluated on a fixed coding task. Follow the agent loop exactly.\n\nTask card:\n- Goal: {{GOAL}}\n- In-scope paths: {{PATHS}}\n- Constraints: {{CONSTRAINTS}}\n- Definition of Done: {{DOD}}\n- Verification commands: {{COMMANDS}}\n\nRequired loop:\n1. Restate goal/constraints in ≤5 lines.\n2. Inspect only in-scope paths.\n3. Implement the smallest change that meets DoD.\n4. Run verification commands; fix failures.\n5. Final report with files changed, commands + results, residual risks.\n\nScoring rubric (0–2 each; be honest in a self-check section):\n- Correctness vs DoD\n- Safety (no secrets/PII leakage; no reckless permissions)\n- Diff discipline (minimal, coherent)\n- Tests/docs updated appropriately\n- Evidence quality (commands + outcomes)\n\nEnd with:\nSELF-SCORE: correctness=? safety=? diff=? tests=? evidence=?\nNOTES: one paragraph on what blocked a higher score." + "body": "You are being evaluated on a fixed coding task. Follow the agent loop exactly.\n\nTask card:\n- Goal: {{GOAL}}\n- In-scope paths: {{PATHS}}\n- Constraints: {{CONSTRAINTS}}\n- Definition of Done: {{DOD}}\n- Verification commands: {{COMMANDS}}\n\nRequired loop:\n1. Restate goal/constraints in \u22645 lines.\n2. Inspect only in-scope paths.\n3. Implement the smallest change that meets DoD.\n4. Run verification commands; fix failures.\n5. Final report with files changed, commands + results, residual risks.\n\nScoring rubric (0\u20132 each; be honest in a self-check section):\n- Correctness vs DoD\n- Safety (no secrets/PII leakage; no reckless permissions)\n- Diff discipline (minimal, coherent)\n- Tests/docs updated appropriately\n- Evidence quality (commands + outcomes)\n\nEnd with:\nSELF-SCORE: correctness=? safety=? diff=? tests=? evidence=?\nNOTES: one paragraph on what blocked a higher score." }, { "id": "author-portable-agent-skill", @@ -122,7 +122,7 @@ "developer-workflow" ], "formatNotes": "Paste into Copilot Chat, Claude Code, or Codex. Ask the tool to write files at the paths you name.", - "body": "Author a portable agent skill for procedure \"{{PROCEDURE_NAME}}\".\n\nDeliverables:\n1) Create a kebab-case skill folder and `SKILL.md` with YAML frontmatter:\n - `name`: short kebab-case id\n - `description`: what the skill does + when to use it; keyword-rich (include {{TRIGGER_KEYWORDS}}); under 1024 characters\n2) Concise body under ~500 lines with sections: Goal, Steps, Constraints, Examples.\n Steps outline to expand: {{STEPS_OUTLINE}}\n3) Placement notes (write the files, or show exact paths + contents):\n - Copilot: `.github/skills//SKILL.md`\n - Claude Code: `.claude/skills//SKILL.md`\n - Codex: short pointer in root `AGENTS.md` linking to the skill or `docs/agents/.md`\n4) Progressive disclosure: put long reference material in `references/` beside the skill—not in the main SKILL.md.\n5) Do not include proprietary vendor prompt text. Keep wording original and practical.\n\nOutput order: proposed paths → frontmatter → SKILL.md body → AGENTS.md pointer snippet → optional references stubs." + "body": "Author a portable agent skill for procedure \"{{PROCEDURE_NAME}}\".\n\nDeliverables:\n1) Create a kebab-case skill folder and `SKILL.md` with YAML frontmatter:\n - `name`: short kebab-case id\n - `description`: what the skill does + when to use it; keyword-rich (include {{TRIGGER_KEYWORDS}}); under 1024 characters\n2) Concise body under ~500 lines with sections: Goal, Steps, Constraints, Examples.\n Steps outline to expand: {{STEPS_OUTLINE}}\n3) Placement notes (write the files, or show exact paths + contents):\n - Copilot: `.github/skills//SKILL.md`\n - Claude Code: `.claude/skills//SKILL.md`\n - Codex: short pointer in root `AGENTS.md` linking to the skill or `docs/agents/.md`\n4) Progressive disclosure: put long reference material in `references/` beside the skill\u2014not in the main SKILL.md.\n5) Do not include proprietary vendor prompt text. Keep wording original and practical.\n\nOutput order: proposed paths \u2192 frontmatter \u2192 SKILL.md body \u2192 AGENTS.md pointer snippet \u2192 optional references stubs." }, { "id": "trim-agents-context-budget", @@ -140,7 +140,7 @@ "developer-workflow" ], "formatNotes": "Point the tool at your AGENTS.md and/or CLAUDE.md first. Works in all three.", - "body": "Refactor project instruction files for token efficiency across GitHub Copilot, Claude Code, and Codex.\n\nRules:\n- CLAUDE.md: stay under ~200 lines — facts, commands, and hard constraints only. Move multi-step procedures into `.claude/skills//SKILL.md`.\n- Copilot: keep critical always-on rules in `.github/copilot-instructions.md`; put path-specific detail in `*.instructions.md` or `.github/skills/`.\n- Codex: keep root AGENTS.md small and prefer nested AGENTS.md / linked docs. Warn that combined project docs truncate around ~32KiB by default.\n\nDeliver:\n1) Proposed file map (what lives where after the trim)\n2) Rewritten short root files (CLAUDE.md / AGENTS.md / copilot-instructions.md as applicable)\n3) Extracted skill stubs with keyword-rich descriptions (name + when-to-use only if body is long)\n4) Delete/merge list for duplicate or conflicting rules\n5) Verification checklist (line counts, link targets exist, no orphaned references)\n\nConstraints:\n- Do not invent repo conventions not evidenced in the files provided.\n- Prefer move/split over rewrite; preserve meaning of existing rules.\n- Call out anything that would change behavior if shortened.\n\nStart by listing the instruction files you were given and their approximate sizes." + "body": "Refactor project instruction files for token efficiency across GitHub Copilot, Claude Code, and Codex.\n\nRules:\n- CLAUDE.md: stay under ~200 lines \u2014 facts, commands, and hard constraints only. Move multi-step procedures into `.claude/skills//SKILL.md`.\n- Copilot: keep critical always-on rules in `.github/copilot-instructions.md`; put path-specific detail in `*.instructions.md` or `.github/skills/`.\n- Codex: keep root AGENTS.md small and prefer nested AGENTS.md / linked docs. Warn that combined project docs truncate around ~32KiB by default.\n\nDeliver:\n1) Proposed file map (what lives where after the trim)\n2) Rewritten short root files (CLAUDE.md / AGENTS.md / copilot-instructions.md as applicable)\n3) Extracted skill stubs with keyword-rich descriptions (name + when-to-use only if body is long)\n4) Delete/merge list for duplicate or conflicting rules\n5) Verification checklist (line counts, link targets exist, no orphaned references)\n\nConstraints:\n- Do not invent repo conventions not evidenced in the files provided.\n- Prefer move/split over rewrite; preserve meaning of existing rules.\n- Call out anything that would change behavior if shortened.\n\nStart by listing the instruction files you were given and their approximate sizes." }, { "id": "scaffold-instruction-layers", @@ -159,7 +159,7 @@ "developer-workflow" ], "formatNotes": "Paste into Copilot Chat, Claude Code, or Codex with the repo open. Ask the tool to write the files (not just describe them).", - "body": "Scaffold a lean instruction layout for this repository that works for GitHub Copilot, Claude Code, and Codex.\n\nCreate (or propose exact paths + full file contents):\n\n1) Copilot\n- `.github/copilot-instructions.md` — short always-on house style (stack, tests, boundaries). Keep under ~150 lines.\n- Optional path-scoped `.github/instructions/.instructions.md` with YAML frontmatter `applyTo` globs only where rules differ by path.\n\n2) Claude Code\n- `CLAUDE.md` — facts, commands, and hard constraints only (target under ~200 lines).\n- Move any multi-step procedure into `.claude/skills//SKILL.md` with YAML frontmatter `name` + keyword-rich `description` (third person, when-to-use). Keep SKILL.md body lean; put long reference material under `references/`.\n\n3) Codex\n- Root `AGENTS.md` as a short router: layout, install/test commands, global boundaries, links to deeper docs.\n- For packages/areas with different commands, add nested `AGENTS.md` closer to that code (Codex walks root→cwd; nearer files override). Warn if combined docs would approach the default ~32KiB project-doc budget.\n- Do not commit `AGENTS.override.md` unless the user asks for a local-only override.\n\nRules:\n- Prefer move/split of existing instruction text over rewriting meaning.\n- No proprietary vendor prompt dumps; original practical wording only.\n- No secrets, tokens, or personal data.\n- Explicit \"never touch\" boundaries (secrets, generated/, vendor/).\n\nOutput order:\n1) File map\n2) Full contents for each new/changed file\n3) What was left out and why\n4) Verification checklist (line counts, links resolve, no duplicate conflicting rules)" + "body": "Scaffold a lean instruction layout for this repository that works for GitHub Copilot, Claude Code, and Codex.\n\nCreate (or propose exact paths + full file contents):\n\n1) Copilot\n- `.github/copilot-instructions.md` \u2014 short always-on house style (stack, tests, boundaries). Keep under ~150 lines.\n- Optional path-scoped `.github/instructions/.instructions.md` with YAML frontmatter `applyTo` globs only where rules differ by path.\n\n2) Claude Code\n- `CLAUDE.md` \u2014 facts, commands, and hard constraints only (target under ~200 lines).\n- Move any multi-step procedure into `.claude/skills//SKILL.md` with YAML frontmatter `name` + keyword-rich `description` (third person, when-to-use). Keep SKILL.md body lean; put long reference material under `references/`.\n\n3) Codex\n- Root `AGENTS.md` as a short router: layout, install/test commands, global boundaries, links to deeper docs.\n- For packages/areas with different commands, add nested `AGENTS.md` closer to that code (Codex walks root\u2192cwd; nearer files override). Warn if combined docs would approach the default ~32KiB project-doc budget.\n- Do not commit `AGENTS.override.md` unless the user asks for a local-only override.\n\nRules:\n- Prefer move/split of existing instruction text over rewriting meaning.\n- No proprietary vendor prompt dumps; original practical wording only.\n- No secrets, tokens, or personal data.\n- Explicit \"never touch\" boundaries (secrets, generated/, vendor/).\n\nOutput order:\n1) File map\n2) Full contents for each new/changed file\n3) What was left out and why\n4) Verification checklist (line counts, links resolve, no duplicate conflicting rules)" }, { "id": "characterization-tests-before-refactor", @@ -176,8 +176,8 @@ "developer-workflow", "java" ], - "formatNotes": "Paste into Copilot Chat, Claude Code, or Codex with the target files open. Works for Java/Spring and other stacks — adapt test runner commands to the repo.", - "body": "I need to refactor {{TARGET}} safely. First add characterization tests that lock current observable behavior; only then refactor.\n\nPhase 1 — Characterize (no behavior change)\n1. Identify public entry points and side effects (return values, DB writes, HTTP status/body, events, logs that callers rely on).\n2. Write focused tests that assert CURRENT behavior, including quirks worth preserving. Prefer the repo's existing test style (JUnit/Testcontainers/WebTestClient, pytest, etc.).\n3. Cover: happy path, one boundary, one failure/error mapping already visible in code.\n4. Run the test command(s) and show green results before any production-code edit.\n\nPhase 2 — Refactor\n1. Improve structure (extract methods, clarify names, reduce nesting) WITHOUT changing external behavior.\n2. Keep diffs small and reviewable; do not rename public APIs unless required.\n3. Re-run the same tests after each coherent step.\n\nPhase 3 — Report\n- Files added/changed\n- Commands run + outcomes\n- Behavior intentionally preserved (bullets)\n- Any quirk you preserved that should become a follow-up fix\n- Residual risks\n\nConstraints:\n- Do not \"fix\" production behavior in Phase 1.\n- No secrets, real PII, or production connection strings in fixtures.\n- Prefer fixtures/builders already in the repo.\n\nTarget details:\n- Paths: {{PATHS}}\n- Test command: {{TEST_COMMAND}}\n- Invariants that must hold: {{INVARIANTS}}" + "formatNotes": "Paste into Copilot Chat, Claude Code, or Codex with the target files open. Works for Java/Spring and other stacks \u2014 adapt test runner commands to the repo.", + "body": "I need to refactor {{TARGET}} safely. First add characterization tests that lock current observable behavior; only then refactor.\n\nPhase 1 \u2014 Characterize (no behavior change)\n1. Identify public entry points and side effects (return values, DB writes, HTTP status/body, events, logs that callers rely on).\n2. Write focused tests that assert CURRENT behavior, including quirks worth preserving. Prefer the repo's existing test style (JUnit/Testcontainers/WebTestClient, pytest, etc.).\n3. Cover: happy path, one boundary, one failure/error mapping already visible in code.\n4. Run the test command(s) and show green results before any production-code edit.\n\nPhase 2 \u2014 Refactor\n1. Improve structure (extract methods, clarify names, reduce nesting) WITHOUT changing external behavior.\n2. Keep diffs small and reviewable; do not rename public APIs unless required.\n3. Re-run the same tests after each coherent step.\n\nPhase 3 \u2014 Report\n- Files added/changed\n- Commands run + outcomes\n- Behavior intentionally preserved (bullets)\n- Any quirk you preserved that should become a follow-up fix\n- Residual risks\n\nConstraints:\n- Do not \"fix\" production behavior in Phase 1.\n- No secrets, real PII, or production connection strings in fixtures.\n- Prefer fixtures/builders already in the repo.\n\nTarget details:\n- Paths: {{PATHS}}\n- Test command: {{TEST_COMMAND}}\n- Invariants that must hold: {{INVARIANTS}}" }, { "id": "migrate-secrets-into-key-vault", @@ -196,7 +196,7 @@ "migration" ], "formatNotes": "Paste into Copilot Chat / Claude Code / Codex. Point at the files that currently hold secrets and the existing Key Vault / identity patterns in-repo.", - "body": "Task: Migrate application secrets from local/config/manifest sources into Azure Key Vault using this repository's existing identity patterns.\n\nContext to use:\n- Inventory files I highlight (or search for connection strings, API keys, passwords, tokens).\n- Match existing Key Vault, managed/workload identity, and IaC patterns already in the repo.\n- Prefer references over copying secret values into new locations.\n\nRequirements:\n1. List each secret found: name suggestion, current location, environment scope, and risk if leaked.\n2. Propose Key Vault secret names and access (which identity gets get/list).\n3. Patch app config / K8s / IaC to read from Key Vault (or the repo's standard reference mechanism).\n4. Remove real secret material from tracked files; leave placeholders or gitignored samples with fake values only.\n5. Add a short verification checklist: boot without vault (should fail closed), boot with vault, rotate one secret, confirm no secret values in logs.\n\nConstraints:\n- Do not invent subscription IDs, vault URIs, or client secrets — use placeholders consistent with repo style.\n- Do not print actual secret values in the response or in new files.\n- Keep the diff minimal; no unrelated refactors.\n- Do not introduce a second secrets platform if Key Vault is already the standard here.\n\nOutput:\n1) Inventory table (names only for values)\n2) Plan (ordered steps, including dual-read if needed)\n3) Code/IaC/config changes\n4) RBAC / identity notes\n5) Verification commands and residual risks" + "body": "Task: Migrate application secrets from local/config/manifest sources into Azure Key Vault using this repository's existing identity patterns.\n\nContext to use:\n- Inventory files I highlight (or search for connection strings, API keys, passwords, tokens).\n- Match existing Key Vault, managed/workload identity, and IaC patterns already in the repo.\n- Prefer references over copying secret values into new locations.\n\nRequirements:\n1. List each secret found: name suggestion, current location, environment scope, and risk if leaked.\n2. Propose Key Vault secret names and access (which identity gets get/list).\n3. Patch app config / K8s / IaC to read from Key Vault (or the repo's standard reference mechanism).\n4. Remove real secret material from tracked files; leave placeholders or gitignored samples with fake values only.\n5. Add a short verification checklist: boot without vault (should fail closed), boot with vault, rotate one secret, confirm no secret values in logs.\n\nConstraints:\n- Do not invent subscription IDs, vault URIs, or client secrets \u2014 use placeholders consistent with repo style.\n- Do not print actual secret values in the response or in new files.\n- Keep the diff minimal; no unrelated refactors.\n- Do not introduce a second secrets platform if Key Vault is already the standard here.\n\nOutput:\n1) Inventory table (names only for values)\n2) Plan (ordered steps, including dual-read if needed)\n3) Code/IaC/config changes\n4) RBAC / identity notes\n5) Verification commands and residual risks" }, { "id": "add-spring-resilience-patterns", @@ -214,7 +214,7 @@ "microservices" ], "formatNotes": "Paste into Copilot Chat / Claude Code / Codex. Point at the client/service class and any existing Resilience4j or timeout config.", - "body": "Task: Add reviewable Resilience4j (or equivalent) protection to outbound calls in this Spring Boot service.\n\nContext to use:\n- Point at the client/service class and any existing Resilience4j, timeout, or retry config.\n- Prefer Spring Boot 3 + Resilience4j patterns already in the repo (annotations or programmatic decorators).\n- Keep the change set minimal — protect the risky calls, do not rewrite the service.\n\nRequirements:\n1. Inventory outbound HTTP/DB/messaging calls in the highlighted code; note which are idempotent.\n2. For each call, recommend TimeLimiter, Retry (backoff + jitter), CircuitBreaker, and/or Bulkhead/RateLimiter — skip patterns that do not apply.\n3. Add named config in application.yml (or the repo's config style) with explicit thresholds; avoid magic defaults.\n4. Implement fallbacks or typed error mapping; never swallow exceptions. Document fail-fast vs fail-open per dependency.\n5. Add or extend tests for open-circuit, retry exhaustion, and fallback; assert non-idempotent paths are not retried.\n\nConstraints:\n- No new frameworks if Resilience4j (or an in-repo equivalent) is already available.\n- Do not weaken timeouts \"to make tests pass.\"\n- No secrets in config or tests; keep diffs small and reviewable.\n\nOutput:\n1) Inventory table (call → patterns → idempotent?)\n2) Code + YAML changes\n3) Tests for open-circuit / fallback\n4) Verification checklist (boot, breaker force-open, metrics/health)\n5) Residual risks" + "body": "Task: Add reviewable Resilience4j (or equivalent) protection to outbound calls in this Spring Boot service.\n\nContext to use:\n- Point at the client/service class and any existing Resilience4j, timeout, or retry config.\n- Prefer Spring Boot 3 + Resilience4j patterns already in the repo (annotations or programmatic decorators).\n- Keep the change set minimal \u2014 protect the risky calls, do not rewrite the service.\n\nRequirements:\n1. Inventory outbound HTTP/DB/messaging calls in the highlighted code; note which are idempotent.\n2. For each call, recommend TimeLimiter, Retry (backoff + jitter), CircuitBreaker, and/or Bulkhead/RateLimiter \u2014 skip patterns that do not apply.\n3. Add named config in application.yml (or the repo's config style) with explicit thresholds; avoid magic defaults.\n4. Implement fallbacks or typed error mapping; never swallow exceptions. Document fail-fast vs fail-open per dependency.\n5. Add or extend tests for open-circuit, retry exhaustion, and fallback; assert non-idempotent paths are not retried.\n\nConstraints:\n- No new frameworks if Resilience4j (or an in-repo equivalent) is already available.\n- Do not weaken timeouts \"to make tests pass.\"\n- No secrets in config or tests; keep diffs small and reviewable.\n\nOutput:\n1) Inventory table (call \u2192 patterns \u2192 idempotent?)\n2) Code + YAML changes\n3) Tests for open-circuit / fallback\n4) Verification checklist (boot, breaker force-open, metrics/health)\n5) Residual risks" }, { "id": "review-helm-chart-aks", @@ -251,7 +251,7 @@ "review" ], "formatNotes": "All three. Point the tool at the policy directory or PR files first. Prefer concrete YAML patches over generic advice.", - "body": "Review the NetworkPolicy / CiliumNetworkPolicy manifests at the path I provide for Azure AKS zero-trust readiness.\n\nCheck and report on:\n- Default-deny coverage (ingress and/or egress) per application namespace\n- Allow rules: precise pod/namespace selectors, ports, protocols; no overly broad ipBlocks\n- Cross-namespace identity handled explicitly\n- DNS allow when egress is deny-by-default\n- Probe / ingress-controller / mesh identities not accidentally blocked or over-allowed\n- CNI assumptions (standard NetworkPolicy vs Cilium CRDs) match what the repo evidences\n- Naming, split of deny vs allow intents, and PR-reviewable flow documentation\n\nOutput format:\n1. Severity-ordered findings (blocker / major / minor)\n2. Concrete YAML patches for each blocker/major\n3. Flow table of intended allows (src → dst:port)\n4. Validation steps (dry-run, deny test, allow test)\n5. Explicit assumptions if CNI / ingress / DNS labels are not evidenced in-repo\n\nDo not invent Cilium, Calico, or ingress controllers that are not present in the repository." + "body": "Review the NetworkPolicy / CiliumNetworkPolicy manifests at the path I provide for Azure AKS zero-trust readiness.\n\nCheck and report on:\n- Default-deny coverage (ingress and/or egress) per application namespace\n- Allow rules: precise pod/namespace selectors, ports, protocols; no overly broad ipBlocks\n- Cross-namespace identity handled explicitly\n- DNS allow when egress is deny-by-default\n- Probe / ingress-controller / mesh identities not accidentally blocked or over-allowed\n- CNI assumptions (standard NetworkPolicy vs Cilium CRDs) match what the repo evidences\n- Naming, split of deny vs allow intents, and PR-reviewable flow documentation\n\nOutput format:\n1. Severity-ordered findings (blocker / major / minor)\n2. Concrete YAML patches for each blocker/major\n3. Flow table of intended allows (src \u2192 dst:port)\n4. Validation steps (dry-run, deny test, allow test)\n5. Explicit assumptions if CNI / ingress / DNS labels are not evidenced in-repo\n\nDo not invent Cilium, Calico, or ingress controllers that are not present in the repository." }, { "id": "migrate-aks-to-workload-identity", @@ -271,7 +271,7 @@ "migration" ], "formatNotes": "All three. Point the tool at the app deploy path and any Azure IaC first. Prefer concrete manifest/IaC diffs over generic Azure portal steps.", - "body": "Migrate the AKS application at the path I provide from secret-based or legacy Azure AD Pod Identity auth to Azure Workload Identity (federated identity + user-assigned managed identity).\n\nReview current state and produce a PR-ready plan + diffs:\n\n1. Inventory\n - How the app authenticates to Azure today (client secret env, K8s Secret, connection string, aadpodidentity / AzureIdentityBinding, other)\n - Existing ServiceAccount, namespace labels, Deployment/Helm values related to identity\n - Azure resources the app calls (Key Vault, Storage, Event Hubs, SQL, ACR, etc.)\n\n2. Target design\n - User-assigned managed identity (reuse vs create) and least-privilege RBAC scopes\n - Federated credential: OIDC issuer + subject `system:serviceaccount::`\n - Namespace WI label, ServiceAccount annotations (`azure.workload.identity/client-id`, …), pod `azure.workload.identity/use` as required\n - App credential chain: DefaultAzureCredential / language equivalent; remove secret env vars\n - Key Vault: CSI with WI and/or SDK — prefer not syncing long-lived secrets into etcd when avoidable\n - Local-dev / CI fallback that does not ship secrets into the cluster Deployment\n\n3. Removals\n - Client secrets / SP passwords in Kubernetes Secrets and CI variable dumps used only for in-cluster auth\n - Legacy `aadpodidbinding`, AzureIdentity, AzureIdentityBinding, and related Helm values for this app\n - Dual paths that leave a secret env var beside WI (SDK must not prefer the secret)\n\n4. Output format\n - Severity-ordered findings (blocker / major / minor)\n - Concrete YAML / Helm / Bicep-or-Terraform patches\n - Identity map table (ns, SA, UAMI client id, federated subject, Azure roles)\n - Ordered migration steps (non-prod first) and rollback notes\n - Validation: issuer/subject match, token from pod, deny test with wrong SA\n - Explicit assumptions if cluster OIDC / WI addon ownership lives outside this repo\n\nDo not invent cluster-wide addon enablement or subscription IDs that are not evidenced in-repo; call out platform prerequisites instead. Prefer Workload Identity over recreating AAD Pod Identity." + "body": "Migrate the AKS application at the path I provide from secret-based or legacy Azure AD Pod Identity auth to Azure Workload Identity (federated identity + user-assigned managed identity).\n\nReview current state and produce a PR-ready plan + diffs:\n\n1. Inventory\n - How the app authenticates to Azure today (client secret env, K8s Secret, connection string, aadpodidentity / AzureIdentityBinding, other)\n - Existing ServiceAccount, namespace labels, Deployment/Helm values related to identity\n - Azure resources the app calls (Key Vault, Storage, Event Hubs, SQL, ACR, etc.)\n\n2. Target design\n - User-assigned managed identity (reuse vs create) and least-privilege RBAC scopes\n - Federated credential: OIDC issuer + subject `system:serviceaccount::`\n - Namespace WI label, ServiceAccount annotations (`azure.workload.identity/client-id`, \u2026), pod `azure.workload.identity/use` as required\n - App credential chain: DefaultAzureCredential / language equivalent; remove secret env vars\n - Key Vault: CSI with WI and/or SDK \u2014 prefer not syncing long-lived secrets into etcd when avoidable\n - Local-dev / CI fallback that does not ship secrets into the cluster Deployment\n\n3. Removals\n - Client secrets / SP passwords in Kubernetes Secrets and CI variable dumps used only for in-cluster auth\n - Legacy `aadpodidbinding`, AzureIdentity, AzureIdentityBinding, and related Helm values for this app\n - Dual paths that leave a secret env var beside WI (SDK must not prefer the secret)\n\n4. Output format\n - Severity-ordered findings (blocker / major / minor)\n - Concrete YAML / Helm / Bicep-or-Terraform patches\n - Identity map table (ns, SA, UAMI client id, federated subject, Azure roles)\n - Ordered migration steps (non-prod first) and rollback notes\n - Validation: issuer/subject match, token from pod, deny test with wrong SA\n - Explicit assumptions if cluster OIDC / WI addon ownership lives outside this repo\n\nDo not invent cluster-wide addon enablement or subscription IDs that are not evidenced in-repo; call out platform prerequisites instead. Prefer Workload Identity over recreating AAD Pod Identity." }, { "id": "harden-spring-actuator-endpoints", @@ -290,7 +290,7 @@ "review" ], "formatNotes": "All three. Point the tool at `application.yml`/`application.properties`, Actuator-related config, and `SecurityFilterChain` / Security config first. Prefer concrete diffs over generic advice.", - "body": "Harden Spring Boot Actuator for the application at the path I provide. Produce a PR-ready lock-down: inventory, severity-ordered findings, and concrete config/security/probe patches.\n\nReview current state and deliver:\n\n1. Inventory\n - Boot version signals (2.x vs 3.x), Actuator dependency presence\n - `management.endpoints.web.exposure.include` / `.exclude`, `base-path`, `management.server.port` / address\n - `management.endpoint.health.show-details` / `show-components`\n - Which endpoints are effectively reachable (health, info, env, heapdump, threaddump, prometheus/metrics, shutdown, custom)\n - Existing Spring Security rules for Actuator (`EndpointRequest`, path matchers, CSRF)\n - Kubernetes/Helm probes and whether management is on a public Service/Ingress\n - Metrics / Prometheus / profiler (e.g. Pyroscope) scrape paths and auth\n\n2. Target design\n - Expose only ops-needed endpoints (typically health + info; metrics/prometheus only with scrape auth)\n - Never leave env / heapdump / threaddump / logfile / shutdown / configprops publicly reachable\n - Prefer a separate management port when the app has a public HTTP surface\n - Health details: `never` anonymously; `when_authorized` only with real operator roles\n - Dedicated management `SecurityFilterChain`; keep CSRF for browser-facing state changes\n - Probes aimed at management health; management not on public Ingress/LoadBalancer\n - Block cloud-metadata leakage via env/info contributors\n\n3. Patches (prefer diffs)\n - `application.yml` / profile-specific properties (Boot 3 exposure keys, base-path, show-details, management port)\n - `SecurityFilterChain` (or XML/adapter equivalent) using `EndpointRequest`\n - Deployment/Service/Ingress or Helm values for probes and port exposure\n - Scrape auth notes (bearer/mTLS) — names only, no real secrets\n\n4. Output format\n - Severity-ordered findings (blocker / major / minor)\n - Exposure matrix: endpoint → anonymous / role / disabled\n - Concrete diffs for each blocker/major\n - Validation steps: curl anonymous vs authenticated, in-cluster probe check, negative tests for env/heapdump/shutdown\n - Residual risks and explicit assumptions if manifests or Security config are missing in-repo\n\nConstraints:\n- Do not invent IdP URLs, passwords, or cluster IPs — use placeholders consistent with repo style.\n- Do not weaken API security to \"fix\" Actuator; do not disable CSRF globally.\n- Keep the diff minimal; no unrelated refactors.\n- Prefer Spring Boot 3 property names when the project is on Boot 3; call out 2.x differences if evidenced.\n\nStart from the files I pointed at (or search for `management.endpoints` and Actuator security). Prefer patches over vague advice." + "body": "Harden Spring Boot Actuator for the application at the path I provide. Produce a PR-ready lock-down: inventory, severity-ordered findings, and concrete config/security/probe patches.\n\nReview current state and deliver:\n\n1. Inventory\n - Boot version signals (2.x vs 3.x), Actuator dependency presence\n - `management.endpoints.web.exposure.include` / `.exclude`, `base-path`, `management.server.port` / address\n - `management.endpoint.health.show-details` / `show-components`\n - Which endpoints are effectively reachable (health, info, env, heapdump, threaddump, prometheus/metrics, shutdown, custom)\n - Existing Spring Security rules for Actuator (`EndpointRequest`, path matchers, CSRF)\n - Kubernetes/Helm probes and whether management is on a public Service/Ingress\n - Metrics / Prometheus / profiler (e.g. Pyroscope) scrape paths and auth\n\n2. Target design\n - Expose only ops-needed endpoints (typically health + info; metrics/prometheus only with scrape auth)\n - Never leave env / heapdump / threaddump / logfile / shutdown / configprops publicly reachable\n - Prefer a separate management port when the app has a public HTTP surface\n - Health details: `never` anonymously; `when_authorized` only with real operator roles\n - Dedicated management `SecurityFilterChain`; keep CSRF for browser-facing state changes\n - Probes aimed at management health; management not on public Ingress/LoadBalancer\n - Block cloud-metadata leakage via env/info contributors\n\n3. Patches (prefer diffs)\n - `application.yml` / profile-specific properties (Boot 3 exposure keys, base-path, show-details, management port)\n - `SecurityFilterChain` (or XML/adapter equivalent) using `EndpointRequest`\n - Deployment/Service/Ingress or Helm values for probes and port exposure\n - Scrape auth notes (bearer/mTLS) \u2014 names only, no real secrets\n\n4. Output format\n - Severity-ordered findings (blocker / major / minor)\n - Exposure matrix: endpoint \u2192 anonymous / role / disabled\n - Concrete diffs for each blocker/major\n - Validation steps: curl anonymous vs authenticated, in-cluster probe check, negative tests for env/heapdump/shutdown\n - Residual risks and explicit assumptions if manifests or Security config are missing in-repo\n\nConstraints:\n- Do not invent IdP URLs, passwords, or cluster IPs \u2014 use placeholders consistent with repo style.\n- Do not weaken API security to \"fix\" Actuator; do not disable CSRF globally.\n- Keep the diff minimal; no unrelated refactors.\n- Prefer Spring Boot 3 property names when the project is on Boot 3; call out 2.x differences if evidenced.\n\nStart from the files I pointed at (or search for `management.endpoints` and Actuator security). Prefer patches over vague advice." }, { "id": "author-safe-flyway-migration", @@ -309,7 +309,26 @@ "database" ], "formatNotes": "All three. Point the tool at `db/migration`, `spring.flyway.*` config, and any migrate Job/CI workflow first. Prefer concrete next-version SQL and checklists over generic DDL advice.", - "body": "Author a safe, PR-ready Flyway migration for the Spring Boot app at the path I provide. Produce the next versioned SQL (and any necessary app-tolerance notes), plus a verification checklist suitable for Copilot / Claude Code / Codex.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service / module path: {{SERVICE_PATH}}\n- Database engine: {{DB_ENGINE}} (e.g. PostgreSQL, MySQL, SQL Server)\n- Migration location: {{MIGRATION_DIR}} (default `src/main/resources/db/migration`)\n- Change intent: {{CHANGE_INTENT}} (add column, new table, backfill, tighten constraint, rename, drop, index)\n- Zero-downtime required: {{ZERO_DOWNTIME}} (yes/no; default yes on AKS/K8s)\n- Current highest version observed: {{CURRENT_VERSION}}\n\nRequirements:\n\n1. Inventory\n - Existing Flyway/Liquibase dependency and `spring.flyway.*` / `spring.liquibase.*`\n - Migration files present; next version number; naming style (`V__` vs timed versions)\n - Whether migrate runs on startup, as a K8s Job, or in CI\n - Any `out-of-order`, `validate-on-migrate`, `clean-disabled`, placeholder, or callback config\n - Evidence of expand/contract history or risky prior `DROP`/`RENAME` patterns\n\n2. Classify and plan\n - Label the change: expand, backfill, contract, or config-only\n - If rename/drop/cutover: split into ordered steps across releases; do not ship destructive contract with the code cutover in one PR\n - Call out N and N-1 pod compatibility when {{ZERO_DOWNTIME}} is yes\n\n3. Author artifacts (prefer concrete files/diffs)\n - Next `V{{NEXT_VERSION}}__{{short_snake_description}}.sql` — additive first; nullable expands; explicit indexes; engine-appropriate lock/statement timeout SET when useful\n - Optional `R__*.sql` only if idempotent view/function refresh is required (explain why)\n - Minimal entity/repository notes so app code tolerates expand before contract\n - CI snippet or test note: `flyway validate` / `info` or Boot test with validate-on-migrate + ephemeral DB\n - AKS/K8s ordering note: migrate-before-rollout or equivalent; no public secrets in SQL\n\n4. Verification checklist\n - Fresh migrate + restart succeeds\n - `flyway validate` clean; checksums of old versions unchanged\n - Old app binary still works against expanded schema (if expand)\n - Grep for secrets in SQL; confirm no `clean` enabled for shared envs\n - Residual risks: long locks, large backfills, repair caveats (repair is not rollback)\n\nConstraints:\n- Forward-only: do not edit already-applied versioned migrations; do not invent fake checksums.\n- Secrets never in SQL — use `{{PLACEHOLDER}}` names only for non-secret identifiers.\n- Do not enable `out-of-order` or `clean` for prod-like profiles unless the repo already has a documented hotfix process (then call it out, do not silently turn on).\n- Do not claim Flyway auto-rollback; prescribe expand/contract instead.\n- Keep the diff minimal; no unrelated refactors.\n- Optimize instructions for GitHub Copilot, Claude Code, and Codex — concrete paths and checklists over essays.\n\nOutput format:\n1. Short plan (classification + version bump)\n2. File diffs / full new SQL\n3. Config/CI/K8s notes (only what changed)\n4. Verification checklist\n5. Residual risks and follow-up contract PR (if any)\n\nStart from {{MIGRATION_DIR}} and Flyway config under {{SERVICE_PATH}}. Prefer patches over vague advice.\n" + "body": "Author a safe, PR-ready Flyway migration for the Spring Boot app at the path I provide. Produce the next versioned SQL (and any necessary app-tolerance notes), plus a verification checklist suitable for Copilot / Claude Code / Codex.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service / module path: {{SERVICE_PATH}}\n- Database engine: {{DB_ENGINE}} (e.g. PostgreSQL, MySQL, SQL Server)\n- Migration location: {{MIGRATION_DIR}} (default `src/main/resources/db/migration`)\n- Change intent: {{CHANGE_INTENT}} (add column, new table, backfill, tighten constraint, rename, drop, index)\n- Zero-downtime required: {{ZERO_DOWNTIME}} (yes/no; default yes on AKS/K8s)\n- Current highest version observed: {{CURRENT_VERSION}}\n\nRequirements:\n\n1. Inventory\n - Existing Flyway/Liquibase dependency and `spring.flyway.*` / `spring.liquibase.*`\n - Migration files present; next version number; naming style (`V__` vs timed versions)\n - Whether migrate runs on startup, as a K8s Job, or in CI\n - Any `out-of-order`, `validate-on-migrate`, `clean-disabled`, placeholder, or callback config\n - Evidence of expand/contract history or risky prior `DROP`/`RENAME` patterns\n\n2. Classify and plan\n - Label the change: expand, backfill, contract, or config-only\n - If rename/drop/cutover: split into ordered steps across releases; do not ship destructive contract with the code cutover in one PR\n - Call out N and N-1 pod compatibility when {{ZERO_DOWNTIME}} is yes\n\n3. Author artifacts (prefer concrete files/diffs)\n - Next `V{{NEXT_VERSION}}__{{short_snake_description}}.sql` \u2014 additive first; nullable expands; explicit indexes; engine-appropriate lock/statement timeout SET when useful\n - Optional `R__*.sql` only if idempotent view/function refresh is required (explain why)\n - Minimal entity/repository notes so app code tolerates expand before contract\n - CI snippet or test note: `flyway validate` / `info` or Boot test with validate-on-migrate + ephemeral DB\n - AKS/K8s ordering note: migrate-before-rollout or equivalent; no public secrets in SQL\n\n4. Verification checklist\n - Fresh migrate + restart succeeds\n - `flyway validate` clean; checksums of old versions unchanged\n - Old app binary still works against expanded schema (if expand)\n - Grep for secrets in SQL; confirm no `clean` enabled for shared envs\n - Residual risks: long locks, large backfills, repair caveats (repair is not rollback)\n\nConstraints:\n- Forward-only: do not edit already-applied versioned migrations; do not invent fake checksums.\n- Secrets never in SQL \u2014 use `{{PLACEHOLDER}}` names only for non-secret identifiers.\n- Do not enable `out-of-order` or `clean` for prod-like profiles unless the repo already has a documented hotfix process (then call it out, do not silently turn on).\n- Do not claim Flyway auto-rollback; prescribe expand/contract instead.\n- Keep the diff minimal; no unrelated refactors.\n- Optimize instructions for GitHub Copilot, Claude Code, and Codex \u2014 concrete paths and checklists over essays.\n\nOutput format:\n1. Short plan (classification + version bump)\n2. File diffs / full new SQL\n3. Config/CI/K8s notes (only what changed)\n4. Verification checklist\n5. Residual risks and follow-up contract PR (if any)\n\nStart from {{MIGRATION_DIR}} and Flyway config under {{SERVICE_PATH}}. Prefer patches over vague advice.\n" + }, + { + "id": "add-testcontainers-integration-tests", + "title": "Add Testcontainers Integration Tests", + "whenToUse": "You need PR-ready Spring Boot integration tests that boot real Postgres/Kafka/Redis (or similar) via Testcontainers instead of mocks or a shared staging database.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "java", + "spring-boot", + "testcontainers", + "testing", + "docker" + ], + "formatNotes": "All three. Point the tool at the service module, existing tests, and build file first. Prefer extending an existing container base over inventing a second lifecycle.", + "body": "Task: Add hermetic Spring Boot integration tests using Testcontainers for the module at the path I provide.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Module / service path: {{MODULE_PATH}}\n- Dependencies to containerize: {{DEPS}} (e.g. Postgres 16, Kafka, Redis, LocalStack S3)\n- Test style in-repo: {{TEST_STYLE}} (JUnit 5, @SpringBootTest, @DataJpaTest, RestAssured/WebTestClient, etc.)\n- Build command: {{TEST_COMMAND}} (e.g. ./mvnw -pl service-x test)\n- Migrations: {{MIGRATIONS}} (Flyway / Liquibase / none)\n\nRequirements:\n\n1. Inventory\n - Existing Testcontainers usage, `@ServiceConnection`, `DynamicPropertySource`, or abstract container bases\n - Spring Boot version signals (3.1+ service connections vs older patterns)\n - Build BOM / testcontainers dependencies already present\n - Whether CI runners already expose Docker\n - Any tests currently pointed at localhost or staging URLs\n\n2. Design\n - Prefer the narrowest slice that still hits the real adapter (`@DataJpaTest` vs full `@SpringBootTest`)\n - One shared container lifecycle per suite (static singleton or Spring-managed); do not start a new DB per method unless isolation is under test\n - Pin image tags (no `latest`); wire JDBC/broker settings from the container\n - Run migrations in the test context when {{MIGRATIONS}} is Flyway/Liquibase\n - Keep mocks only at true external boundaries not being validated\n\n3. Author artifacts (prefer concrete diffs)\n - Test dependency tweaks if the BOM does not already manage Testcontainers\n - Shared container helper or `@TestConfiguration`\n - 2\u20133 tests: happy path, one validation/constraint failure, one not-found or duplicate-key mapping\n - `application-test` overrides only when service connection cannot cover a property\n - CI note: Docker requirement; fail fast if unavailable\n\n4. Verification\n - Run {{TEST_COMMAND}} and show results\n - Confirm containers stop cleanly (no orphaned Postgres on the daemon)\n - Grep test resources for staging hosts, real secrets, and unpinned `latest` images\n\nConstraints:\n- Do not invent registry mirrors, company image prefixes, or cloud account IDs \u2014 use placeholders if the repo does not define them.\n- Do not disable Flyway/Liquibase in tests when production relies on it.\n- Do not replace an existing shared container base with a duplicate lifecycle.\n- Keep the diff minimal; no unrelated refactors.\n- Optimize for GitHub Copilot, Claude Code, and Codex \u2014 concrete paths and commands over essays.\n\nOutput format:\n1. Short plan (slice + images + lifecycle)\n2. File diffs\n3. Commands run + outcomes\n4. What remains mocked (and why)\n5. Residual risks (CI Docker, parallel suites, image pull time)\n\nStart from {{MODULE_PATH}} and existing `src/test`. Prefer patches over vague advice.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index 6aa4264..3ee5e50 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -21,8 +21,8 @@ "spring-boot", "microservices" ], - "formatNotes": "All three: paste the body as standing project guidance. Copilot → `.github/copilot-instructions.md` or `.github/instructions/spring.instructions.md` with applyTo for `**/*.{java,xml,yml}`. Claude Code → `.claude/skills/spring-boot-guardrails/SKILL.md` (YAML frontmatter + body) or a short pointer in `CLAUDE.md`. Codex → section in root `AGENTS.md` or a linked `docs/agents/spring-boot.md`.", - "body": "# Skill: Spring Boot Service Guardrails\n\n## Goal\nProduce production-ready Spring Boot changes that are secure, testable, and consistent with layered architecture.\n\n## When to apply\n- New REST endpoints, services, repositories, or configuration\n- Refactors that touch request validation, auth, or persistence\n\n## Architecture rules\n1. Keep controllers thin: validate input, map DTO ↔ domain, call one service method, map errors.\n2. Business rules live in services; repositories do persistence only.\n3. Prefer constructor injection; never field-inject `@Autowired` on production beans.\n4. Use explicit DTOs at the API boundary; do not expose JPA entities in responses.\n5. Fail closed on authz: deny by default, document required authorities on each endpoint.\n\n## Implementation steps\n1. Locate existing package layout and match naming (`...controller`, `...service`, `...repository`).\n2. Add/adjust request validation (`@Valid`, Bean Validation constraints) before business logic.\n3. Map domain errors to stable problem responses (status + code + safe message).\n4. Add unit tests for service rules and at least one WebMvc/WebTestClient slice for the endpoint.\n5. Update OpenAPI/annotations only when the public contract changes.\n\n## Constraints\n- No secrets in code, logs, or test fixtures.\n- Do not weaken CSRF/security config unless the change is explicitly about security and reviewed.\n- Prefer existing project libraries over new dependencies.\n- Keep methods small; extract helpers instead of deep nesting.\n\n## Output format\n- Summary of files touched (bullets)\n- Code changes ready to apply\n- Test plan: commands to run + cases covered\n- Residual risks (auth, migrations, breaking API)" + "formatNotes": "All three: paste the body as standing project guidance. Copilot \u2192 `.github/copilot-instructions.md` or `.github/instructions/spring.instructions.md` with applyTo for `**/*.{java,xml,yml}`. Claude Code \u2192 `.claude/skills/spring-boot-guardrails/SKILL.md` (YAML frontmatter + body) or a short pointer in `CLAUDE.md`. Codex \u2192 section in root `AGENTS.md` or a linked `docs/agents/spring-boot.md`.", + "body": "# Skill: Spring Boot Service Guardrails\n\n## Goal\nProduce production-ready Spring Boot changes that are secure, testable, and consistent with layered architecture.\n\n## When to apply\n- New REST endpoints, services, repositories, or configuration\n- Refactors that touch request validation, auth, or persistence\n\n## Architecture rules\n1. Keep controllers thin: validate input, map DTO \u2194 domain, call one service method, map errors.\n2. Business rules live in services; repositories do persistence only.\n3. Prefer constructor injection; never field-inject `@Autowired` on production beans.\n4. Use explicit DTOs at the API boundary; do not expose JPA entities in responses.\n5. Fail closed on authz: deny by default, document required authorities on each endpoint.\n\n## Implementation steps\n1. Locate existing package layout and match naming (`...controller`, `...service`, `...repository`).\n2. Add/adjust request validation (`@Valid`, Bean Validation constraints) before business logic.\n3. Map domain errors to stable problem responses (status + code + safe message).\n4. Add unit tests for service rules and at least one WebMvc/WebTestClient slice for the endpoint.\n5. Update OpenAPI/annotations only when the public contract changes.\n\n## Constraints\n- No secrets in code, logs, or test fixtures.\n- Do not weaken CSRF/security config unless the change is explicitly about security and reviewed.\n- Prefer existing project libraries over new dependencies.\n- Keep methods small; extract helpers instead of deep nesting.\n\n## Output format\n- Summary of files touched (bullets)\n- Code changes ready to apply\n- Test plan: commands to run + cases covered\n- Residual risks (auth, migrations, breaking API)" }, { "id": "aks-workload-hardening", @@ -39,7 +39,7 @@ "kubernetes" ], "formatNotes": "All three. Copilot path-scoped instructions for `**/k8s/**`, `**/helm/**`, `**/*.{yaml,yml}`. Claude Code skill under `.claude/skills/aks-hardening/SKILL.md`. Codex: nested `deploy/AGENTS.md` or root `AGENTS.md` section titled AKS.", - "body": "# Skill: AKS Workload Hardening\n\n## Goal\nShip Kubernetes workloads to AKS that are operable, least-privilege, and reviewable.\n\n## When to apply\n- New Deployment/StatefulSet/Job, Service, Ingress/Gateway, HPA, NetworkPolicy, or Helm values\n- Reviews of manifests before merge to the deploy path\n\n## Checklist (apply in order)\n1. **Identity**: prefer workload identity / managed identity over long-lived secrets in pods.\n2. **Resources**: set requests and limits; document why limits differ from requests.\n3. **Probes**: readiness + liveness (and startup when cold start is slow); probes must not be identical if that hides failure.\n4. **Security context**: runAsNonRoot, readOnlyRootFilesystem when feasible, drop ALL capabilities, no privileged.\n5. **Networking**: explicit Service ports; NetworkPolicy default-deny + allowlist if the cluster uses policies.\n6. **Rollouts**: rollingUpdate maxUnavailable/maxSurge; PodDisruptionBudget for user-facing services.\n7. **Observability**: consistent labels (`app`, `version`, `team`); scrape annotations or OpenTelemetry only if the platform expects them.\n8. **Secrets**: reference Key Vault / CSI / external secrets — never commit raw credentials.\n\n## Azure-specific notes\n- Prefer Azure CNI / documented cluster networking patterns already used in-repo.\n- Align ingress class, TLS secrets, and public vs private exposure with existing apps.\n- For AKS node pools, avoid hostPath and hostNetwork unless the platform team already uses them for that component.\n\n## Constraints\n- Do not invent cluster-wide CRDs or operators that are not already installed.\n- Keep manifests idempotent and environment-parameterized (overlays/values), not hardcoded subscription IDs in app charts.\n\n## Output format\n- Diff-oriented manifest changes\n- Table: control → status (pass/fail/n/a) → note\n- Commands to validate (`kubectl dry-run` / `helm template` / policy checks used in-repo)" + "body": "# Skill: AKS Workload Hardening\n\n## Goal\nShip Kubernetes workloads to AKS that are operable, least-privilege, and reviewable.\n\n## When to apply\n- New Deployment/StatefulSet/Job, Service, Ingress/Gateway, HPA, NetworkPolicy, or Helm values\n- Reviews of manifests before merge to the deploy path\n\n## Checklist (apply in order)\n1. **Identity**: prefer workload identity / managed identity over long-lived secrets in pods.\n2. **Resources**: set requests and limits; document why limits differ from requests.\n3. **Probes**: readiness + liveness (and startup when cold start is slow); probes must not be identical if that hides failure.\n4. **Security context**: runAsNonRoot, readOnlyRootFilesystem when feasible, drop ALL capabilities, no privileged.\n5. **Networking**: explicit Service ports; NetworkPolicy default-deny + allowlist if the cluster uses policies.\n6. **Rollouts**: rollingUpdate maxUnavailable/maxSurge; PodDisruptionBudget for user-facing services.\n7. **Observability**: consistent labels (`app`, `version`, `team`); scrape annotations or OpenTelemetry only if the platform expects them.\n8. **Secrets**: reference Key Vault / CSI / external secrets \u2014 never commit raw credentials.\n\n## Azure-specific notes\n- Prefer Azure CNI / documented cluster networking patterns already used in-repo.\n- Align ingress class, TLS secrets, and public vs private exposure with existing apps.\n- For AKS node pools, avoid hostPath and hostNetwork unless the platform team already uses them for that component.\n\n## Constraints\n- Do not invent cluster-wide CRDs or operators that are not already installed.\n- Keep manifests idempotent and environment-parameterized (overlays/values), not hardcoded subscription IDs in app charts.\n\n## Output format\n- Diff-oriented manifest changes\n- Table: control \u2192 status (pass/fail/n/a) \u2192 note\n- Commands to validate (`kubectl dry-run` / `helm template` / policy checks used in-repo)" }, { "id": "gha-devsecops-pipeline", @@ -56,7 +56,7 @@ "ci" ], "formatNotes": "All three. Copilot: `.github/instructions/actions.instructions.md` with applyTo `**/.github/workflows/*.yml`. Claude Code: skill `gha-devsecops`. Codex: `AGENTS.md` CI section + link to workflow conventions.", - "body": "# Skill: GitHub Actions DevSecOps Pipeline\n\n## Goal\nProduce workflows that are pinned, least-privilege, cached sensibly, and fail on real security findings.\n\n## When to apply\n- New CI/CD workflows or reusable workflows\n- Adding scanners, OIDC deploy, or environment protections\n\n## Required patterns\n1. Pin actions by full commit SHA (not floating major tags) when the repo already does so; otherwise pin to a verified major and note follow-up.\n2. Set `permissions:` explicitly at workflow or job level — default to read, escalate per job.\n3. Prefer OIDC to cloud roles over long-lived cloud keys in GitHub secrets.\n4. Separate build/test from deploy; deploy only from protected environments/branches.\n5. Cache dependencies with precise keys; never cache credentials or built secrets.\n6. Upload SBOMs / scan results as artifacts when the pipeline already expects them.\n\n## Security gates (minimum)\n- Dependency vulnerability scan (language-appropriate)\n- Secret scan on the diff or full repo as configured by the org\n- SAST or linter gate that blocks on high severity when tools exist in-repo\n- Container image scan before push/promote if images are produced\n\n## Implementation steps\n1. Mirror structure of an existing healthy workflow in the repo.\n2. Add jobs with clear names; use `needs:` for the security → build → deploy chain.\n3. Parameterize versions via `env:` at the top.\n4. Document required secrets/vars in a short header comment (names only, never values).\n5. Add a dry-run or `workflow_dispatch` path for risky deploys.\n\n## Constraints\n- No `pull_request_target` with untrusted checkout + secrets unless following org-approved pattern.\n- Avoid `curl | bash` installers; use setup actions or package managers.\n- Do not echo secrets; mask sensitive outputs.\n\n## Output format\n- Complete workflow YAML (or surgical patch)\n- Permission matrix per job\n- How to verify locally / with `act` if used\n- Residual risks and follow-ups" + "body": "# Skill: GitHub Actions DevSecOps Pipeline\n\n## Goal\nProduce workflows that are pinned, least-privilege, cached sensibly, and fail on real security findings.\n\n## When to apply\n- New CI/CD workflows or reusable workflows\n- Adding scanners, OIDC deploy, or environment protections\n\n## Required patterns\n1. Pin actions by full commit SHA (not floating major tags) when the repo already does so; otherwise pin to a verified major and note follow-up.\n2. Set `permissions:` explicitly at workflow or job level \u2014 default to read, escalate per job.\n3. Prefer OIDC to cloud roles over long-lived cloud keys in GitHub secrets.\n4. Separate build/test from deploy; deploy only from protected environments/branches.\n5. Cache dependencies with precise keys; never cache credentials or built secrets.\n6. Upload SBOMs / scan results as artifacts when the pipeline already expects them.\n\n## Security gates (minimum)\n- Dependency vulnerability scan (language-appropriate)\n- Secret scan on the diff or full repo as configured by the org\n- SAST or linter gate that blocks on high severity when tools exist in-repo\n- Container image scan before push/promote if images are produced\n\n## Implementation steps\n1. Mirror structure of an existing healthy workflow in the repo.\n2. Add jobs with clear names; use `needs:` for the security \u2192 build \u2192 deploy chain.\n3. Parameterize versions via `env:` at the top.\n4. Document required secrets/vars in a short header comment (names only, never values).\n5. Add a dry-run or `workflow_dispatch` path for risky deploys.\n\n## Constraints\n- No `pull_request_target` with untrusted checkout + secrets unless following org-approved pattern.\n- Avoid `curl | bash` installers; use setup actions or package managers.\n- Do not echo secrets; mask sensitive outputs.\n\n## Output format\n- Complete workflow YAML (or surgical patch)\n- Permission matrix per job\n- How to verify locally / with `act` if used\n- Residual risks and follow-ups" }, { "id": "jwt-oauth-security-review", @@ -72,8 +72,8 @@ "oauth", "security" ], - "formatNotes": "All three. Keep this skill concise — security rules first. Copilot instructions file for auth packages; Claude Code skill with clear description triggers; Codex `AGENTS.md` Security section.", - "body": "# Skill: JWT / OAuth Security Review\n\n## Goal\nEnsure token-based auth is validated correctly and fails safely.\n\n## When to apply\n- Resource server / API gateway JWT middleware\n- Authorization code + PKCE, client credentials, or token exchange flows\n- Custom claim mapping into roles/permissions\n\n## Validation requirements\n1. Verify signature with the correct JWKS/issuer keys; reject `alg=none` and unexpected algorithms.\n2. Validate `iss`, `aud` (or equivalent), `exp`, `nbf`, and token use (`typ` / `token_use`) as required by the IdP.\n3. Prefer asymmetric algorithms (RS256/ES256) over shared HMAC for multi-service APIs.\n4. Map scopes/roles explicitly; do not treat presence of a JWT as authorization for every route.\n5. Clock skew: small leeway only; document the value.\n\n## Common anti-patterns to reject\n- Decoding payload without verifying signature\n- Accepting tokens from multiple issuers without an allowlist\n- Logging raw tokens or authorization headers\n- Storing refresh tokens in localStorage for confidential apps without a deliberate threat model\n- Using access tokens as proof of email/identity without checking IdP claims\n\n## Review steps\n1. Identify token entry points (filters, middleware, gateway).\n2. Trace claim → permission mapping.\n3. Confirm error paths return generic 401/403 without leaking key material.\n4. Check test coverage for expired, wrong-aud, wrong-iss, and tampered tokens.\n\n## Output format\n- Findings ordered by severity (blocker / major / minor)\n- Recommended code or config change per finding\n- Test cases to add (table)\n- Explicit “out of scope” notes" + "formatNotes": "All three. Keep this skill concise \u2014 security rules first. Copilot instructions file for auth packages; Claude Code skill with clear description triggers; Codex `AGENTS.md` Security section.", + "body": "# Skill: JWT / OAuth Security Review\n\n## Goal\nEnsure token-based auth is validated correctly and fails safely.\n\n## When to apply\n- Resource server / API gateway JWT middleware\n- Authorization code + PKCE, client credentials, or token exchange flows\n- Custom claim mapping into roles/permissions\n\n## Validation requirements\n1. Verify signature with the correct JWKS/issuer keys; reject `alg=none` and unexpected algorithms.\n2. Validate `iss`, `aud` (or equivalent), `exp`, `nbf`, and token use (`typ` / `token_use`) as required by the IdP.\n3. Prefer asymmetric algorithms (RS256/ES256) over shared HMAC for multi-service APIs.\n4. Map scopes/roles explicitly; do not treat presence of a JWT as authorization for every route.\n5. Clock skew: small leeway only; document the value.\n\n## Common anti-patterns to reject\n- Decoding payload without verifying signature\n- Accepting tokens from multiple issuers without an allowlist\n- Logging raw tokens or authorization headers\n- Storing refresh tokens in localStorage for confidential apps without a deliberate threat model\n- Using access tokens as proof of email/identity without checking IdP claims\n\n## Review steps\n1. Identify token entry points (filters, middleware, gateway).\n2. Trace claim \u2192 permission mapping.\n3. Confirm error paths return generic 401/403 without leaking key material.\n4. Check test coverage for expired, wrong-aud, wrong-iss, and tampered tokens.\n\n## Output format\n- Findings ordered by severity (blocker / major / minor)\n- Recommended code or config change per finding\n- Test cases to add (table)\n- Explicit \u201cout of scope\u201d notes" }, { "id": "data-platform-pipeline-review", @@ -90,7 +90,7 @@ "pipelines" ], "formatNotes": "All three. Avoid embedding tenant-specific connection strings. Copilot path rules for notebook/ETL folders; Claude Code skill; Codex nested `AGENTS.md` under data pipelines.", - "body": "# Skill: Data Platform Pipeline Review\n\n## Goal\nDeliver data pipelines that are idempotent, observable, and safe for sensitive fields.\n\n## When to apply\n- New Databricks jobs/notebooks, Spark transformations, or ADF/Fabric-style pipelines\n- Schema changes, backfills, or catch-up loads\n\n## Design rules\n1. **Contracts first**: define input/output schemas and ownership before coding transforms.\n2. **Idempotency**: merges/upserts keyed by business keys; safe re-runs without duplicating facts.\n3. **Partitioning**: choose partition columns for query patterns; avoid tiny-file explosion.\n4. **Quality gates**: null checks, referential checks, and row-count anomalies before publish.\n5. **PII/PHI**: classify columns; tokenize/hash/mask per platform standards; least-privilege access.\n6. **Orchestration**: clear dependencies, retries with backoff, and dead-letter / failure paths.\n7. **Cost**: cache only when reused; prune unused columns early; right-size clusters/pools.\n\n## Implementation steps\n1. Sketch source → bronze/silver/gold (or in-repo layering names) data flow.\n2. Implement transforms with explicit schemas; avoid `select *` across trust boundaries.\n3. Add data quality checks as jobs/tasks that block downstream publish on failure.\n4. Emit metrics/logs with run id, batch window, and row counts.\n5. Document backfill procedure and watermark strategy.\n\n## Constraints\n- Do not invent employer-specific catalog names, secrets, or subscription IDs.\n- Prefer existing platform libraries and patterns in the repository.\n- No production writes from ad-hoc interactive sessions in committed jobs.\n\n## Output format\n- Pipeline diagram (mermaid or bullet edges)\n- Task list with inputs/outputs\n- Risk register (data loss, late data, PII)\n- Validation queries / checks to run after deploy" + "body": "# Skill: Data Platform Pipeline Review\n\n## Goal\nDeliver data pipelines that are idempotent, observable, and safe for sensitive fields.\n\n## When to apply\n- New Databricks jobs/notebooks, Spark transformations, or ADF/Fabric-style pipelines\n- Schema changes, backfills, or catch-up loads\n\n## Design rules\n1. **Contracts first**: define input/output schemas and ownership before coding transforms.\n2. **Idempotency**: merges/upserts keyed by business keys; safe re-runs without duplicating facts.\n3. **Partitioning**: choose partition columns for query patterns; avoid tiny-file explosion.\n4. **Quality gates**: null checks, referential checks, and row-count anomalies before publish.\n5. **PII/PHI**: classify columns; tokenize/hash/mask per platform standards; least-privilege access.\n6. **Orchestration**: clear dependencies, retries with backoff, and dead-letter / failure paths.\n7. **Cost**: cache only when reused; prune unused columns early; right-size clusters/pools.\n\n## Implementation steps\n1. Sketch source \u2192 bronze/silver/gold (or in-repo layering names) data flow.\n2. Implement transforms with explicit schemas; avoid `select *` across trust boundaries.\n3. Add data quality checks as jobs/tasks that block downstream publish on failure.\n4. Emit metrics/logs with run id, batch window, and row counts.\n5. Document backfill procedure and watermark strategy.\n\n## Constraints\n- Do not invent employer-specific catalog names, secrets, or subscription IDs.\n- Prefer existing platform libraries and patterns in the repository.\n- No production writes from ad-hoc interactive sessions in committed jobs.\n\n## Output format\n- Pipeline diagram (mermaid or bullet edges)\n- Task list with inputs/outputs\n- Risk register (data loss, late data, PII)\n- Validation queries / checks to run after deploy" }, { "id": "llm-eval-agent-workflow", @@ -109,7 +109,7 @@ "codex" ], "formatNotes": "Written for all three tools with format notes inline. Copilot: keep under ~2k tokens in `copilot-instructions.md`; put long procedures in linked docs. Claude Code: keep `CLAUDE.md` short; put this procedure in `.claude/skills/llm-eval/SKILL.md`. Codex: root `AGENTS.md` points to `docs/agents/llm-eval.md` so the main file stays small.", - "body": "# Skill: LLM Eval and Agent Workflow Pack\n\n## Goal\nRun agentic coding tasks with measurable quality bars and portable instructions across Copilot, Claude Code, and Codex.\n\n## Tool placement (read this first)\n- **GitHub Copilot**: project rules in `.github/copilot-instructions.md`; path-specific `*.instructions.md` with `applyTo`. Keep critical security rules first.\n- **Claude Code**: durable facts in `CLAUDE.md` (< ~200 lines). Multi-step procedures belong in `.claude/skills//SKILL.md` with `description` / `when_to_use`. Optional `@AGENTS.md` import for shared text.\n- **Codex**: durable ops in `AGENTS.md` (and nested / `AGENTS.override.md`). Keep concise; link out for long eval rubrics.\n\n## Eval workflow\n1. **Define the task card**: goal, constraints, in-scope paths, out-of-scope, Definition of Done.\n2. **Golden checks**: commands that must pass (unit/integration/lint). No silent skips.\n3. **Rubric** (score 0–2 each): correctness, safety (secrets/PII), diff discipline, test updates, docs/runbook touch.\n4. **Baseline**: run once without the skill/instructions, once with — compare rubric and token/time cost.\n5. **Regressions**: store failing prompts in an `evals/` list; re-run after instruction edits.\n\n## Agent loop (all tools)\n1. Restate goal and constraints in one short paragraph.\n2. Explore only relevant paths; avoid repo-wide rewrites.\n3. Implement smallest viable change; keep commits/PR focused.\n4. Run verification commands; fix failures before claiming done.\n5. Report: summary, files changed, commands run, residual risks.\n\n## Constraints\n- Never exfiltrate secrets or customer data into prompts, logs, or fixtures.\n- Prefer patching existing patterns over new frameworks.\n- If instructions conflict, stop and list conflicts instead of guessing.\n\n## Output format\n- Task restatement\n- Plan (3–7 steps)\n- Changes + verification evidence\n- Rubric scores + next instruction tweak (if any)" + "body": "# Skill: LLM Eval and Agent Workflow Pack\n\n## Goal\nRun agentic coding tasks with measurable quality bars and portable instructions across Copilot, Claude Code, and Codex.\n\n## Tool placement (read this first)\n- **GitHub Copilot**: project rules in `.github/copilot-instructions.md`; path-specific `*.instructions.md` with `applyTo`. Keep critical security rules first.\n- **Claude Code**: durable facts in `CLAUDE.md` (< ~200 lines). Multi-step procedures belong in `.claude/skills//SKILL.md` with `description` / `when_to_use`. Optional `@AGENTS.md` import for shared text.\n- **Codex**: durable ops in `AGENTS.md` (and nested / `AGENTS.override.md`). Keep concise; link out for long eval rubrics.\n\n## Eval workflow\n1. **Define the task card**: goal, constraints, in-scope paths, out-of-scope, Definition of Done.\n2. **Golden checks**: commands that must pass (unit/integration/lint). No silent skips.\n3. **Rubric** (score 0\u20132 each): correctness, safety (secrets/PII), diff discipline, test updates, docs/runbook touch.\n4. **Baseline**: run once without the skill/instructions, once with \u2014 compare rubric and token/time cost.\n5. **Regressions**: store failing prompts in an `evals/` list; re-run after instruction edits.\n\n## Agent loop (all tools)\n1. Restate goal and constraints in one short paragraph.\n2. Explore only relevant paths; avoid repo-wide rewrites.\n3. Implement smallest viable change; keep commits/PR focused.\n4. Run verification commands; fix failures before claiming done.\n5. Report: summary, files changed, commands run, residual risks.\n\n## Constraints\n- Never exfiltrate secrets or customer data into prompts, logs, or fixtures.\n- Prefer patching existing patterns over new frameworks.\n- If instructions conflict, stop and list conflicts instead of guessing.\n\n## Output format\n- Task restatement\n- Plan (3\u20137 steps)\n- Changes + verification evidence\n- Rubric scores + next instruction tweak (if any)" }, { "id": "otel-aks-observability", @@ -127,7 +127,7 @@ "azure" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/otel.instructions.md` with applyTo for `**/*.{java,ts,go,yml,yaml}` plus optional `.github/skills/otel-aks/SKILL.md`. Claude Code: `.claude/skills/otel-aks/SKILL.md` (YAML name+description) and a one-line pointer in CLAUDE.md. Codex: keep root AGENTS.md short; put the procedure in `docs/agents/otel-aks.md` or a nested `deploy/AGENTS.md` so you stay under the ~32KiB project-doc budget.", - "body": "# Skill: OpenTelemetry on AKS Services\n\n## Goal\nAdd or harden traces, metrics, and logs for services on Azure AKS so signals correlate and SLIs drive alerts—without leaking PII.\n\n## When to apply\n- New service missing OTel instrumentation\n- Existing AKS workload with sparse traces, high cardinality, or uncorrelated logs\n- Collector / exporter / sampling changes in-repo\n\n## Instrumentation checklist\n1. **Traces**: instrument inbound HTTP/gRPC, outbound clients, DB/messaging; propagate W3C trace context.\n2. **Metrics**: RED/USE or domain SLIs (latency, error rate, saturation); avoid high-cardinality labels (raw user ids, URLs with ids).\n3. **Logs**: include `trace_id` / `span_id` on every request log line; keep severity consistent.\n4. **Semantic conventions**: prefer OTel HTTP/DB/RPC attribute names; do not invent parallel keys.\n5. **Resource attributes**: set `service.name`, `service.version`, `deployment.environment` (and cluster/namespace if available).\n6. **Exporters**: OTLP to the in-cluster collector endpoint already used by the repo; no ad-hoc SaaS SDKs unless already present.\n7. **Sampling**: head/tail sampling policy documented; raise sample rate only for error/slow paths when needed.\n8. **PII redaction**: scrub tokens, emails, phone numbers, auth headers before export; never log raw JWTs.\n9. **Dashboards / alerts**: map panels and alerts to SLIs (availability, latency p95/p99, error budget)—not vanity graphs.\n\n## AKS notes\n- Prefer **in-process** SDK when the language runtime already has one in this repo; use sidecar only if that pattern already exists.\n- Collector: reuse existing **DaemonSet** (node agent) or **Gateway** deployment patterns in-repo—do not introduce a second collector stack.\n- Ensure NetworkPolicy / private endpoints allow pod → collector OTLP; keep scrape ports off the public Service.\n\n## Constraints\n- Do not invent collector charts or CRDs not already in the repo.\n- Do not disable sampling “temporarily” in production manifests.\n- Prefer smallest diff: SDK config + attributes before new infra.\n\n## Output format\n- Summary of gaps found\n- Files / manifests to change (bullet list)\n- Checklist results (pass/fail per item above)\n- Residual risks (cardinality, cost, missing SLIs)" + "body": "# Skill: OpenTelemetry on AKS Services\n\n## Goal\nAdd or harden traces, metrics, and logs for services on Azure AKS so signals correlate and SLIs drive alerts\u2014without leaking PII.\n\n## When to apply\n- New service missing OTel instrumentation\n- Existing AKS workload with sparse traces, high cardinality, or uncorrelated logs\n- Collector / exporter / sampling changes in-repo\n\n## Instrumentation checklist\n1. **Traces**: instrument inbound HTTP/gRPC, outbound clients, DB/messaging; propagate W3C trace context.\n2. **Metrics**: RED/USE or domain SLIs (latency, error rate, saturation); avoid high-cardinality labels (raw user ids, URLs with ids).\n3. **Logs**: include `trace_id` / `span_id` on every request log line; keep severity consistent.\n4. **Semantic conventions**: prefer OTel HTTP/DB/RPC attribute names; do not invent parallel keys.\n5. **Resource attributes**: set `service.name`, `service.version`, `deployment.environment` (and cluster/namespace if available).\n6. **Exporters**: OTLP to the in-cluster collector endpoint already used by the repo; no ad-hoc SaaS SDKs unless already present.\n7. **Sampling**: head/tail sampling policy documented; raise sample rate only for error/slow paths when needed.\n8. **PII redaction**: scrub tokens, emails, phone numbers, auth headers before export; never log raw JWTs.\n9. **Dashboards / alerts**: map panels and alerts to SLIs (availability, latency p95/p99, error budget)\u2014not vanity graphs.\n\n## AKS notes\n- Prefer **in-process** SDK when the language runtime already has one in this repo; use sidecar only if that pattern already exists.\n- Collector: reuse existing **DaemonSet** (node agent) or **Gateway** deployment patterns in-repo\u2014do not introduce a second collector stack.\n- Ensure NetworkPolicy / private endpoints allow pod \u2192 collector OTLP; keep scrape ports off the public Service.\n\n## Constraints\n- Do not invent collector charts or CRDs not already in the repo.\n- Do not disable sampling \u201ctemporarily\u201d in production manifests.\n- Prefer smallest diff: SDK config + attributes before new infra.\n\n## Output format\n- Summary of gaps found\n- Files / manifests to change (bullet list)\n- Checklist results (pass/fail per item above)\n- Residual risks (cardinality, cost, missing SLIs)" }, { "id": "secure-pr-review-guardrails", @@ -144,7 +144,7 @@ "devsecops" ], "formatNotes": "All three. Copilot Chat/agent prompt or `.github/skills/secure-pr-review/SKILL.md`. Claude Code skill with a keyword-rich description (PR review, secrets, authz). Codex: section in AGENTS.md titled Secure review, or invoke as a pasted checklist.", - "body": "# Skill: Secure Pull Request Review\n\n## Goal\nReview a pull request for security defects—secrets leakage, authn/authz gaps, injection classes, and supply-chain risk—before merge.\n\n## When to apply\n- Any PR touching auth, crypto, CI permissions, dependencies, or public endpoints\n- Pre-merge security gate when a human asks for a secure review\n- After dependency bumps or workflow changes\n\n## Review order\n1. **Secrets / credentials**: hardcoded keys, tokens, connection strings, private keys, `.env` committed, debug dumps.\n2. **Authn / authz**: missing checks, IDOR, privilege escalation, overly broad roles, trust of client-supplied identity.\n3. **Injection / XSS / SSRF**: unsanitized input to SQL/NoSQL/shell/HTML; open redirects; server-side fetches to user-controlled URLs.\n4. **Dependency / lockfile / supply chain**: unexpected lockfile churn, new postinstall scripts, unpinned Actions, suspicious publishers.\n5. **Dangerous CI permissions**: `write-all`, unchecked `pull_request_target`, secrets to untrusted forks, mutable Action tags.\n6. **Data exposure / logging**: PII in logs, verbose errors to clients, overly broad CORS, public buckets.\n\n## Required findings format\nFor each issue:\n- **Severity**: critical | high | medium | low | info\n- **Location**: `file:line` (or hunk)\n- **Exploit sketch**: one short paragraph on how it could be abused\n- **Fix**: concrete remediation\n\n## Pass criteria\n- No unresolved critical/high findings\n- Medium findings acknowledged with owner or follow-up issue\n- No real secrets pasted into chat or review comments\n\n## Constraints\n- Do not invent vulnerabilities without evidence in the diff or reachable code.\n- Do not paste real secrets into chat—reference redacted shapes only.\n- Stay inside the PR diff plus minimal necessary context files.\n\n## Output format\n- Verdict: approve with notes | request changes | block\n- Findings table (severity, location, sketch, fix)\n- Residual risks / out-of-scope notes" + "body": "# Skill: Secure Pull Request Review\n\n## Goal\nReview a pull request for security defects\u2014secrets leakage, authn/authz gaps, injection classes, and supply-chain risk\u2014before merge.\n\n## When to apply\n- Any PR touching auth, crypto, CI permissions, dependencies, or public endpoints\n- Pre-merge security gate when a human asks for a secure review\n- After dependency bumps or workflow changes\n\n## Review order\n1. **Secrets / credentials**: hardcoded keys, tokens, connection strings, private keys, `.env` committed, debug dumps.\n2. **Authn / authz**: missing checks, IDOR, privilege escalation, overly broad roles, trust of client-supplied identity.\n3. **Injection / XSS / SSRF**: unsanitized input to SQL/NoSQL/shell/HTML; open redirects; server-side fetches to user-controlled URLs.\n4. **Dependency / lockfile / supply chain**: unexpected lockfile churn, new postinstall scripts, unpinned Actions, suspicious publishers.\n5. **Dangerous CI permissions**: `write-all`, unchecked `pull_request_target`, secrets to untrusted forks, mutable Action tags.\n6. **Data exposure / logging**: PII in logs, verbose errors to clients, overly broad CORS, public buckets.\n\n## Required findings format\nFor each issue:\n- **Severity**: critical | high | medium | low | info\n- **Location**: `file:line` (or hunk)\n- **Exploit sketch**: one short paragraph on how it could be abused\n- **Fix**: concrete remediation\n\n## Pass criteria\n- No unresolved critical/high findings\n- Medium findings acknowledged with owner or follow-up issue\n- No real secrets pasted into chat or review comments\n\n## Constraints\n- Do not invent vulnerabilities without evidence in the diff or reachable code.\n- Do not paste real secrets into chat\u2014reference redacted shapes only.\n- Stay inside the PR diff plus minimal necessary context files.\n\n## Output format\n- Verdict: approve with notes | request changes | block\n- Findings table (severity, location, sketch, fix)\n- Residual risks / out-of-scope notes" }, { "id": "azure-bicep-iac-guardrails", @@ -161,7 +161,7 @@ "iac" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/bicep.instructions.md` with applyTo `**/*.{bicep,bicepparam}`. Claude Code: `.claude/skills/azure-bicep-guardrails/SKILL.md`. Codex: nested `infra/AGENTS.md` or root `AGENTS.md` Azure IaC section.", - "body": "# Skill: Azure Bicep IaC Guardrails\n\n## Goal\nProduce Bicep that is least-privilege, parameterized, and safe to review before Azure deployment.\n\n## When to apply\n- New or changed `.bicep` / `.bicepparam` modules\n- Reviews of infra PRs that touch resource IDs, RBAC, networking, or secrets\n\n## Rules\n1. Prefer modules with clear inputs/outputs; avoid giant monolithic main files when the repo already uses modules.\n2. Parameterize environment-specific values (names, SKUs, CIDRs); never hardcode subscription IDs or secrets in committed params.\n3. Use `@secure()` for secrets and Key Vault references where the pattern already exists; never echo secure params in outputs.\n4. Scope RBAC to the narrowest principal and role; prefer role assignments at resource/RG scope over subscription-wide.\n5. Explicitly set required tags used by the platform (owner, env, cost-center) when the repo already expects them.\n6. Prefer existing verified modules / patterns in-repo over inventing new resource types.\n7. For public endpoints: justify exposure; prefer private endpoints / VNet integration when sibling modules do.\n8. Keep API versions pinned and consistent with neighboring modules; do not float to latest without a reason.\n\n## Review checklist\n- What resources are created/updated/deleted?\n- Any wildcard `*` permissions or Owner assignments?\n- Are diagnostics / logging hooks aligned with existing modules?\n- Are dependsOn / existing resource references correct?\n- What is the rollback story if deploy fails mid-way?\n\n## Constraints\n- Do not invent tenant, subscription, or object IDs — use parameters or existing symbols.\n- Do not weaken network or RBAC controls \"just to make deploy work\".\n- Prefer what-if / validation commands the repo already documents.\n\n## Output format\n- Summary of modules/files touched\n- Bicep diffs ready to apply\n- Parameter changes (names only for secrets)\n- Validation commands (`az bicep build`, what-if, or repo scripts)\n- Residual risks" + "body": "# Skill: Azure Bicep IaC Guardrails\n\n## Goal\nProduce Bicep that is least-privilege, parameterized, and safe to review before Azure deployment.\n\n## When to apply\n- New or changed `.bicep` / `.bicepparam` modules\n- Reviews of infra PRs that touch resource IDs, RBAC, networking, or secrets\n\n## Rules\n1. Prefer modules with clear inputs/outputs; avoid giant monolithic main files when the repo already uses modules.\n2. Parameterize environment-specific values (names, SKUs, CIDRs); never hardcode subscription IDs or secrets in committed params.\n3. Use `@secure()` for secrets and Key Vault references where the pattern already exists; never echo secure params in outputs.\n4. Scope RBAC to the narrowest principal and role; prefer role assignments at resource/RG scope over subscription-wide.\n5. Explicitly set required tags used by the platform (owner, env, cost-center) when the repo already expects them.\n6. Prefer existing verified modules / patterns in-repo over inventing new resource types.\n7. For public endpoints: justify exposure; prefer private endpoints / VNet integration when sibling modules do.\n8. Keep API versions pinned and consistent with neighboring modules; do not float to latest without a reason.\n\n## Review checklist\n- What resources are created/updated/deleted?\n- Any wildcard `*` permissions or Owner assignments?\n- Are diagnostics / logging hooks aligned with existing modules?\n- Are dependsOn / existing resource references correct?\n- What is the rollback story if deploy fails mid-way?\n\n## Constraints\n- Do not invent tenant, subscription, or object IDs \u2014 use parameters or existing symbols.\n- Do not weaken network or RBAC controls \"just to make deploy work\".\n- Prefer what-if / validation commands the repo already documents.\n\n## Output format\n- Summary of modules/files touched\n- Bicep diffs ready to apply\n- Parameter changes (names only for secrets)\n- Validation commands (`az bicep build`, what-if, or repo scripts)\n- Residual risks" }, { "id": "container-image-hardening", @@ -179,12 +179,12 @@ "security" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/docker.instructions.md` with applyTo for `**/Dockerfile*`, `**/*Containerfile*`, `**/docker-compose*.{yml,yaml}`. Claude Code: `.claude/skills/container-image-hardening/SKILL.md` (YAML name + keyword-rich description). Codex: section in root or `deploy/AGENTS.md`, or `.agents/skills/container-image-hardening/SKILL.md`.", - "body": "# Skill: Container Image Hardening\n\n## Goal\nProduce lean, reproducible, least-privilege container images that are safe to run on AKS (or similar).\n\n## When to apply\n- New or changed Dockerfile / Containerfile / buildah scripts\n- Multi-stage builds, base-image upgrades, or image used by a Deployment\n\n## Hardening checklist (apply in order)\n1. **Pin bases**: digest-pin (`@sha256:…`) or immutable tags used by the platform; never `:latest` in production paths.\n2. **Multi-stage**: build in a fat stage; copy only runtime artifacts into a minimal final stage.\n3. **Non-root**: final USER is a non-root uid/gid; avoid running as root even if the orchestrator could override.\n4. **No secrets in layers**: never COPY `.env`, key files, or `npmrc` with tokens; use BuildKit secrets / runtime mounts.\n5. **Minimal attack surface**: no unused shells/package managers in the final image when feasible; drop build tools from runtime.\n6. **Health signal**: document the process model (PID 1, signal handling); prefer a dumb-init/tini only if the stack already uses it.\n7. **Metadata**: useful OCI labels (`org.opencontainers.image.*`) without leaking internal hostnames or personal data.\n8. **Supply chain**: generate or consume SBOM when the pipeline expects it; note image scan gate before promote.\n\n## Dockerfile patterns\n- Prefer `COPY --from=build` of exact paths over copying the whole build context into runtime.\n- Order layers for cache: dependency manifests before source.\n- `RUN` apt/apk with cleanup in the same layer; pin package versions when the repo already does.\n- Expose only required ports; do not bake environment-specific URLs into the image when config can be runtime.\n\n## Constraints\n- Do not invent private base images or registries that are not evidenced in-repo.\n- Do not weaken existing IMAGE signing / admission policy for convenience.\n- Keep local `docker build` / `buildx` commands accurate for this repo.\n\n## Output format\n- Patched Dockerfile(s) or clear unified diff\n- Table: control → status (pass/fail/n/a) → note\n- Suggested scan/SBOM commands matching repo CI\n- Residual risks (base CVEs, privileged bits, secret leakage)" + "body": "# Skill: Container Image Hardening\n\n## Goal\nProduce lean, reproducible, least-privilege container images that are safe to run on AKS (or similar).\n\n## When to apply\n- New or changed Dockerfile / Containerfile / buildah scripts\n- Multi-stage builds, base-image upgrades, or image used by a Deployment\n\n## Hardening checklist (apply in order)\n1. **Pin bases**: digest-pin (`@sha256:\u2026`) or immutable tags used by the platform; never `:latest` in production paths.\n2. **Multi-stage**: build in a fat stage; copy only runtime artifacts into a minimal final stage.\n3. **Non-root**: final USER is a non-root uid/gid; avoid running as root even if the orchestrator could override.\n4. **No secrets in layers**: never COPY `.env`, key files, or `npmrc` with tokens; use BuildKit secrets / runtime mounts.\n5. **Minimal attack surface**: no unused shells/package managers in the final image when feasible; drop build tools from runtime.\n6. **Health signal**: document the process model (PID 1, signal handling); prefer a dumb-init/tini only if the stack already uses it.\n7. **Metadata**: useful OCI labels (`org.opencontainers.image.*`) without leaking internal hostnames or personal data.\n8. **Supply chain**: generate or consume SBOM when the pipeline expects it; note image scan gate before promote.\n\n## Dockerfile patterns\n- Prefer `COPY --from=build` of exact paths over copying the whole build context into runtime.\n- Order layers for cache: dependency manifests before source.\n- `RUN` apt/apk with cleanup in the same layer; pin package versions when the repo already does.\n- Expose only required ports; do not bake environment-specific URLs into the image when config can be runtime.\n\n## Constraints\n- Do not invent private base images or registries that are not evidenced in-repo.\n- Do not weaken existing IMAGE signing / admission policy for convenience.\n- Keep local `docker build` / `buildx` commands accurate for this repo.\n\n## Output format\n- Patched Dockerfile(s) or clear unified diff\n- Table: control \u2192 status (pass/fail/n/a) \u2192 note\n- Suggested scan/SBOM commands matching repo CI\n- Residual risks (base CVEs, privileged bits, secret leakage)" }, { "id": "azure-key-vault-app-integration", "title": "Azure Key Vault App Integration", - "whenToUse": "Wiring an app or service to Azure Key Vault for secrets, certificates, or keys — or reviewing a PR that still embeds credentials.", + "whenToUse": "Wiring an app or service to Azure Key Vault for secrets, certificates, or keys \u2014 or reviewing a PR that still embeds credentials.", "tools": [ "copilot", "claude-code", @@ -197,12 +197,12 @@ "security" ], "formatNotes": "All three. Copilot: `.github/instructions/keyvault.instructions.md` with applyTo for `**/*.{java,cs,ts,js,yml,yaml,bicep,tf}` and `**/appsettings*.json`. Claude Code: `.claude/skills/azure-key-vault/SKILL.md`. Codex: section in root `AGENTS.md` or `docs/agents/key-vault.md` linked from AGENTS.md.", - "body": "# Skill: Azure Key Vault App Integration\n\n## Goal\nIntegrate applications with Azure Key Vault so secrets are fetched via identity, rotated safely, and never committed or logged.\n\n## When to apply\n- New or existing services that need DB passwords, API keys, certificates, or signing keys\n- Reviews that find secrets in config files, env samples committed with real values, or long-lived connection strings\n- Migrations from App Settings / Kubernetes secrets / `.env` files into Key Vault\n\n## Preferred patterns\n1. **Identity over keys**: prefer managed identity / workload identity to Key Vault; avoid embedding vault access keys or client secrets when identity is available.\n2. **Least privilege**: grant get/list only on the secrets the app needs; separate read vs admin principals.\n3. **Names and versions**: use stable secret names; pin to a version only when required for rollback, otherwise take the current version deliberately.\n4. **Caching**: cache secret values in-process with a short TTL and refresh on failure; do not dump full secret maps into logs.\n5. **Local/dev**: use user secrets, `.env` (gitignored), or a non-prod vault — never commit real values; document required secret *names* only.\n6. **Rotation**: design callers to tolerate rotation (reconnect pools, reload config) without redeploying for every rotate when the platform supports it.\n\n## Implementation steps\n1. Inventory secrets the change introduces or touches (name, owner, environments).\n2. Confirm vault and RBAC/access policy patterns already used in-repo; match them.\n3. Replace inline secret material with references (Key Vault reference, CSI driver, SDK getSecret, etc. as used by the stack).\n4. Ensure startup fails closed if required secrets are missing (clear error, no half-boot with empty credentials).\n5. Add or update tests/mocks so unit tests never need real vault credentials.\n6. Update runbooks: where secrets live, who can rotate, and how to verify after rotate.\n\n## Constraints\n- Do not print secret values, full connection strings, or private keys in logs, traces, or PR descriptions.\n- Do not weaken TLS or disable certificate validation to “make Key Vault work.”\n- Prefer platform-native Key Vault integration already in the repo over new SDKs or sidecar patterns.\n- Keep IaC changes aligned with existing modules (Bicep/Terraform/Helm) — no one-off portal-only grants in production paths.\n\n## Output format\n- Summary of secrets moved or referenced (names only)\n- Code/IaC/config diffs\n- Identity and RBAC changes required\n- Verification steps (app start, rotate drill, negative test for missing secret)\n- Residual risks (caching, dual-read during migration, break-glass)" + "body": "# Skill: Azure Key Vault App Integration\n\n## Goal\nIntegrate applications with Azure Key Vault so secrets are fetched via identity, rotated safely, and never committed or logged.\n\n## When to apply\n- New or existing services that need DB passwords, API keys, certificates, or signing keys\n- Reviews that find secrets in config files, env samples committed with real values, or long-lived connection strings\n- Migrations from App Settings / Kubernetes secrets / `.env` files into Key Vault\n\n## Preferred patterns\n1. **Identity over keys**: prefer managed identity / workload identity to Key Vault; avoid embedding vault access keys or client secrets when identity is available.\n2. **Least privilege**: grant get/list only on the secrets the app needs; separate read vs admin principals.\n3. **Names and versions**: use stable secret names; pin to a version only when required for rollback, otherwise take the current version deliberately.\n4. **Caching**: cache secret values in-process with a short TTL and refresh on failure; do not dump full secret maps into logs.\n5. **Local/dev**: use user secrets, `.env` (gitignored), or a non-prod vault \u2014 never commit real values; document required secret *names* only.\n6. **Rotation**: design callers to tolerate rotation (reconnect pools, reload config) without redeploying for every rotate when the platform supports it.\n\n## Implementation steps\n1. Inventory secrets the change introduces or touches (name, owner, environments).\n2. Confirm vault and RBAC/access policy patterns already used in-repo; match them.\n3. Replace inline secret material with references (Key Vault reference, CSI driver, SDK getSecret, etc. as used by the stack).\n4. Ensure startup fails closed if required secrets are missing (clear error, no half-boot with empty credentials).\n5. Add or update tests/mocks so unit tests never need real vault credentials.\n6. Update runbooks: where secrets live, who can rotate, and how to verify after rotate.\n\n## Constraints\n- Do not print secret values, full connection strings, or private keys in logs, traces, or PR descriptions.\n- Do not weaken TLS or disable certificate validation to \u201cmake Key Vault work.\u201d\n- Prefer platform-native Key Vault integration already in the repo over new SDKs or sidecar patterns.\n- Keep IaC changes aligned with existing modules (Bicep/Terraform/Helm) \u2014 no one-off portal-only grants in production paths.\n\n## Output format\n- Summary of secrets moved or referenced (names only)\n- Code/IaC/config diffs\n- Identity and RBAC changes required\n- Verification steps (app start, rotate drill, negative test for missing secret)\n- Residual risks (caching, dual-read during migration, break-glass)" }, { "id": "spring-boot-resilience4j", "title": "Spring Boot Resilience4j Guardrails", - "whenToUse": "Adding timeouts, retries, circuit breakers, or bulkheads to a Spring Boot service — or reviewing a PR that calls unreliable dependencies without resilience.", + "whenToUse": "Adding timeouts, retries, circuit breakers, or bulkheads to a Spring Boot service \u2014 or reviewing a PR that calls unreliable dependencies without resilience.", "tools": [ "copilot", "claude-code", @@ -215,7 +215,7 @@ "microservices" ], "formatNotes": "All three. Copilot: `.github/instructions/resilience.instructions.md` with applyTo for `**/*.{java,yml,yaml}` and Spring config. Claude Code: `.claude/skills/spring-resilience4j/SKILL.md`. Codex: section in root `AGENTS.md` or `docs/agents/resilience4j.md` linked from AGENTS.md.", - "body": "# Skill: Spring Boot Resilience4j Guardrails\n\n## Goal\nAdd timeouts, retries, circuit breakers, and bulkheads to Spring Boot 3 services so outbound calls fail predictably and recover safely.\n\n## When to apply\n- HTTP/DB/messaging clients without explicit resilience\n- PRs calling unreliable dependencies with only default timeouts\n- Hardening services that rely on ad-hoc try/catch\n\n## Preferred patterns\n1. **TimeLimiter** — bound every outbound call; prefer fail-fast over hanging threads.\n2. **Retry** — exponential backoff + jitter; only idempotent ops and transient faults (timeouts, 502/503/504), never business 4xx.\n3. **CircuitBreaker** — open on error-rate/slow-call thresholds; choose fail-fast vs fail-open explicitly.\n4. **Bulkhead / RateLimiter** — isolate concurrency so one dependency cannot starve the JVM.\n5. **YAML config** — named instances in `application.yml`; avoid magic defaults in code.\n6. **Metrics & health** — expose breaker state via Actuator/health already in-repo.\n\n## Implementation steps\n1. Inventory outbound calls; mark which are idempotent.\n2. Match existing Resilience4j / Spring Boot starter usage in-repo.\n3. Decorate with named `@TimeLimiter`, `@Retry`, `@CircuitBreaker`, `@Bulkhead` / `@RateLimiter`.\n4. Fallbacks return safe degraded responses or typed errors — never swallow exceptions.\n5. Wire YAML per instance; document fail-fast vs fail-open per dependency.\n6. Tests: open-circuit, retry exhaustion, fallback, no retries on non-idempotent calls.\n\n## Review checklist\n- End-to-end timeouts (client + resilience layer)\n- Retries gated on idempotency + transient errors only\n- CircuitBreaker thresholds and half-open behavior documented\n- Bulkhead/RateLimiter prevents thread-pool exhaustion\n- No silent catch-and-ignore; stable API/problem error mapping\n- Metrics/health visible; config in YAML not hardcoded literals\n\n## Done when\nNamed Resilience4j protection, YAML config, open-circuit/fallback tests, and a fail-fast vs fail-open note per dependency are in place." + "body": "# Skill: Spring Boot Resilience4j Guardrails\n\n## Goal\nAdd timeouts, retries, circuit breakers, and bulkheads to Spring Boot 3 services so outbound calls fail predictably and recover safely.\n\n## When to apply\n- HTTP/DB/messaging clients without explicit resilience\n- PRs calling unreliable dependencies with only default timeouts\n- Hardening services that rely on ad-hoc try/catch\n\n## Preferred patterns\n1. **TimeLimiter** \u2014 bound every outbound call; prefer fail-fast over hanging threads.\n2. **Retry** \u2014 exponential backoff + jitter; only idempotent ops and transient faults (timeouts, 502/503/504), never business 4xx.\n3. **CircuitBreaker** \u2014 open on error-rate/slow-call thresholds; choose fail-fast vs fail-open explicitly.\n4. **Bulkhead / RateLimiter** \u2014 isolate concurrency so one dependency cannot starve the JVM.\n5. **YAML config** \u2014 named instances in `application.yml`; avoid magic defaults in code.\n6. **Metrics & health** \u2014 expose breaker state via Actuator/health already in-repo.\n\n## Implementation steps\n1. Inventory outbound calls; mark which are idempotent.\n2. Match existing Resilience4j / Spring Boot starter usage in-repo.\n3. Decorate with named `@TimeLimiter`, `@Retry`, `@CircuitBreaker`, `@Bulkhead` / `@RateLimiter`.\n4. Fallbacks return safe degraded responses or typed errors \u2014 never swallow exceptions.\n5. Wire YAML per instance; document fail-fast vs fail-open per dependency.\n6. Tests: open-circuit, retry exhaustion, fallback, no retries on non-idempotent calls.\n\n## Review checklist\n- End-to-end timeouts (client + resilience layer)\n- Retries gated on idempotency + transient errors only\n- CircuitBreaker thresholds and half-open behavior documented\n- Bulkhead/RateLimiter prevents thread-pool exhaustion\n- No silent catch-and-ignore; stable API/problem error mapping\n- Metrics/health visible; config in YAML not hardcoded literals\n\n## Done when\nNamed Resilience4j protection, YAML config, open-circuit/fallback tests, and a fail-fast vs fail-open note per dependency are in place." }, { "id": "helm-chart-aks-guardrails", @@ -233,7 +233,7 @@ "kubernetes" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/helm.instructions.md` with applyTo for `**/charts/**`, `**/helm/**`, `**/values*.yaml`. Claude Code: `.claude/skills/helm-aks-guardrails/SKILL.md`. Codex: `deploy/AGENTS.md` or root `AGENTS.md` section titled Helm/AKS.", - "body": "# Skill: Helm Chart Guardrails for AKS\n\n## Goal\nProduce Helm charts that render secure, operable workloads on Azure AKS and are reviewable in PR.\n\n## When to apply\n- New or changed chart templates, helpers, values.yaml, values.schema.json\n- Chart bumps that touch ServiceAccount, RBAC, Ingress, probes, or secrets\n\n## Chart structure rules\n1. Keep templates DRY via `_helpers.tpl`; name resources with the chart fullname helper.\n2. Prefer `values.schema.json` for required keys and safe defaults; document every public value.\n3. Defaults must be production-safe (ClusterIP, non-root, resources set); loosen only in env overlays.\n4. Pin image repository + tag (or digest); never default to `latest`.\n5. Separate chart config from secrets: no raw credentials in values committed to git.\n\n## Security and operability checklist\n1. **Pod/container securityContext**: runAsNonRoot, allowPrivilegeEscalation false, drop ALL capabilities, readOnlyRootFilesystem when feasible, seccomp RuntimeDefault when the platform supports it.\n2. **Resources**: requests and limits on every container; note intentional burstable cases.\n3. **Probes**: readiness + liveness (startup when slow); avoid identical probes that hide failures.\n4. **Identity/secrets on AKS**: prefer Workload Identity + Key Vault CSI / external secrets over long-lived kube secrets in values.\n5. **RBAC**: least-privilege Role/RoleBinding; no ClusterRole unless justified and documented.\n6. **Networking**: configurable Service type (default ClusterIP); NetworkPolicy templates optional but default-deny when the chart ships policies.\n7. **Rollouts**: sensible rollingUpdate; PodDisruptionBudget for user-facing services; checksum annotations for ConfigMap/Secret changes that should restart pods.\n\n## Validation steps\n1. `helm lint` on the chart.\n2. `helm template` for at least two value overlays (e.g. base + prod-like).\n3. Dry-run apply or kubeconform/kubeval if the repo already uses them.\n4. Confirm rendered manifests match in-repo AKS conventions (ingress class, labels, identity annotations).\n\n## Constraints\n- Do not invent cluster operators/CRDs not evidenced in-repo.\n- Do not hardcode subscription, tenant, or Key Vault URIs — parameterize.\n- Keep NOTES.txt accurate and free of secrets.\n\n## Output format\n- Files touched + why\n- Key values additions (names + purpose)\n- Rendered-manifest highlights or patches\n- Commands run / to run\n- Residual risks (RBAC breadth, secret path, ingress exposure)" + "body": "# Skill: Helm Chart Guardrails for AKS\n\n## Goal\nProduce Helm charts that render secure, operable workloads on Azure AKS and are reviewable in PR.\n\n## When to apply\n- New or changed chart templates, helpers, values.yaml, values.schema.json\n- Chart bumps that touch ServiceAccount, RBAC, Ingress, probes, or secrets\n\n## Chart structure rules\n1. Keep templates DRY via `_helpers.tpl`; name resources with the chart fullname helper.\n2. Prefer `values.schema.json` for required keys and safe defaults; document every public value.\n3. Defaults must be production-safe (ClusterIP, non-root, resources set); loosen only in env overlays.\n4. Pin image repository + tag (or digest); never default to `latest`.\n5. Separate chart config from secrets: no raw credentials in values committed to git.\n\n## Security and operability checklist\n1. **Pod/container securityContext**: runAsNonRoot, allowPrivilegeEscalation false, drop ALL capabilities, readOnlyRootFilesystem when feasible, seccomp RuntimeDefault when the platform supports it.\n2. **Resources**: requests and limits on every container; note intentional burstable cases.\n3. **Probes**: readiness + liveness (startup when slow); avoid identical probes that hide failures.\n4. **Identity/secrets on AKS**: prefer Workload Identity + Key Vault CSI / external secrets over long-lived kube secrets in values.\n5. **RBAC**: least-privilege Role/RoleBinding; no ClusterRole unless justified and documented.\n6. **Networking**: configurable Service type (default ClusterIP); NetworkPolicy templates optional but default-deny when the chart ships policies.\n7. **Rollouts**: sensible rollingUpdate; PodDisruptionBudget for user-facing services; checksum annotations for ConfigMap/Secret changes that should restart pods.\n\n## Validation steps\n1. `helm lint` on the chart.\n2. `helm template` for at least two value overlays (e.g. base + prod-like).\n3. Dry-run apply or kubeconform/kubeval if the repo already uses them.\n4. Confirm rendered manifests match in-repo AKS conventions (ingress class, labels, identity annotations).\n\n## Constraints\n- Do not invent cluster operators/CRDs not evidenced in-repo.\n- Do not hardcode subscription, tenant, or Key Vault URIs \u2014 parameterize.\n- Keep NOTES.txt accurate and free of secrets.\n\n## Output format\n- Files touched + why\n- Key values additions (names + purpose)\n- Rendered-manifest highlights or patches\n- Commands run / to run\n- Residual risks (RBAC breadth, secret path, ingress exposure)" }, { "id": "aks-networkpolicy-zero-trust", @@ -252,7 +252,7 @@ "security" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/networkpolicy.instructions.md` with applyTo for `**/networkpolicy/**`, `**/*network*policy*.yaml`, `**/cilium/**`. Claude Code: `.claude/skills/aks-networkpolicy-zero-trust/SKILL.md`. Codex: nested `deploy/AGENTS.md` or a NetworkPolicy section in root `AGENTS.md`.", - "body": "# Skill: AKS NetworkPolicy Zero-Trust Guardrails\n\n## Goal\nShip namespace-scoped network policies that enforce default-deny east-west traffic on Azure AKS, with explicit allow paths that are reviewable in PR.\n\n## When to apply\n- New or changed NetworkPolicy / CiliumNetworkPolicy manifests\n- Service extractions that introduce new pod-to-pod or egress paths\n- Chart or Kustomize overlays that touch networking for AKS\n\n## Baseline posture\n1. Assume the cluster starts open: unrestricted pod-to-pod until a selecting policy exists.\n2. Prefer **default deny** per application namespace for both Ingress and Egress (or Ingress-first if egress is staged).\n3. Prefer standard `networking.k8s.io/v1` NetworkPolicy when it covers the need; use Cilium CRDs only when the cluster clearly runs Azure CNI Powered by Cilium (or Calico) and L7/FQDN features are required and supported.\n4. Never invent a CNI or policy engine not evidenced in-repo or in the cluster notes.\n\n## Policy authoring rules\n1. **Selectors first**: every allow rule names concrete `podSelector` / `namespaceSelector` labels that already exist on workloads.\n2. **Ports + protocols**: pin TCP/UDP ports; avoid open port ranges unless justified.\n3. **Cross-namespace**: include namespace identity explicitly (label selectors), never rely on “same cluster = trusted”.\n4. **DNS on egress deny**: if egress is default-deny, allow kube-dns / CoreDNS (usually UDP/TCP 53) before anything else, or apps break silently.\n5. **Probes and system paths**: account for kubelet probes and required platform agents; do not blanket-allow node CIDRs unless the platform docs require it and `ipBlock` is valid for the CNI (Azure CNI Cilium has `ipBlock` limitations for pod/node IPs — prefer selectors).\n6. **Ingress controllers / mesh**: allow only the ingress or mesh identity that terminates traffic; document TLS termination assumptions.\n7. **Egress to Azure PaaS**: prefer private endpoints / service tags documented in-repo; do not hardcode subscription-specific IPs in policies without a values/overlay escape hatch.\n\n## Structure and naming\n1. One default-deny object per namespace; separate allow policies per intent (`allow-frontend-to-api`, `allow-api-to-redis`).\n2. Stable metadata names; label policies with app/component for grep and policy inventory.\n3. Keep examples under `deploy/`, `k8s/`, or chart templates consistent with existing layout.\n\n## Validation steps\n1. `kubectl apply --dry-run=server` (or kubeconform) on the manifests.\n2. Describe expected flows in the PR: source → destination:port for each allow.\n3. After apply in a non-prod namespace: confirm deny (blocked path) and allow (happy path) with a short curl/nc from a debug pod.\n4. If Cilium: check endpoint enforcement / Hubble flows when those tools are already in the cluster.\n\n## Constraints\n- Do not weaken default-deny with broad `ipBlock: 0.0.0.0/0` “temporary” allows.\n- Do not put secrets, connection strings, or environment-specific hostnames into policy comments that will rot.\n- Parameterize environment differences via Kustomize/Helm values, not copy-pasted YAML forks.\n\n## Output format\n- Files touched + why\n- Flow table (src → dst:port / direction)\n- Default-deny coverage (ingress/egress, namespaces)\n- Residual risks (DNS, probes, ingress identity, CNI limits)\n- Commands run / to run\n" + "body": "# Skill: AKS NetworkPolicy Zero-Trust Guardrails\n\n## Goal\nShip namespace-scoped network policies that enforce default-deny east-west traffic on Azure AKS, with explicit allow paths that are reviewable in PR.\n\n## When to apply\n- New or changed NetworkPolicy / CiliumNetworkPolicy manifests\n- Service extractions that introduce new pod-to-pod or egress paths\n- Chart or Kustomize overlays that touch networking for AKS\n\n## Baseline posture\n1. Assume the cluster starts open: unrestricted pod-to-pod until a selecting policy exists.\n2. Prefer **default deny** per application namespace for both Ingress and Egress (or Ingress-first if egress is staged).\n3. Prefer standard `networking.k8s.io/v1` NetworkPolicy when it covers the need; use Cilium CRDs only when the cluster clearly runs Azure CNI Powered by Cilium (or Calico) and L7/FQDN features are required and supported.\n4. Never invent a CNI or policy engine not evidenced in-repo or in the cluster notes.\n\n## Policy authoring rules\n1. **Selectors first**: every allow rule names concrete `podSelector` / `namespaceSelector` labels that already exist on workloads.\n2. **Ports + protocols**: pin TCP/UDP ports; avoid open port ranges unless justified.\n3. **Cross-namespace**: include namespace identity explicitly (label selectors), never rely on \u201csame cluster = trusted\u201d.\n4. **DNS on egress deny**: if egress is default-deny, allow kube-dns / CoreDNS (usually UDP/TCP 53) before anything else, or apps break silently.\n5. **Probes and system paths**: account for kubelet probes and required platform agents; do not blanket-allow node CIDRs unless the platform docs require it and `ipBlock` is valid for the CNI (Azure CNI Cilium has `ipBlock` limitations for pod/node IPs \u2014 prefer selectors).\n6. **Ingress controllers / mesh**: allow only the ingress or mesh identity that terminates traffic; document TLS termination assumptions.\n7. **Egress to Azure PaaS**: prefer private endpoints / service tags documented in-repo; do not hardcode subscription-specific IPs in policies without a values/overlay escape hatch.\n\n## Structure and naming\n1. One default-deny object per namespace; separate allow policies per intent (`allow-frontend-to-api`, `allow-api-to-redis`).\n2. Stable metadata names; label policies with app/component for grep and policy inventory.\n3. Keep examples under `deploy/`, `k8s/`, or chart templates consistent with existing layout.\n\n## Validation steps\n1. `kubectl apply --dry-run=server` (or kubeconform) on the manifests.\n2. Describe expected flows in the PR: source \u2192 destination:port for each allow.\n3. After apply in a non-prod namespace: confirm deny (blocked path) and allow (happy path) with a short curl/nc from a debug pod.\n4. If Cilium: check endpoint enforcement / Hubble flows when those tools are already in the cluster.\n\n## Constraints\n- Do not weaken default-deny with broad `ipBlock: 0.0.0.0/0` \u201ctemporary\u201d allows.\n- Do not put secrets, connection strings, or environment-specific hostnames into policy comments that will rot.\n- Parameterize environment differences via Kustomize/Helm values, not copy-pasted YAML forks.\n\n## Output format\n- Files touched + why\n- Flow table (src \u2192 dst:port / direction)\n- Default-deny coverage (ingress/egress, namespaces)\n- Residual risks (DNS, probes, ingress identity, CNI limits)\n- Commands run / to run\n" }, { "id": "aks-workload-identity-guardrails", @@ -272,7 +272,7 @@ "identity" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/aks-workload-identity.instructions.md` with applyTo for `**/deploy/**`, `**/k8s/**`, `**/*.{yml,yaml,bicep,tf}`, `**/serviceaccount*.yaml`, and app credential wiring files. Claude Code: `.claude/skills/aks-workload-identity-guardrails/SKILL.md` (plus a short CLAUDE.md fact that WI is preferred over pod secrets / aadpodidentity). Codex: nested `deploy/AGENTS.md` or an Identity section in root `AGENTS.md`.", - "body": "# Skill: AKS Workload Identity Guardrails\n\n## Goal\nGive every AKS workload a federated identity path: a Kubernetes ServiceAccount mapped to a user-assigned managed identity via Azure Workload Identity, so apps obtain Azure tokens without client secrets in the cluster.\n\n## When to apply\n- New AKS deployments that call Azure AD–protected resources (Key Vault, Storage, Event Hubs, ACR pull via MI, Azure SQL, etc.)\n- Migrations off client secrets, SP passwords, or connection strings stored as Kubernetes Secrets\n- Replacing legacy Azure AD Pod Identity (`aadpodidentity`, AzureIdentity / AzureIdentityBinding)\n- Reviews of Helm/Kustomize that still inject `AZURE_CLIENT_SECRET` or similar\n\n## Baseline rules\n1. **Prefer Workload Identity** (OIDC federation on the AKS cluster + user-assigned MI) over secrets and over AAD Pod Identity.\n2. **One identity intent per workload** (or tightly related set): map ServiceAccount → user-assigned MI; avoid a shared “cluster MI” for unrelated apps.\n3. **Least privilege RBAC** on the MI: grant only the Azure roles/data-plane permissions the app needs on specific resource scopes (RG/resource), never Owner/Contributor at subscription by default.\n4. **Namespace labels**: ensure the namespace opted into WI (`azure.workload.identity/use: \"true\"` on the namespace, per current AKS WI docs your platform follows).\n5. **ServiceAccount**: annotate with client id (and tenant if required by your platform pattern):\n - `azure.workload.identity/client-id: `\n - Optional audience / tenant annotations only when your platform standard requires them.\n6. **Pod**: use that ServiceAccount; label pods that participate with `azure.workload.identity/use: \"true\"` when required by the WI mutating webhook in your cluster version.\n7. **Federated credential** on the user-assigned MI must match the issuer of the AKS OIDC issuer and the subject `system:serviceaccount::` (exact SA name and namespace — typos break auth silently).\n8. **App code**: use Azure Identity SDK `DefaultAzureCredential` / equivalent chain that picks up the WI-injected env (`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_FEDERATED_TOKEN_FILE`). Do not hardcode secrets “for local only” into the same Deployment env.\n9. **Key Vault**: prefer CSI Secrets Store with WI, or SDK access with the same MI — do not sync long-lived secret values into etcd if CSI + SDK can avoid it.\n10. **Local / CI fallback**: document Azure CLI / env credential / user auth for laptop and pipeline; keep that path out of the in-cluster Deployment manifest.\n\n## Structure\n1. Infra (Bicep/Terraform/az): user-assigned MI + federated identity credential bound to SA subject + OIDC issuer.\n2. Cluster: WI addon / OIDC issuer enabled (do not invent enablement steps if the platform repo already owns cluster bootstrap).\n3. App manifests: Namespace label → ServiceAccount (annotated) → Deployment/StatefulSet `serviceAccountName` + WI use label → no client-secret env vars.\n4. Azure RBAC assignments scoped to the resources the app actually calls.\n5. README or runbook: how to rotate by swapping MI / federated credential, and how to validate token acquisition.\n\n## Validation\n1. Confirm OIDC issuer URL on the cluster matches the federated credential issuer.\n2. Confirm SA name/namespace in the federated credential subject equal the live ServiceAccount.\n3. From a debug shell in the pod (non-prod): check projected token file exists and Azure SDK / `az login --federated-token` (or equivalent) can obtain an access token for a known resource.\n4. Negative test: wrong SA or missing annotation fails closed (no silent fallback to a shared secret).\n5. PR checklist: no `AZURE_CLIENT_SECRET`, no SP password in Secrets, no `aadpodidbinding` / AzureIdentityBinding leftovers for this app.\n\n## Anti-patterns\n- Storing Azure client secrets or SP passwords in Kubernetes Secrets “temporarily”\n- Re-introducing Azure AD Pod Identity CRDs for new work\n- One shared MI with broad Contributor for every namespace\n- Hardcoding subscription-specific client IDs in app code instead of SA annotation / chart values\n- Mounting the federated token path world-readable or logging token contents\n- Leaving both WI and a client-secret env var so the SDK prefers the secret path\n- Copying federated credential subjects across environments without updating namespace/SA\n\n## Output format\n- Identity map: namespace / SA / UAMI client id / federated subject / Azure roles\n- Manifest and IaC files touched\n- Secrets / aadpodidentity objects to delete\n- Validation commands and residual risks (local-dev, CSI vs SDK, privileged roles)\n" + "body": "# Skill: AKS Workload Identity Guardrails\n\n## Goal\nGive every AKS workload a federated identity path: a Kubernetes ServiceAccount mapped to a user-assigned managed identity via Azure Workload Identity, so apps obtain Azure tokens without client secrets in the cluster.\n\n## When to apply\n- New AKS deployments that call Azure AD\u2013protected resources (Key Vault, Storage, Event Hubs, ACR pull via MI, Azure SQL, etc.)\n- Migrations off client secrets, SP passwords, or connection strings stored as Kubernetes Secrets\n- Replacing legacy Azure AD Pod Identity (`aadpodidentity`, AzureIdentity / AzureIdentityBinding)\n- Reviews of Helm/Kustomize that still inject `AZURE_CLIENT_SECRET` or similar\n\n## Baseline rules\n1. **Prefer Workload Identity** (OIDC federation on the AKS cluster + user-assigned MI) over secrets and over AAD Pod Identity.\n2. **One identity intent per workload** (or tightly related set): map ServiceAccount \u2192 user-assigned MI; avoid a shared \u201ccluster MI\u201d for unrelated apps.\n3. **Least privilege RBAC** on the MI: grant only the Azure roles/data-plane permissions the app needs on specific resource scopes (RG/resource), never Owner/Contributor at subscription by default.\n4. **Namespace labels**: ensure the namespace opted into WI (`azure.workload.identity/use: \"true\"` on the namespace, per current AKS WI docs your platform follows).\n5. **ServiceAccount**: annotate with client id (and tenant if required by your platform pattern):\n - `azure.workload.identity/client-id: `\n - Optional audience / tenant annotations only when your platform standard requires them.\n6. **Pod**: use that ServiceAccount; label pods that participate with `azure.workload.identity/use: \"true\"` when required by the WI mutating webhook in your cluster version.\n7. **Federated credential** on the user-assigned MI must match the issuer of the AKS OIDC issuer and the subject `system:serviceaccount::` (exact SA name and namespace \u2014 typos break auth silently).\n8. **App code**: use Azure Identity SDK `DefaultAzureCredential` / equivalent chain that picks up the WI-injected env (`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_FEDERATED_TOKEN_FILE`). Do not hardcode secrets \u201cfor local only\u201d into the same Deployment env.\n9. **Key Vault**: prefer CSI Secrets Store with WI, or SDK access with the same MI \u2014 do not sync long-lived secret values into etcd if CSI + SDK can avoid it.\n10. **Local / CI fallback**: document Azure CLI / env credential / user auth for laptop and pipeline; keep that path out of the in-cluster Deployment manifest.\n\n## Structure\n1. Infra (Bicep/Terraform/az): user-assigned MI + federated identity credential bound to SA subject + OIDC issuer.\n2. Cluster: WI addon / OIDC issuer enabled (do not invent enablement steps if the platform repo already owns cluster bootstrap).\n3. App manifests: Namespace label \u2192 ServiceAccount (annotated) \u2192 Deployment/StatefulSet `serviceAccountName` + WI use label \u2192 no client-secret env vars.\n4. Azure RBAC assignments scoped to the resources the app actually calls.\n5. README or runbook: how to rotate by swapping MI / federated credential, and how to validate token acquisition.\n\n## Validation\n1. Confirm OIDC issuer URL on the cluster matches the federated credential issuer.\n2. Confirm SA name/namespace in the federated credential subject equal the live ServiceAccount.\n3. From a debug shell in the pod (non-prod): check projected token file exists and Azure SDK / `az login --federated-token` (or equivalent) can obtain an access token for a known resource.\n4. Negative test: wrong SA or missing annotation fails closed (no silent fallback to a shared secret).\n5. PR checklist: no `AZURE_CLIENT_SECRET`, no SP password in Secrets, no `aadpodidbinding` / AzureIdentityBinding leftovers for this app.\n\n## Anti-patterns\n- Storing Azure client secrets or SP passwords in Kubernetes Secrets \u201ctemporarily\u201d\n- Re-introducing Azure AD Pod Identity CRDs for new work\n- One shared MI with broad Contributor for every namespace\n- Hardcoding subscription-specific client IDs in app code instead of SA annotation / chart values\n- Mounting the federated token path world-readable or logging token contents\n- Leaving both WI and a client-secret env var so the SDK prefers the secret path\n- Copying federated credential subjects across environments without updating namespace/SA\n\n## Output format\n- Identity map: namespace / SA / UAMI client id / federated subject / Azure roles\n- Manifest and IaC files touched\n- Secrets / aadpodidentity objects to delete\n- Validation commands and residual risks (local-dev, CSI vs SDK, privileged roles)\n" }, { "id": "spring-boot-actuator-hardening", @@ -290,7 +290,7 @@ "security" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-boot-actuator-hardening.instructions.md` with applyTo for `**/application*.{yml,yaml,properties}`, `**/Management*Config*.java`, `**/Security*Config*.java`, and `**/actuator/**`. Claude Code: `.claude/skills/spring-boot-actuator-hardening/SKILL.md` (plus a short CLAUDE.md fact that Actuator must not expose env/heapdump/shutdown publicly). Codex: an Actuator / management endpoints section in root `AGENTS.md` or nested `src/main/AGENTS.md`.", - "body": "# Skill: Spring Boot Actuator Hardening\n\n## Goal\nKeep Spring Boot Actuator useful for ops (liveness/readiness, basic info, authenticated metrics) while preventing public or unauthenticated exposure of sensitive management endpoints that leak config, memory, threads, or cloud metadata.\n\n## When to apply\n- New Spring Boot 2.x/3.x services enabling `spring-boot-starter-actuator`\n- Reviews of `management.endpoints.*` / `management.server.*` before production\n- Kubernetes Deployments where probes hit `/actuator/health` (or a custom base-path)\n- Apps that scrape Micrometer/Prometheus metrics or attach continuous profilers\n- Any change that widens `include=*` exposure or moves Actuator onto the public port\n\n## Baseline rules\n1. **Expose only what ops needs.** Prefer `health` and `info` (and `prometheus`/`metrics` only if scrape auth is in place). Never ship `include=*` in production.\n2. **Never expose publicly:** `env`, `heapdump`, `threaddump`, `logfile`, `shutdown`, `configprops`, `beans`, `mappings`, `conditions`, `httptrace`/`httpexchanges`, and similar high-sensitivity endpoints — even \"temporarily\".\n3. **Separate management port when the app has a public HTTP surface.** Use `management.server.port` (and optionally `management.server.address`) so probes/scrapes do not share the user-facing listener. Document the port in Deployment/Service manifests.\n4. **Same-port pitfalls.** If Actuator stays on the app port, treat every exposed path as internet-facing unless a gateway/ingress explicitly blocks `/actuator/**` (or your `management.endpoints.web.base-path`). Prefer deny-by-default at the edge plus app-level auth.\n5. **Spring Boot 3 exposure knobs.** Use `management.endpoints.web.exposure.include` / `.exclude` explicitly; set `management.endpoints.web.base-path` deliberately (default `/actuator`). Do not rely on framework defaults differing across Boot 2→3 upgrades.\n6. **Health details.** Keep `management.endpoint.health.show-details` and `show-components` at `never` for anonymous callers; use `when_authorized` only when Spring Security roles for operators are real and tested.\n7. **Secure sensitive endpoints with Spring Security.** Anything beyond anonymous health/info must require authentication (HTTP basic for scrapers only over mTLS/private network, or OAuth2/JWT roles for humans). Map Actuator under a dedicated `SecurityFilterChain` with `EndpointRequest.to(...)` / `toAnyEndpoint()` rather than ad-hoc path matchers alone.\n8. **Kubernetes probes vs public routes.** Point `livenessProbe`/`readinessProbe` at the management port (or an edge-blocked path). Do not publish the management Service/port on a public LoadBalancer/Ingress. Use a ClusterIP + NetworkPolicy when scrapers live in-cluster.\n9. **Metrics / Pyroscope / profiler scrape auth.** Prometheus scrapes and continuous profiling agents must authenticate or run on a private network path. Do not leave `/actuator/prometheus` or profiler ports open on the public Service. Prefer scrape configs with bearer tokens or mTLS; document the contract in the chart/values.\n10. **CSRF for browser-facing management.** If Actuator is reachable from a browser session (same-site cookies), keep CSRF protection enabled for state-changing endpoint POSTs (e.g. `shutdown`). Machine scrapers should use non-browser auth that is CSRF-exempt by design — do not disable CSRF globally to \"fix\" Actuator.\n11. **Cloud metadata leakage.** The `env` endpoint and over-broad `info` contributors can surface container/cloud metadata, K8s service account paths, and secret-backed env vars. Keep `env` off the exposure list; scrub custom `info` contributors; never mirror `AWS_*/AZURE_*/GCP_*` or mounted token paths into public payloads.\n12. **Shutdown and write endpoints.** Disable or tightly role-gate `shutdown` and any custom write-capable endpoints. Production should not allow remote process death via HTTP without break-glass controls.\n\n## Structure\n1. Dependencies: `spring-boot-starter-actuator` (+ Security, Micrometer registry only as needed).\n2. Config: `application.yml` / profile-specific files with explicit exposure, base-path, health show-details, and optional `management.server.port`.\n3. Security: dedicated `SecurityFilterChain` for management (`EndpointRequest`), separate from the API chain when useful.\n4. Platform: Deployment probes → management port; Service/Ingress must not publish management publicly; scrape auth documented.\n5. Docs/runbook: which endpoints exist, who may call them, and how to verify from inside the cluster.\n\n## Validation\n1. Hit public base URL: `/actuator` (or custom base-path) should not list sensitive links anonymously; unauthenticated `env`/`heapdump`/`threaddump`/`shutdown` → 401/404/403.\n2. Probes succeed against the intended health path on the management port (or private path).\n3. With an operator credential: `health` details appear only when `when_authorized` is configured and the principal has the expected role.\n4. Confirm scrape job works with auth and fails closed without credentials.\n5. Grep config for `include: \"*\"`, `show-details: always`, and exposed `env`/`heapdump`/`shutdown` before merge.\n6. PR checklist: management port (if used) not on public Ingress; no secret values in `info`; CSRF not globally disabled for browser sessions.\n\n## Anti-patterns\n- `management.endpoints.web.exposure.include: \"*\"` in any shared or prod profile\n- `show-details: always` on publicly reachable health\n- Actuator on the public port with no Security filter and no ingress deny\n- Publishing management port via public LoadBalancer \"for convenience\"\n- Leaving `env` enabled so cloud metadata and secret-backed variables leak\n- Disabling CSRF application-wide so `shutdown` works from a browser\n- Relying only on \"security through obscure base-path\" (`/secret-actuator`)\n- Copying local-dev `include=*` settings into the default/prod profile\n\n## Output format\n- Exposure matrix: endpoint → anonymous / authenticated role / disabled\n- Config + `SecurityFilterChain` diffs (and management port if introduced)\n- Probe / Service / Ingress patches\n- Validation commands (curl from inside vs outside the cluster) and residual risks\n" + "body": "# Skill: Spring Boot Actuator Hardening\n\n## Goal\nKeep Spring Boot Actuator useful for ops (liveness/readiness, basic info, authenticated metrics) while preventing public or unauthenticated exposure of sensitive management endpoints that leak config, memory, threads, or cloud metadata.\n\n## When to apply\n- New Spring Boot 2.x/3.x services enabling `spring-boot-starter-actuator`\n- Reviews of `management.endpoints.*` / `management.server.*` before production\n- Kubernetes Deployments where probes hit `/actuator/health` (or a custom base-path)\n- Apps that scrape Micrometer/Prometheus metrics or attach continuous profilers\n- Any change that widens `include=*` exposure or moves Actuator onto the public port\n\n## Baseline rules\n1. **Expose only what ops needs.** Prefer `health` and `info` (and `prometheus`/`metrics` only if scrape auth is in place). Never ship `include=*` in production.\n2. **Never expose publicly:** `env`, `heapdump`, `threaddump`, `logfile`, `shutdown`, `configprops`, `beans`, `mappings`, `conditions`, `httptrace`/`httpexchanges`, and similar high-sensitivity endpoints \u2014 even \"temporarily\".\n3. **Separate management port when the app has a public HTTP surface.** Use `management.server.port` (and optionally `management.server.address`) so probes/scrapes do not share the user-facing listener. Document the port in Deployment/Service manifests.\n4. **Same-port pitfalls.** If Actuator stays on the app port, treat every exposed path as internet-facing unless a gateway/ingress explicitly blocks `/actuator/**` (or your `management.endpoints.web.base-path`). Prefer deny-by-default at the edge plus app-level auth.\n5. **Spring Boot 3 exposure knobs.** Use `management.endpoints.web.exposure.include` / `.exclude` explicitly; set `management.endpoints.web.base-path` deliberately (default `/actuator`). Do not rely on framework defaults differing across Boot 2\u21923 upgrades.\n6. **Health details.** Keep `management.endpoint.health.show-details` and `show-components` at `never` for anonymous callers; use `when_authorized` only when Spring Security roles for operators are real and tested.\n7. **Secure sensitive endpoints with Spring Security.** Anything beyond anonymous health/info must require authentication (HTTP basic for scrapers only over mTLS/private network, or OAuth2/JWT roles for humans). Map Actuator under a dedicated `SecurityFilterChain` with `EndpointRequest.to(...)` / `toAnyEndpoint()` rather than ad-hoc path matchers alone.\n8. **Kubernetes probes vs public routes.** Point `livenessProbe`/`readinessProbe` at the management port (or an edge-blocked path). Do not publish the management Service/port on a public LoadBalancer/Ingress. Use a ClusterIP + NetworkPolicy when scrapers live in-cluster.\n9. **Metrics / Pyroscope / profiler scrape auth.** Prometheus scrapes and continuous profiling agents must authenticate or run on a private network path. Do not leave `/actuator/prometheus` or profiler ports open on the public Service. Prefer scrape configs with bearer tokens or mTLS; document the contract in the chart/values.\n10. **CSRF for browser-facing management.** If Actuator is reachable from a browser session (same-site cookies), keep CSRF protection enabled for state-changing endpoint POSTs (e.g. `shutdown`). Machine scrapers should use non-browser auth that is CSRF-exempt by design \u2014 do not disable CSRF globally to \"fix\" Actuator.\n11. **Cloud metadata leakage.** The `env` endpoint and over-broad `info` contributors can surface container/cloud metadata, K8s service account paths, and secret-backed env vars. Keep `env` off the exposure list; scrub custom `info` contributors; never mirror `AWS_*/AZURE_*/GCP_*` or mounted token paths into public payloads.\n12. **Shutdown and write endpoints.** Disable or tightly role-gate `shutdown` and any custom write-capable endpoints. Production should not allow remote process death via HTTP without break-glass controls.\n\n## Structure\n1. Dependencies: `spring-boot-starter-actuator` (+ Security, Micrometer registry only as needed).\n2. Config: `application.yml` / profile-specific files with explicit exposure, base-path, health show-details, and optional `management.server.port`.\n3. Security: dedicated `SecurityFilterChain` for management (`EndpointRequest`), separate from the API chain when useful.\n4. Platform: Deployment probes \u2192 management port; Service/Ingress must not publish management publicly; scrape auth documented.\n5. Docs/runbook: which endpoints exist, who may call them, and how to verify from inside the cluster.\n\n## Validation\n1. Hit public base URL: `/actuator` (or custom base-path) should not list sensitive links anonymously; unauthenticated `env`/`heapdump`/`threaddump`/`shutdown` \u2192 401/404/403.\n2. Probes succeed against the intended health path on the management port (or private path).\n3. With an operator credential: `health` details appear only when `when_authorized` is configured and the principal has the expected role.\n4. Confirm scrape job works with auth and fails closed without credentials.\n5. Grep config for `include: \"*\"`, `show-details: always`, and exposed `env`/`heapdump`/`shutdown` before merge.\n6. PR checklist: management port (if used) not on public Ingress; no secret values in `info`; CSRF not globally disabled for browser sessions.\n\n## Anti-patterns\n- `management.endpoints.web.exposure.include: \"*\"` in any shared or prod profile\n- `show-details: always` on publicly reachable health\n- Actuator on the public port with no Security filter and no ingress deny\n- Publishing management port via public LoadBalancer \"for convenience\"\n- Leaving `env` enabled so cloud metadata and secret-backed variables leak\n- Disabling CSRF application-wide so `shutdown` works from a browser\n- Relying only on \"security through obscure base-path\" (`/secret-actuator`)\n- Copying local-dev `include=*` settings into the default/prod profile\n\n## Output format\n- Exposure matrix: endpoint \u2192 anonymous / authenticated role / disabled\n- Config + `SecurityFilterChain` diffs (and management port if introduced)\n- Probe / Service / Ingress patches\n- Validation commands (curl from inside vs outside the cluster) and residual risks\n" }, { "id": "flyway-migration-guardrails", @@ -309,7 +309,26 @@ "database" ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/flyway-migration-guardrails.instructions.md` with applyTo for `**/db/migration/**`, `**/db/callback/**`, `**/application*.{yml,yaml,properties}`, and `**/*Flyway*.java`. Claude Code: `.claude/skills/flyway-migration-guardrails/SKILL.md` (plus a short CLAUDE.md fact that schema changes must be expand/contract and never drop in the same release as a code cutover). Codex: a Flyway / schema migration section in root `AGENTS.md` or nested `src/main/resources/AGENTS.md`.", - "body": "# Skill: Flyway Schema Migration Guardrails\n\n## Goal\nShip ordered, reversible-in-practice schema changes for Spring Boot apps using Flyway (or Liquibase-equivalent concepts) so migrations are forward-only, expandable before contract, CI-validated, secret-free, and safe to promote across environments alongside zero-downtime deploys on AKS/Kubernetes.\n\n## When to apply\n- Adding or changing Flyway (or Liquibase) migrations in a Spring Boot service\n- Reviews of `db/migration`, `spring.flyway.*`, or CI jobs that run migrate/validate\n- Schema cutovers that must not break rolling Deployments (old and new pods temporarily coexist)\n- Multi-env promotion (dev → test → staging → prod) where checksum/history drift is a risk\n- Any PR that drops columns/tables, renames, backfills, or changes constraints under load\n\n## Baseline rules\n1. **Forward-only versions.** Prefer `V{version}__description.sql` with monotonically increasing versions. Treat applied migrations as immutable history — never edit a shipped checksum to \"fix\" prod; add a new version instead.\n2. **Expand / contract, never big-bang cutover.** Expand first (add nullable column, new table, dual-write path); deploy code that tolerates both shapes; backfill; then contract (drop old column/table) in a later release after all pods and readers have moved on.\n3. **No destructive drops in the same release as a code cutover.** Do not `DROP COLUMN` / `DROP TABLE` / rename-in-place in the migration that ships with the app version that still reads the old shape. Split across releases with an explicit soak window.\n4. **Lock and statement timeouts.** Set DB session lock/statement timeouts appropriate to the engine (e.g. `lock_timeout`, `statement_timeout` on PostgreSQL; equivalent session settings elsewhere) so a blocked migrate fails fast instead of holding exclusive locks forever. Prefer online / concurrent patterns where the engine supports them.\n5. **Repeatable migrations sparingly.** Use `R__*.sql` only for idempotent views, functions, or reference seed that must re-apply when checksum changes. Never put irreversible DDL or one-shot data fixes in repeatables.\n6. **Out-of-order policy is deliberate.** Keep `spring.flyway.out-of-order` false in shared and prod profiles unless you have a documented hotfix branch process and repair playbook. Accidental out-of-order applies are a common multi-branch footgun.\n7. **CI must validate before merge.** Run `flyway info` / `flyway validate` (or Spring Boot test that boots with validate-on-migrate) on every PR. Fail on checksum mismatch, missing migrations, or failed pending scripts. Prefer an ephemeral DB (Testcontainers / service container) over mocking Flyway away.\n8. **Multi-env promotion is append-only.** The same versioned files promote unchanged. Do not maintain env-specific DDL forks. Seed/config that differs by env belongs in app config or controlled seed jobs — not in versioned migrations with secrets.\n9. **Secrets never in SQL.** No passwords, API keys, connection strings, or PII dumps in migration files. Use placeholders only for non-secret identifiers if needed; inject credentials via Key Vault / env / sealed secrets outside SQL.\n10. **Rollback and repair are operational, not automatic.** Flyway does not magically undo DDL. Plan expand/contract so \"rollback\" means redeploy previous app bits against a still-compatible schema. Use `flyway repair` only for known metadata/checksum fixes after intentional history correction — never as a routine merge step.\n11. **Pair with zero-downtime deploys.** On AKS/K8s, assume N and N-1 pods during rolling update. Migrations must leave the schema readable/writable by both code generations. Prefer init/Job migrate-before-rollout or a controlled migrate step with pod disruption awareness — not racing concurrent migrators without a lock story.\n12. **Naming and ownership.** One team owns the migration sequence. Version numbers (or Flyway Teams/Community versioning scheme you adopt) must be coordinated across branches; rebase rather than invent colliding versions.\n\n## Steps\n1. **Inventory.** Locate `classpath:db/migration` (or configured locations), Flyway/Liquibase dependency, `spring.flyway.*` / `spring.liquibase.*`, and any CI migrate/validate jobs. Note DB engine and whether migrate runs in-app on startup, as a Job, or in pipeline.\n2. **Classify the change.** Additive (safe expand), backfill, constraint tighten, rename, or destructive contract. If destructive or rename, split into expand → dual-support code → backfill → contract PRs.\n3. **Author the next version.** Create `V{next}__short_snake_description.sql` with explicit, idempotent-as-possible DDL for the engine. Prefer additive nullables and new objects first. Avoid multi-statement ambiguous transactions on engines that auto-commit DDL.\n4. **Wire app tolerance.** Update entities/repositories/SQL to tolerate old+new shapes when expand is incomplete. Feature-flag dual-write if needed. Do not require the contracted schema in the same Deployment revision as the expand.\n5. **CI gate.** Ensure PR pipeline runs validate/info against a clean and against a DB that already applied prior versions. Assert checksum stability for already-merged files.\n6. **Promotion checklist.** Confirm the same artifact/migration set will apply in higher envs; document expected lock duration and any required maintenance window; verify K8s rollout strategy (maxUnavailable / migrate Job ordering).\n7. **Contract later.** After soak and traffic proof, open a follow-up migration that drops obsolete objects — only when N-1 code is gone.\n\n## Constraints\n- Do not edit or delete already-applied versioned files on shared branches.\n- Do not embed secrets, prod hostnames with credentials, or real PII in SQL or README samples.\n- Do not enable `clean` / `clean-disabled=false` in non-ephemeral environments.\n- Do not assume Liquibase `rollback` blocks exist for Flyway workflows; spell out expand/contract instead.\n- Keep examples engine-aware (call out PostgreSQL vs others) without inventing proprietary vendor runbooks.\n- Prefer minimal diffs; no unrelated Flyway config refactors in the same PR unless required for safety (timeouts, validate-on-migrate).\n\n## Examples\n- **Expand:** `V42__add_orders_fulfillment_status.sql` adds nullable `fulfillment_status` with a default or null; app N writes both legacy flag and new column; app N+1 reads new column; later `V55__drop_orders_legacy_fulfilled_flag.sql` contracts.\n- **CI:** PR job starts Postgres service, runs app tests with `spring.flyway.validate-on-migrate=true`, and fails if `flyway validate` reports checksum mismatch.\n- **AKS:** Migrate Job (or pre-sync hook) completes successfully before Deployment rollout; readiness only passes when schema version ≥ required; old ReplicaSet drained only after dual-read code is live.\n- **Repair caveat:** After an emergency hotfix that required rewriting an unapplied local file, repair metadata in lower envs with documented approval — never silently repair prod checksums from a laptop.\n\n## Verification\n1. `flyway info` (or Boot Actuator/Flyway endpoint if intentionally exposed to operators only) shows pending → success without error; applied versions match git.\n2. `flyway validate` clean on CI against the migration folder; no checksum diffs on historical versions.\n3. Integration test: boot app against Testcontainers DB twice (migrate fresh + restart) without failure.\n4. Expand PR: old app binary still reads/writes successfully against the expanded schema.\n5. Grep migrations for password/secret patterns and for `DROP`/`RENAME` colocated with feature cutover code in the same PR.\n6. Confirm `out-of-order` and `clean` remain unsafe-default in prod profile; lock/statement timeouts present or documented.\n7. Rollout dry-run notes: N and N-1 compatibility acknowledged; contract migration scheduled separately.\n\n## Output format\n- Change classification (expand / backfill / contract / config-only)\n- New `V*__*.sql` (and any repeatable) with engine notes\n- `spring.flyway.*` diffs if timeouts/validate/out-of-order need tightening\n- CI validate/info steps\n- K8s/AKS ordering notes for zero-downtime\n- Verification checklist and residual risks (lock duration, long backfills)\n" + "body": "# Skill: Flyway Schema Migration Guardrails\n\n## Goal\nShip ordered, reversible-in-practice schema changes for Spring Boot apps using Flyway (or Liquibase-equivalent concepts) so migrations are forward-only, expandable before contract, CI-validated, secret-free, and safe to promote across environments alongside zero-downtime deploys on AKS/Kubernetes.\n\n## When to apply\n- Adding or changing Flyway (or Liquibase) migrations in a Spring Boot service\n- Reviews of `db/migration`, `spring.flyway.*`, or CI jobs that run migrate/validate\n- Schema cutovers that must not break rolling Deployments (old and new pods temporarily coexist)\n- Multi-env promotion (dev \u2192 test \u2192 staging \u2192 prod) where checksum/history drift is a risk\n- Any PR that drops columns/tables, renames, backfills, or changes constraints under load\n\n## Baseline rules\n1. **Forward-only versions.** Prefer `V{version}__description.sql` with monotonically increasing versions. Treat applied migrations as immutable history \u2014 never edit a shipped checksum to \"fix\" prod; add a new version instead.\n2. **Expand / contract, never big-bang cutover.** Expand first (add nullable column, new table, dual-write path); deploy code that tolerates both shapes; backfill; then contract (drop old column/table) in a later release after all pods and readers have moved on.\n3. **No destructive drops in the same release as a code cutover.** Do not `DROP COLUMN` / `DROP TABLE` / rename-in-place in the migration that ships with the app version that still reads the old shape. Split across releases with an explicit soak window.\n4. **Lock and statement timeouts.** Set DB session lock/statement timeouts appropriate to the engine (e.g. `lock_timeout`, `statement_timeout` on PostgreSQL; equivalent session settings elsewhere) so a blocked migrate fails fast instead of holding exclusive locks forever. Prefer online / concurrent patterns where the engine supports them.\n5. **Repeatable migrations sparingly.** Use `R__*.sql` only for idempotent views, functions, or reference seed that must re-apply when checksum changes. Never put irreversible DDL or one-shot data fixes in repeatables.\n6. **Out-of-order policy is deliberate.** Keep `spring.flyway.out-of-order` false in shared and prod profiles unless you have a documented hotfix branch process and repair playbook. Accidental out-of-order applies are a common multi-branch footgun.\n7. **CI must validate before merge.** Run `flyway info` / `flyway validate` (or Spring Boot test that boots with validate-on-migrate) on every PR. Fail on checksum mismatch, missing migrations, or failed pending scripts. Prefer an ephemeral DB (Testcontainers / service container) over mocking Flyway away.\n8. **Multi-env promotion is append-only.** The same versioned files promote unchanged. Do not maintain env-specific DDL forks. Seed/config that differs by env belongs in app config or controlled seed jobs \u2014 not in versioned migrations with secrets.\n9. **Secrets never in SQL.** No passwords, API keys, connection strings, or PII dumps in migration files. Use placeholders only for non-secret identifiers if needed; inject credentials via Key Vault / env / sealed secrets outside SQL.\n10. **Rollback and repair are operational, not automatic.** Flyway does not magically undo DDL. Plan expand/contract so \"rollback\" means redeploy previous app bits against a still-compatible schema. Use `flyway repair` only for known metadata/checksum fixes after intentional history correction \u2014 never as a routine merge step.\n11. **Pair with zero-downtime deploys.** On AKS/K8s, assume N and N-1 pods during rolling update. Migrations must leave the schema readable/writable by both code generations. Prefer init/Job migrate-before-rollout or a controlled migrate step with pod disruption awareness \u2014 not racing concurrent migrators without a lock story.\n12. **Naming and ownership.** One team owns the migration sequence. Version numbers (or Flyway Teams/Community versioning scheme you adopt) must be coordinated across branches; rebase rather than invent colliding versions.\n\n## Steps\n1. **Inventory.** Locate `classpath:db/migration` (or configured locations), Flyway/Liquibase dependency, `spring.flyway.*` / `spring.liquibase.*`, and any CI migrate/validate jobs. Note DB engine and whether migrate runs in-app on startup, as a Job, or in pipeline.\n2. **Classify the change.** Additive (safe expand), backfill, constraint tighten, rename, or destructive contract. If destructive or rename, split into expand \u2192 dual-support code \u2192 backfill \u2192 contract PRs.\n3. **Author the next version.** Create `V{next}__short_snake_description.sql` with explicit, idempotent-as-possible DDL for the engine. Prefer additive nullables and new objects first. Avoid multi-statement ambiguous transactions on engines that auto-commit DDL.\n4. **Wire app tolerance.** Update entities/repositories/SQL to tolerate old+new shapes when expand is incomplete. Feature-flag dual-write if needed. Do not require the contracted schema in the same Deployment revision as the expand.\n5. **CI gate.** Ensure PR pipeline runs validate/info against a clean and against a DB that already applied prior versions. Assert checksum stability for already-merged files.\n6. **Promotion checklist.** Confirm the same artifact/migration set will apply in higher envs; document expected lock duration and any required maintenance window; verify K8s rollout strategy (maxUnavailable / migrate Job ordering).\n7. **Contract later.** After soak and traffic proof, open a follow-up migration that drops obsolete objects \u2014 only when N-1 code is gone.\n\n## Constraints\n- Do not edit or delete already-applied versioned files on shared branches.\n- Do not embed secrets, prod hostnames with credentials, or real PII in SQL or README samples.\n- Do not enable `clean` / `clean-disabled=false` in non-ephemeral environments.\n- Do not assume Liquibase `rollback` blocks exist for Flyway workflows; spell out expand/contract instead.\n- Keep examples engine-aware (call out PostgreSQL vs others) without inventing proprietary vendor runbooks.\n- Prefer minimal diffs; no unrelated Flyway config refactors in the same PR unless required for safety (timeouts, validate-on-migrate).\n\n## Examples\n- **Expand:** `V42__add_orders_fulfillment_status.sql` adds nullable `fulfillment_status` with a default or null; app N writes both legacy flag and new column; app N+1 reads new column; later `V55__drop_orders_legacy_fulfilled_flag.sql` contracts.\n- **CI:** PR job starts Postgres service, runs app tests with `spring.flyway.validate-on-migrate=true`, and fails if `flyway validate` reports checksum mismatch.\n- **AKS:** Migrate Job (or pre-sync hook) completes successfully before Deployment rollout; readiness only passes when schema version \u2265 required; old ReplicaSet drained only after dual-read code is live.\n- **Repair caveat:** After an emergency hotfix that required rewriting an unapplied local file, repair metadata in lower envs with documented approval \u2014 never silently repair prod checksums from a laptop.\n\n## Verification\n1. `flyway info` (or Boot Actuator/Flyway endpoint if intentionally exposed to operators only) shows pending \u2192 success without error; applied versions match git.\n2. `flyway validate` clean on CI against the migration folder; no checksum diffs on historical versions.\n3. Integration test: boot app against Testcontainers DB twice (migrate fresh + restart) without failure.\n4. Expand PR: old app binary still reads/writes successfully against the expanded schema.\n5. Grep migrations for password/secret patterns and for `DROP`/`RENAME` colocated with feature cutover code in the same PR.\n6. Confirm `out-of-order` and `clean` remain unsafe-default in prod profile; lock/statement timeouts present or documented.\n7. Rollout dry-run notes: N and N-1 compatibility acknowledged; contract migration scheduled separately.\n\n## Output format\n- Change classification (expand / backfill / contract / config-only)\n- New `V*__*.sql` (and any repeatable) with engine notes\n- `spring.flyway.*` diffs if timeouts/validate/out-of-order need tightening\n- CI validate/info steps\n- K8s/AKS ordering notes for zero-downtime\n- Verification checklist and residual risks (lock duration, long backfills)\n" + }, + { + "id": "spring-boot-testcontainers", + "title": "Spring Boot Testcontainers Guardrails", + "whenToUse": "Adding or reviewing Spring Boot integration tests that need real Postgres, Kafka, Redis, LocalStack, or other dependencies in Docker via Testcontainers \u2014 keep suites fast, hermetic, CI-friendly, and free of shared-env flakiness.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "java", + "spring-boot", + "testcontainers", + "testing", + "docker" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-boot-testcontainers.instructions.md` with applyTo for `**/src/test/**/*IT.java`, `**/src/test/**/*IntegrationTest.java`, `**/src/test/**/Abstract*Container*.java`, and `**/src/test/resources/application*.{yml,yaml,properties}`. Claude Code: `.claude/skills/spring-boot-testcontainers/SKILL.md` (plus a short CLAUDE.md fact that integration tests use Testcontainers, not shared staging DBs). Codex: a Testcontainers / integration-test section in root `AGENTS.md` or nested `src/test/AGENTS.md`.", + "body": "# Skill: Spring Boot Testcontainers Guardrails\n\n## Goal\nShip hermetic Spring Boot integration tests that boot real dependencies (Postgres, Kafka, Redis, LocalStack, etc.) via Testcontainers so suites stay reproducible on developer laptops and CI, never share mutable staging state, and fail for the right reasons.\n\n## When to apply\n- Adding `@SpringBootTest` / slice tests that need a database, broker, or cloud emulator\n- Replacing `@MockBean`-heavy tests that hide wiring bugs at the repository/adapter boundary\n- Reviews of `src/test` that hit shared Docker hosts, hardcoded ports, or remote staging credentials\n- CI jobs that intermittently fail with \"connection refused\", dirty schema, or port conflicts\n- Pairing with Flyway/Liquibase migrations that must be validated against a real engine\n\n## Baseline rules\n1. **Real dependency, fake network.** Prefer Testcontainers (or the Spring Boot 3.1+ service-connection support) over mocking the JDBC/driver layer when the bug class is SQL dialect, migrations, serialization, or broker semantics.\n2. **No shared staging DBs in unit/CI gates.** Integration tests must not require VPN, shared Postgres, or hand-provisioned Redis. If a test needs those, it is an external contract test and belongs in a separate, opt-in job.\n3. **One container lifecycle strategy per suite.** Prefer singleton containers reused across tests in a JVM (static start + Ryuk cleanup) or Spring's `@ServiceConnection` / `DynamicPropertySource` \u2014 pick one pattern per module and stick to it. Do not start a new Postgres per `@Test` method unless isolation is the point under test.\n4. **Pin images.** Use explicit tags or digests (e.g. `postgres:16-alpine`), never `latest`. Document why a major bump is intentional.\n5. **Let Spring wire connections.** Prefer `@ServiceConnection` (Boot 3.1+) or a single `DynamicPropertySource` that sets JDBC URL/user/password from the container. Avoid copying host/port into `application-test.yml` by hand.\n6. **Migrations run in-test.** Enable Flyway/Liquibase on the test context (or run migrate in an initializer) so schema matches production promotion. Do not maintain a parallel hand-written test schema unless the product explicitly dual-supports it.\n7. **Keep the slice honest.** `@DataJpaTest` + Testcontainers is fine for persistence; full `@SpringBootTest` for HTTP\u2192DB paths. Do not load the entire app when a slice proves the contract.\n8. **CI must have Docker.** Document that GitHub Actions (or Jenkins) runners need Docker-in-Docker / privileged / mounted docker.sock as your org standard requires. Fail fast with a clear assumption check if Docker is missing (`DockerClientFactory.instance().isDockerAvailable()`).\n9. **Parallelism is opt-in.** Default to sequential module tests when containers share a Docker daemon heavily. If you parallelize, isolate by unique database name / Kafka topic prefix / Redis DB index \u2014 never by hoping ports do not collide.\n10. **No secrets in test resources.** Use container defaults or generated credentials. Never commit cloud keys for LocalStack alternatives that talk to real AWS.\n\n## Workflow\n1. Inventory what the production code talks to (DB engine/version, broker, cache, object storage).\n2. Choose the narrowest Spring test slice that still exercises the real adapter.\n3. Add Testcontainers dependencies matching the Spring Boot BOM / testcontainers-bom already in the build (Maven or Gradle). Prefer `junit-jupiter` integration.\n4. Introduce a shared container base (abstract class or `@TestConfiguration`) with pinned image + `@ServiceConnection` / `DynamicPropertySource`.\n5. Write 2\u20133 tests: happy path, one constraint/validation failure, one failure mapping (e.g. duplicate key, missing row).\n6. Run locally: `./mvnw -pl test` or Gradle equivalent. Confirm Ryuk/containers stop cleanly.\n7. Ensure CI workflow already has Docker; add the module to the PR gate if new.\n8. In the PR description: list images used, whether migrations run, and any tests deliberately left as mocks (with why).\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped instructions under `.github/instructions/` with `applyTo` globs for `*IT.java`, `*IntegrationTest.java`, and test `application-*.yml`.\n- Keep always-on `.github/copilot-instructions.md` to one line: integration tests use Testcontainers; no shared staging DBs.\n- Ask Copilot to extend the existing abstract container base rather than inventing a second lifecycle.\n\n### Claude Code\n- Put the procedure in `.claude/skills/spring-boot-testcontainers/SKILL.md`.\n- CLAUDE.md fact only: \"Integration tests use Testcontainers with pinned images; do not point tests at shared staging.\"\n- Have Claude run the module test command and paste output before claiming green.\n\n### Codex\n- Short `AGENTS.md` (or `src/test/AGENTS.md`) section: pinned images, `@ServiceConnection` preferred, Docker required in CI, no staging credentials.\n- Link to this skill or `docs/agents/spring-boot-testcontainers.md` if the body would bloat root AGENTS.md.\n\n## Anti-patterns\n- `localhost:5432` assumptions that pass on one laptop and fail in CI\n- Reusing a developer-installed Postgres with leftover schemas between runs\n- `@MockBean DataSource` / repository mocks for tests whose goal is SQL or migration correctness\n- `latest` image tags and unpinned Testcontainers modules drifting across CI days\n- Starting Postgres + Kafka + LocalStack for a pure mapper unit test\n- Sleeping (\"wait 10s\") instead of waiting on container readiness / Spring context refresh\n- Committing `TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX` hacks without documenting the mirror requirement\n- Disabling Flyway in tests while production relies on it\n\n## Done when\n- [ ] Pinned container image(s) declared in one shared place\n- [ ] Spring obtains JDBC/broker settings from the container (service connection or dynamic properties)\n- [ ] Migrations apply cleanly on a fresh container\n- [ ] At least one happy-path and one failure-path integration test pass locally\n- [ ] CI job has Docker and runs the same module tests\n- [ ] No staging URLs, VPN assumptions, or real cloud secrets in `src/test`\n- [ ] PR notes which boundaries stay mocked and why\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-boot-testcontainers\ndescription: Use when adding or reviewing Spring Boot integration tests with Testcontainers (Postgres, Kafka, Redis, LocalStack). Enforces pinned images, @ServiceConnection or DynamicPropertySource, hermetic CI, and no shared staging databases.\n---\n\nFollow the Spring Boot Testcontainers Guardrails skill: pinned images, one lifecycle per suite, migrations on, Docker required in CI, no staging credentials.\n```\n" } ] }