From ac6c87c143cd9e2ae0a2308a2a5af0892a54f7de Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Thu, 24 Sep 2026 05:10:23 +0000 Subject: [PATCH] Add Flyway schema migration guardrails skill and prompt Skillbook entry for safe ordered Flyway migrations (expand/contract, CI validate, zero-downtime AKS pairing) plus a matching Promptbook task to author PR-ready migrations with a verification checklist. --- promptbook/prompts.json | 19 +++++++++++++++++++ skillbook/skills.json | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index b07d271..30a2b8a 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -291,6 +291,25 @@ ], "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." + }, + { + "id": "author-safe-flyway-migration", + "title": "Author a Safe Flyway Migration", + "whenToUse": "You need a PR-ready Flyway migration (SQL + verification checklist) for a Spring Boot service, including expand/contract planning and CI/AKS safety notes.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "java", + "spring-boot", + "sql", + "flyway", + "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" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index e435742..6aa4264 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -291,6 +291,25 @@ ], "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" + }, + { + "id": "flyway-migration-guardrails", + "title": "Flyway Schema Migration Guardrails", + "whenToUse": "Authoring or reviewing Flyway (or Liquibase-equivalent) schema migrations for Spring Boot apps so changes stay forward-only, expand/contract safe, CI-validated, secret-free, and compatible with zero-downtime AKS/K8s rollouts.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "java", + "spring-boot", + "sql", + "flyway", + "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" } ] }