diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/.editorconfig b/PROJECTS/intermediate/credential-rotation-enforcer/.editorconfig new file mode 100644 index 00000000..89656622 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/.editorconfig @@ -0,0 +1,15 @@ +# ©AngelaMos | 2026 +# .editorconfig + +root = true + +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/.github/workflows/ci.yml b/PROJECTS/intermediate/credential-rotation-enforcer/.github/workflows/ci.yml new file mode 100644 index 00000000..18687c0a --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/.github/workflows/ci.yml @@ -0,0 +1,73 @@ +# ©AngelaMos | 2026 +# ci.yml + +name: CI - Credential Rotation Enforcer + +on: + push: + paths: + - 'PROJECTS/intermediate/credential-rotation-enforcer/**' + - '.github/workflows/cre-*.yml' + pull_request: + paths: + - 'PROJECTS/intermediate/credential-rotation-enforcer/**' + +defaults: + run: + working-directory: PROJECTS/intermediate/credential-rotation-enforcer + +jobs: + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: crystal-lang/install-crystal@v1 + with: + crystal: 1.20.0 + - run: crystal tool format --check + + unit: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + crystal: ["1.19.0", "1.20.0", "nightly"] + steps: + - uses: actions/checkout@v4 + - uses: crystal-lang/install-crystal@v1 + with: + crystal: ${{ matrix.crystal }} + - run: shards install + - run: crystal spec spec/unit --order=random + + integration: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: cre_test + POSTGRES_PASSWORD: cre_test + POSTGRES_DB: cre_test + ports: [5432:5432] + options: --health-cmd "pg_isready -U cre_test" --health-interval 10s + env: + DATABASE_URL: postgres://cre_test:cre_test@localhost:5432/cre_test + steps: + - uses: actions/checkout@v4 + - uses: crystal-lang/install-crystal@v1 + with: + crystal: 1.20.0 + - run: shards install + - run: crystal spec spec/integration --order=random + + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: crystal-lang/install-crystal@v1 + with: + crystal: 1.20.0 + - run: shards install + - run: shards build cre --release diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/.gitignore b/PROJECTS/intermediate/credential-rotation-enforcer/.gitignore new file mode 100644 index 00000000..d1c230ff --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/.gitignore @@ -0,0 +1,19 @@ +# ©AngelaMos | 2026 +# .gitignore + +/bin/ +/lib/ +/.shards/ +/.crystal/ +*.dwarf +.env.local +.env.pending +*.pid +/coverage/ +/tmp/ +*.log +.DS_Store + +# Local-only dev docs (not committed to public repo) +/docs/research/ +/docs/plans/ diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/CONFIGURATION.md b/PROJECTS/intermediate/credential-rotation-enforcer/CONFIGURATION.md new file mode 100644 index 00000000..9a2dffec --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/CONFIGURATION.md @@ -0,0 +1,603 @@ + + +# Configuration Guide + +Step-by-step setup for running `cre` against real systems. Read top-to-bottom on first install; come back as a reference later. + +> **TL;DR:** `cre` is configured entirely via **environment variables** (no config file required). Every integration is opt-in — set the env vars for the integrations you want, leave the rest unset, and the daemon adapts. Run `cre run` and watch the boot output to see which integrations actually wired up. + +--- + +## Table of contents + +1. [Required env vars](#1-required-env-vars) +2. [Database setup (Postgres)](#2-database-setup-postgres) +3. [Generate the cryptographic keys](#3-generate-the-cryptographic-keys) +4. [Define your policies](#4-define-your-policies) +5. [Seed your inventory](#5-seed-your-inventory) +6. [Wire AWS Secrets Manager](#6-wire-aws-secrets-manager) +7. [Wire HashiCorp Vault](#7-wire-hashicorp-vault) +8. [Wire GitHub fine-grained PATs](#8-wire-github-fine-grained-pats) +9. [Wire Telegram (notifications + commands)](#9-wire-telegram-notifications--commands) +10. [Run as a systemd service](#10-run-as-a-systemd-service) +11. [Verify and audit](#11-verify-and-audit) +12. [Key rotation (the KEK / HMAC keys themselves)](#12-key-rotation-the-kek--hmac-keys-themselves) +13. [Security checklist before production](#13-security-checklist-before-production) + +--- + +## 1. Required env vars + +Bare minimum to boot: + +```bash +export DATABASE_URL="sqlite:/var/lib/cre/cre.db" # or postgres://... +export CRE_KEK_HEX="$(openssl rand -hex 32)" # 64 hex chars (32 bytes) +export CRE_HMAC_KEY_HEX="$(openssl rand -hex 32)" # 64 hex chars (32 bytes) +``` + +Optional but worth setting: + +```bash +export CRE_TICK_SECONDS=60 # scheduler interval (default: 60) +export CRE_DB_PATH=/var/lib/cre/cre.db # used by 'cre audit verify' default +``` + +Everything else (AWS, Vault, GitHub, Telegram) is **opt-in** — set those vars only if you want those integrations. + +--- + +## 2. Database setup (Postgres) + +For production, use Postgres. SQLite is for the Tier 1 demo and small single-host deployments. + +### Create the database + +```bash +sudo -u postgres psql < Future versions will support `CRE_KEK_KMS=arn:...` to load directly from AWS KMS. Today it's env-only. + +--- + +## 4. Define your policies + +Policies are **Crystal source files** in `policies/`. They're compiled into the binary, so changes require a rebuild — but the compiler validates them, which means you can't ship a typo. + +### Example: `policies/production.cr` + +```crystal +require "../src/cre/policy/dsl" +include CRE::Policy::DSL + +policy "aws-prod-databases" do + description "Prod RDS credentials rotate every 30 days" + match { |c| c.kind.aws_secretsmgr? && c.tag(:env) == "prod" } + max_age 30.days + warn_at 25.days + enforce :rotate_immediately + notify_via :telegram, :structured_log + on_rotation_failure :alert_critical +end + +policy "github-bots" do + description "GitHub bot PATs notify-only at 90 days" + match { |c| c.kind.github_pat? && c.tag(:purpose) == "ci" } + max_age 90.days + warn_at 83.days + enforce :notify_only + notify_via :telegram +end + +policy "vault-dynamic-aggressive" do + description "Vault dynamic DB creds rotate weekly" + match { |c| c.kind.vault_dynamic? } + max_age 7.days + enforce :rotate_immediately + notify_via :structured_log +end + +policy "all-local-env-files" do + match { |c| c.kind.env_file? } + max_age 30.days + enforce :rotate_immediately +end +``` + +### Validation + +`crystal build` compiles policies and runs three independent checks: + +1. **Enum autocast** — `enforce :foo_bar` fails if `:foo_bar` isn't an `Action` +2. **Typed Proc matchers** — `c.kund` (typo) fails because `Credential` has no `kund` method +3. **Required-fields check** — Builder raises if `match`, `max_age`, or `enforce` is missing + +If `cre` ships, the policies are well-formed — period. + +### Available enum values + +| `enforce` | `notify_via` (any combination) | `on_rotation_failure` / `on_drift_detected` | +|---|---|---| +| `:rotate_immediately` | `:telegram` | `:rotate_immediately` | +| `:notify_only` | `:email` (placeholder) | `:notify_only` | +| `:quarantine` | `:structured_log` | `:quarantine` | +| | `:pagerduty` (placeholder) | | + +--- + +## 5. Seed your inventory + +`cre` doesn't auto-discover credentials. You tell it what exists by inserting rows into the `credentials` table. Each rotator looks for specific tags. + +### Tag schema by rotator kind + +| `kind` | Required tags | Optional tags | +|---|---|---| +| `AwsSecretsmgr` | `secret_arn` | `value_length` (default 32), `env`, `team` | +| `VaultDynamic` | `role_path` (e.g. `database/creds/myrole`) | `current_lease_id` (set after first rotation) | +| `GithubPat` | `name`, `scopes` (JSON array as string), `old_pat_id` | `expires_in_days` (default 90) | +| `EnvFile` | `path`, `key` | `bytes` (default 32) | + +### Seed examples + +#### AWS Secrets Manager credential + +```sql +INSERT INTO credentials (id, external_id, kind, name, tags, created_at, updated_at) +VALUES ( + gen_random_uuid(), + 'arn:aws:secretsmanager:us-east-1:123456789012:secret:db-prod-rw', + 'AwsSecretsmgr', + 'db-prod-rw', + '{"env":"prod","team":"platform","value_length":"24"}'::jsonb, + now(), + now() +); +``` + +#### Vault dynamic-secrets credential + +```sql +INSERT INTO credentials (id, external_id, kind, name, tags, created_at, updated_at) +VALUES ( + gen_random_uuid(), + 'database/creds/postgres-readonly', + 'VaultDynamic', + 'postgres-readonly', + '{"role_path":"database/creds/postgres-readonly"}'::jsonb, + now(), + now() +); +``` + +#### GitHub fine-grained PAT + +```sql +INSERT INTO credentials (id, external_id, kind, name, tags, created_at, updated_at) +VALUES ( + gen_random_uuid(), + 'gh-deploy-bot', + 'GithubPat', + 'deploy-bot', + '{"name":"deploy-bot","scopes":"[\"repo\",\"read:org\"]","old_pat_id":"12345","expires_in_days":"90"}'::jsonb, + now(), + now() +); +``` + +> The `old_pat_id` field gets updated by the rotator after each rotation (the new PAT becomes the next "old"). For the first seed, set it to your existing PAT's id (find it via GitHub UI or `GET /user/personal-access-tokens`). + +#### Local `.env` file + +```sql +INSERT INTO credentials (id, external_id, kind, name, tags, created_at, updated_at) +VALUES ( + gen_random_uuid(), + '/etc/myapp/.env::API_KEY', + 'EnvFile', + 'myapp-API_KEY', + '{"path":"/etc/myapp/.env","key":"API_KEY","bytes":"32"}'::jsonb, + now(), + now() +); +``` + +> Make sure the `cre` user has read+write permission on the file's parent directory (it writes `.env.pending` and renames atomically). + +--- + +## 6. Wire AWS Secrets Manager + +### IAM permissions + +Create an IAM user (or assumable role) with this policy: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "CreRotation", + "Effect": "Allow", + "Action": [ + "secretsmanager:GetSecretValue", + "secretsmanager:PutSecretValue", + "secretsmanager:UpdateSecretVersionStage", + "secretsmanager:DescribeSecret" + ], + "Resource": "arn:aws:secretsmanager:*:*:secret:cre-managed/*" + } + ] +} +``` + +> Scope `Resource` tightly. `arn:aws:secretsmanager:*:*:secret:cre-managed/*` means CRE can only touch secrets prefixed `cre-managed/` — anything else in your account is off-limits even if the daemon is compromised. + +### Env vars + +```bash +export AWS_ACCESS_KEY_ID="AKIA..." +export AWS_SECRET_ACCESS_KEY="..." +export AWS_REGION="us-east-1" +# Optional - for STS assumed roles: +# export AWS_SESSION_TOKEN="..." +# Optional - for LocalStack / Tier 2 testing: +# export AWS_ENDPOINT="http://localhost:4566" +``` + +### Verify + +After restart, boot output should show `rotators: env_file, aws_secretsmgr`. If it only shows `env_file`, your AWS env vars aren't being read. + +### IRSA / instance profile (no static keys) + +If you're running CRE on EC2/EKS, you can drop static keys entirely and use the instance profile. Set `AWS_REGION` and leave `AWS_ACCESS_KEY_ID` unset — current code requires explicit keys, so this is **TODO**: when supported, the SDK chain will pick up IRSA / IMDSv2 automatically. + +--- + +## 7. Wire HashiCorp Vault + +### Vault server requirements + +- Database secrets engine enabled at `database/` +- A role configured (e.g., `vault write database/roles/myrole ...`) +- A token with `read` on `database/creds/*` and `update` on `sys/leases/revoke` + +### Token policy example + +`cre-policy.hcl`: + +```hcl +path "database/creds/*" { + capabilities = ["read"] +} +path "sys/leases/revoke" { + capabilities = ["update"] +} +path "sys/leases/renew" { + capabilities = ["update"] +} +``` + +```bash +vault policy write cre-policy cre-policy.hcl +vault token create -policy=cre-policy -ttl=720h +# capture the .auth.client_token from output +``` + +### Env vars + +```bash +export VAULT_ADDR="https://vault.internal:8200" +export VAULT_TOKEN="hvs.CAESI..." +``` + +### Verify + +Boot output should show `rotators: env_file, ..., vault_dynamic`. + +--- + +## 8. Wire GitHub fine-grained PATs + +### The "admin" PAT + +You need a fine-grained PAT that has permission to **manage other fine-grained PATs**. This is special: + +1. Go to https://github.com/settings/personal-access-tokens +2. Click "Generate new token (fine-grained)" +3. Resource owner: yourself or org +4. Permissions: **Account → Personal access tokens → Read & write** +5. Save the token (`ghp_admin_...`) + +> This token has admin power over your other PATs — store it like a root credential. In production, this is a great candidate to itself be managed by `cre` once a year (you rotate the rotator's own credentials). + +### Env vars + +```bash +export GITHUB_TOKEN="ghp_admin_..." +# Optional - for fake-GitHub Tier 2 testing: +# export GITHUB_API_BASE="http://localhost:7115" +``` + +### Find your existing PAT IDs + +```bash +curl -H "Authorization: Bearer $GITHUB_TOKEN" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + https://api.github.com/user/personal-access-tokens +``` + +Use the `id` field from each entry as the `old_pat_id` in your seed SQL. + +--- + +## 9. Wire Telegram (notifications + commands) + +### Create the bot + +1. Open Telegram, search for `@BotFather` +2. `/newbot`, give it a name + username +3. Save the token (`123456:ABC-DEF...`) — that's `TELEGRAM_TOKEN` + +### Find your chat ID + +The bot can only message chats you've started a conversation with first. + +1. Open your bot in Telegram, send it any message (e.g. `/start`) +2. Visit `https://api.telegram.org/bot/getUpdates` in a browser +3. Find `"chat":{"id":123456789,...}` — that's your chat ID + +For group chats: add the bot to the group, send a message, then call `getUpdates` — you'll see a negative chat ID like `-1001234567890`. + +### Env vars + +```bash +export TELEGRAM_TOKEN="123456:ABC-DEF..." +export TELEGRAM_VIEWER_CHATS="123456789,987654321" # comma-separated +export TELEGRAM_OPERATOR_CHATS="123456789" # operators get /rotate, /snooze +``` + +> Anyone in `OPERATOR_CHATS` can `/rotate` any credential. Anyone in `VIEWER_CHATS` (and operators) can `/status`, `/queue`, `/history`, `/alerts`, `/help`. + +### Available commands + +| Command | Tier | Purpose | +|---|---|---| +| `/status` | viewer | Quick health snapshot | +| `/queue` | viewer | Active + scheduled rotations | +| `/history ` | viewer | Last 10 audit events for one credential | +| `/alerts` | viewer | Pointer to `cre audit verify` | +| `/help` | viewer | Command list | +| `/rotate ` | operator | Manually trigger rotation | +| `/snooze 24h` | operator | Defer scheduled rotation (currently a stub) | + +### Verify + +Boot output: `telegram: enabled`. Open Telegram, send `/status`, you should get a reply within 2 seconds. + +--- + +## 10. Run as a systemd service + +### `/etc/systemd/system/cre.service` + +```ini +[Unit] +Description=Credential Rotation Enforcer +After=network-online.target postgresql.service +Wants=network-online.target + +[Service] +Type=simple +User=cre +Group=cre +WorkingDirectory=/var/lib/cre +ExecStart=/usr/local/bin/cre run --db=postgres://cre:CHANGEME@localhost:5432/cre_prod +EnvironmentFile=/etc/cre/cre.env +Restart=on-failure +RestartSec=10 +StandardOutput=journal +StandardError=journal + +# Hardening +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ReadWritePaths=/var/lib/cre /etc/myapp # whatever .env paths you manage +ProtectHome=true +ProtectKernelTunables=true +ProtectControlGroups=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +LockPersonality=true +MemoryDenyWriteExecute=true + +[Install] +WantedBy=multi-user.target +``` + +### `/etc/cre/cre.env` (mode 0600, owner cre:cre) + +``` +CRE_KEK_HEX=... +CRE_HMAC_KEY_HEX=... +CRE_TICK_SECONDS=60 + +AWS_ACCESS_KEY_ID=AKIA... +AWS_SECRET_ACCESS_KEY=... +AWS_REGION=us-east-1 + +VAULT_ADDR=https://vault.internal:8200 +VAULT_TOKEN=hvs.... + +GITHUB_TOKEN=ghp_admin_... + +TELEGRAM_TOKEN=123456:... +TELEGRAM_VIEWER_CHATS=123456789 +TELEGRAM_OPERATOR_CHATS=123456789 +``` + +### Enable + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now cre +sudo systemctl status cre +journalctl -u cre -f # follow logs +``` + +--- + +## 11. Verify and audit + +### Live monitoring + +```bash +cre watch --db=$DATABASE_URL # k9s-style live TUI +just tui-demo # synthetic 8-second preview (no daemon needed) +``` + +### One-shot CI gate + +```bash +cre check --db=$DATABASE_URL --output=json | jq . +# exit code 0 = no violations, 1 = violations found +``` + +### Audit chain integrity + +```bash +cre audit verify --db=/var/lib/cre/cre.db +# ✓ chain valid: 14,892 entries +``` + +### Compliance evidence export + +```bash +cre export --framework=soc2 --out=/tmp/q1-evidence.zip +unzip -l /tmp/q1-evidence.zip +# audit_log.ndjson, audit_batches.json, control_mapping.json, manifest.json, README.md +``` + +Hand the ZIP to your auditor. They can verify file checksums against `manifest.json` and recompute the audit hash chain offline. + +--- + +## 12. Key rotation (the KEK / HMAC keys themselves) + +The crypto roots are themselves credentials. They have lifetimes too. + +### KEK rotation + +Annual or on suspected compromise: + +1. Generate a new KEK +2. Update `CRE_KEK_HEX` in `/etc/cre/cre.env` (keep the old one in `CRE_KEK_HEX_PREVIOUS` if you wire that) +3. Restart the daemon — it will use the new KEK for new credentials, and the persistence layer will fail to decrypt rows wrapped under the old KEK +4. **Forced rewrap (planned, not yet wired):** `cre crypto rewrap` reads each row, unwraps with `CRE_KEK_HEX_PREVIOUS`, re-wraps with the new KEK. Until that command exists, KEK rotation requires writing a one-off Crystal script. + +> KEK rotation without a rewrap path = data loss. Test the rewrap procedure on a non-prod DB before doing this in production. + +### HMAC ratchet + +The audit log's HMAC key rolls automatically every 1024 entries (configurable). You don't manually rotate it. To force an early rotation, restart the daemon with a new `CRE_HMAC_KEY_HEX` — old entries remain verifiable under their original ratchet generation; new entries chain forward under the new key. + +--- + +## 13. Security checklist before production + +- [ ] `CRE_KEK_HEX` and `CRE_HMAC_KEY_HEX` are different random 32-byte values +- [ ] `/etc/cre/cre.env` has mode `0600`, owner `cre:cre`, never committed to Git +- [ ] Database app role demoted to `INSERT, SELECT` on `audit_events` +- [ ] AWS IAM scope is narrow (`Resource: arn:aws:secretsmanager:*:*:secret:cre-managed/*`) +- [ ] Vault token is scoped (no root tokens); rotated periodically itself +- [ ] GitHub admin PAT is also a credential CRE could manage (recursion!) +- [ ] Telegram operator chats list is short and audited (each chat ID is a person) +- [ ] systemd hardening directives applied (`NoNewPrivileges`, `ProtectSystem=strict`, etc.) +- [ ] `cre audit verify` runs as a periodic cron job and pages on failure +- [ ] Compliance bundle export tested end-to-end with a sample auditor walkthrough +- [ ] Backup strategy for the database includes the `audit_events` table (point-in-time recovery preferred over snapshots — protects the chain) + +--- + +## Appendix A: Boot output decoder + +When you start `cre run`, expect output like: + +``` +cre running. PID 4242, tick 60s, db postgres://****:****@db.internal:5432/cre_prod +rotators: env_file, aws_secretsmgr, vault_dynamic, github_pat +telegram: enabled +2026-04-29T15:00:00.000Z INFO - cre.rotation_worker: registered rotator: env_file +2026-04-29T15:00:00.001Z INFO - cre.rotation_worker: registered rotator: aws_secretsmgr +2026-04-29T15:00:00.002Z INFO - cre.rotation_worker: registered rotator: vault_dynamic +2026-04-29T15:00:00.003Z INFO - cre.rotation_worker: registered rotator: github_pat +2026-04-29T15:00:00.005Z INFO - cre.engine: engine started +``` + +`rotators: ...` lists the rotators that successfully wired. If you set `AWS_ACCESS_KEY_ID` but `aws_secretsmgr` is missing, your env var didn't propagate to the daemon — check `systemctl show cre -p Environment` or the EnvironmentFile path. + +`telegram: (disabled)` means either `TELEGRAM_TOKEN` is unset or the chat-ID lists are empty. With token + at least one chat, you'll see `telegram: enabled`. + +## Appendix B: One-line setup recipes + +| Need | Command | +|---|---| +| Tier 1 demo | `just demo` | +| Live TUI preview | `just tui-demo` | +| Full Docker stack | `just demo-full` then `just demo-full-down` | +| Format + lint + test | `just ci` | +| List all recipes | `just` | diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/LICENSE b/PROJECTS/intermediate/credential-rotation-enforcer/LICENSE new file mode 100644 index 00000000..0ad25db4 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/README.md b/PROJECTS/intermediate/credential-rotation-enforcer/README.md new file mode 100644 index 00000000..24346065 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/README.md @@ -0,0 +1,171 @@ + + +```regex + ██████╗██████╗ ███████╗ +██╔════╝██╔══██╗██╔════╝ +██║ ██████╔╝█████╗ +██║ ██╔══██╗██╔══╝ +╚██████╗██║ ██║███████╗ + ╚═════╝╚═╝ ╚═╝╚══════╝ +``` + +[![Cybersecurity Projects](https://img.shields.io/badge/Cybersecurity--Projects-Project%20%2327%20intermediate-red?style=flat&logo=github)](https://github.com/CarterPerez-dev/Cybersecurity-Projects/tree/main/PROJECTS/intermediate/credential-rotation-enforcer) +[![Crystal](https://img.shields.io/badge/Crystal-1.20+-black?style=flat&logo=crystal&logoColor=white)](https://crystal-lang.org) +[![License: AGPLv3](https://img.shields.io/badge/License-AGPL_v3-purple.svg)](https://www.gnu.org/licenses/agpl-3.0) +[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-16-336791?style=flat&logo=postgresql&logoColor=white)](https://www.postgresql.org) + +> Credential rotation enforcer written in Crystal. Tracks credentials, evaluates compile-time-checked policies, and executes the four-step rotation contract against AWS Secrets Manager, HashiCorp Vault, GitHub fine-grained PATs, and local `.env` files. Single binary, live TUI, bidirectional Telegram bot, tamper-evident audit log, signed compliance evidence export. + +*This is a quick overview — security theory, architecture, and full walkthroughs are in the [learn modules](#learn). Operator setup lives in [CONFIGURATION.md](CONFIGURATION.md).* + +## What It Does + +- Compile-time-checked policy DSL (typo'd action symbols, missing fields, bad credential property references all fail `crystal build`) +- Bus + plugin architecture — typed events fan out across Crystal channels; subscribers (audit, TUI, Telegram, log) react independently; rotators register at compile time via `register_as :kind` macro +- Four-step rotation contract (`generate → apply → verify → commit`) borrowed from AWS Secrets Manager's rotation Lambda template, dual-version safe under concurrent reads +- Three-layer tamper-evident audit log: SHA-256 hash chain + ratcheting HMAC-SHA256 + Ed25519-signed Merkle batches +- AEAD envelope encryption (AES-256-GCM, per-row DEKs wrapped by KEK, AAD-bound to credential identity, reserved `algorithm_id` byte for crypto agility) +- Hand-rolled live TUI (no external TUI framework — stdlib ANSI escapes only) with event-driven repaints coalesced to a tick interval +- Bidirectional Telegram bot — viewer tier (`/status`, `/queue`, `/history`, `/alerts`) + operator tier (`/rotate`) +- Compliance evidence export bundle (signed ZIP with audit log, Merkle batches, control mapping for SOC 2 / PCI-DSS / ISO 27001 / HIPAA) + +## Quick Start + +```bash +git clone https://github.com/CarterPerez-dev/Cybersecurity-Projects.git +cd Cybersecurity-Projects/PROJECTS/intermediate/credential-rotation-enforcer +shards install && shards build cre --release +./bin/cre demo +``` + +Or use the install script: + +```bash +curl -fsSL https://raw.githubusercontent.com/CarterPerez-dev/Cybersecurity-Projects/main/PROJECTS/intermediate/credential-rotation-enforcer/scripts/install.sh | bash +``` + +> [!TIP] +> This project uses [`just`](https://github.com/casey/just) as a command runner. Type `just` to see all available recipes. +> +> Install: `curl -sSf https://just.systems/install.sh | bash -s -- --to ~/.local/bin` + +### Demo tiers + +```bash +just demo # Tier 1 — zero-deps SQLite + .env rotator (under 30s) +just tui-demo # Live TUI preview with synthetic events (8s, no setup) +just demo-full # Tier 2 — Docker Compose: PG + LocalStack + Vault + fake-GH +just demo-full-down # tear down the stack +``` + +### Daemon usage + +`cre run` and `cre watch` require two 32-byte secrets — the seed key for the audit-log HMAC ratchet and the KEK that wraps per-row data keys. Generate fresh values once and store them somewhere durable (KMS, password manager, sealed env file): + +```bash +export CRE_HMAC_KEY_HEX=$(openssl rand -hex 32) +export CRE_KEK_HEX=$(openssl rand -hex 32) +export CRE_SIGNING_KEY_HEX=$(openssl rand -hex 32) # optional: enables Merkle-batch sealing +``` + +Then: + +```bash +cre run --db=sqlite:cre.db # headless daemon +cre watch --db=sqlite:cre.db # daemon + live TUI +cre check --db=sqlite:cre.db --output=json # one-shot CI gate (no key required) +cre rotate # manual rotation (uses same env-driven rotators as run) +cre policy list # inspect compiled policies +cre audit verify # hash chain + HMAC ratchet (+ Merkle if --public-key given) +cre export --framework=soc2 --out=evidence.zip # signed compliance bundle +cre verify-bundle evidence.zip # offline re-verify a bundle +``` + +`cre check` exits 1 when any credential violates its policy — drop into any CI pipeline. + +## Flagship Rotators + +| Rotator | What it talks to | Auth | +|---|---|---| +| AWS Secrets Manager | `secretsmanager..amazonaws.com` | SigV4 (rolled from scratch in `src/cre/aws/signer.cr`) | +| HashiCorp Vault | `vault read database/creds/` + lease revoke | `X-Vault-Token` | +| GitHub fine-grained PATs | `POST/DELETE /user/personal-access-tokens` | `Bearer ghp_...` | +| Local `.env` file | atomic temp+rename | n/a | + +Adding a fifth rotator means dropping a single file in `src/cre/rotators/` — the `register_as :kind` macro hooks it into the registry at compile time. Zero changes to the orchestrator, scheduler, or any subscriber. + +## Architecture + +``` + ┌──────────────────────────────────────┐ + │ cre (single Crystal binary) │ + │ │ + ┌────────────┐ │ ┌──────────────────────────────┐ │ + │ Scheduler │─────►│ │ Typed Event Bus │ │ + │ (fiber) │ │ └──┬─────┬─────┬─────┬─────┬───┘ │ + └────────────┘ │ │ │ │ │ │ │ + │ ┌──▼──┐ ┌▼────┐ ┌▼──┐ ┌▼──┐ ┌▼───┐ │ + │ │Rot. │ │Audit│ │TUI│ │Tg │ │Pol.│ │ + │ │Wrkr │ │Sub │ │Sub│ │Bot│ │Eval│ │ + │ └──┬──┘ └──┬──┘ └───┘ └───┘ └────┘ │ + │ │ │ │ + │ ▼ ▼ │ + │ ┌──────────────────────────────┐ │ + │ │ Persistence (PG / SQLite) │ │ + │ │ + 3-layer audit integrity │ │ + │ └──────────────────────────────┘ │ + └──────────────────────────────────────┘ +``` + +All long-lived components are fibers in one OS process. The bus is in-process (Crystal channels are nanosecond-scale) so the architectural overhead is essentially free. Per-subscriber overflow policy: `Block` for audit (compliance — never drop), `Drop` for TUI / metrics / Telegram (best-effort). + +## The Three-Layer Audit Log + +``` + Layer 3 ─ Ed25519-signed Merkle batches → auditor verifies with public key only + Layer 2 ─ HMAC ratchet (key zeroized per rotation) → past entries unforgeable + Layer 1 ─ SHA-256 hash chain → any single-row tampering breaks forward chain + ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Postgres ─ append-only via TRIGGER + role grants (INSERT-only) +``` + +`cre audit verify` walks all three layers and reports which (if any) is broken. + +## Stack + +**Language:** Crystal 1.20+ + +**Dependencies:** crystal-db (DB abstraction), crystal-pg (PostgreSQL), crystal-sqlite3 (SQLite), tourmaline (Telegram framework, used minimally), webmock.cr (test HTTP mocks) + +**Direct LibCrypto FFI** for AES-256-GCM AEAD (Crystal stdlib `OpenSSL::Cipher` lacks GCM auth_data/auth_tag) and Ed25519 signing (stdlib lacks high-level wrapper). Bindings live in `src/cre/crypto/aead.cr` and `src/cre/audit/signing.cr`. + +**Testing:** stdlib `Spec` runner, 179+ unit tests + integration tests against real PostgreSQL via Docker. + +## Configuration + +Setup is fully env-var driven — no config file required. See **[CONFIGURATION.md](CONFIGURATION.md)** for the operator guide: + +- Required env vars (`CRE_KEK_HEX`, `CRE_HMAC_KEY_HEX`, `DATABASE_URL`) +- Per-rotator setup (AWS IAM policy, Vault token policy, GitHub admin PAT) +- Telegram bot creation + chat-ID discovery +- systemd service unit with hardening directives +- Production security checklist + +## Learn + +This project includes step-by-step learning materials covering security theory, architecture, and implementation. + +| Module | Topic | +|--------|-------| +| [00 - Overview](learn/00-OVERVIEW.md) | Prerequisites, quick start, three-tier demo path | +| [01 - Concepts](learn/01-CONCEPTS.md) | Rotation theory, real breaches, NIST/SOC2/PCI/ISO/HIPAA framework controls | +| [02 - Architecture](learn/02-ARCHITECTURE.md) | Bus + plugin design, persistence layers, three-layer audit integrity, AEAD envelope | +| [03 - Implementation](learn/03-IMPLEMENTATION.md) | Code-level walkthrough; where to look in source for each concept | +| [04 - Challenges](learn/04-CHALLENGES.md) | 10 ranked extension challenges (PG ALTER USER, Slack, ML-KEM, OpenTimestamps, SPIFFE, JIT broker, etc.) | + +## License + +AGPL 3.0 diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/config/demo-full.cr.example b/PROJECTS/intermediate/credential-rotation-enforcer/config/demo-full.cr.example new file mode 100644 index 00000000..44bca6da --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/config/demo-full.cr.example @@ -0,0 +1,23 @@ +# ©AngelaMos | 2026 +# demo-full.cr.example + +# Tier 2 demo config: docker-compose stack on localhost. +# Copy to demo-full.cr and load via `cre run --config=...` (full config loader +# wired in a future iteration). + +# Database: +# DATABASE_URL=postgres://cre:cre@localhost:5432/cre + +# AWS Secrets Manager (LocalStack): +# AWS_ACCESS_KEY_ID=test +# AWS_SECRET_ACCESS_KEY=test +# AWS_REGION=us-east-1 +# AWS_ENDPOINT=http://localhost:4566 + +# Vault: +# VAULT_ADDR=http://localhost:8200 +# VAULT_TOKEN=dev-root-token + +# GitHub (fake API): +# GITHUB_API_BASE=http://localhost:7000 +# GITHUB_TOKEN=ghp_admin_fake diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/docker/docker-compose.yml b/PROJECTS/intermediate/credential-rotation-enforcer/docker/docker-compose.yml new file mode 100644 index 00000000..5794825d --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/docker/docker-compose.yml @@ -0,0 +1,39 @@ +# ©AngelaMos | 2026 +# docker-compose.yml + +services: + postgres: + image: postgres:18 + environment: + POSTGRES_USER: cre + POSTGRES_PASSWORD: cre + POSTGRES_DB: cre + ports: ["6022:5432"] + healthcheck: + test: ["CMD-SHELL", "pg_isready -U cre"] + interval: 3s + timeout: 3s + retries: 10 + + localstack: + image: localstack/localstack:latest + environment: + SERVICES: secretsmanager + DEBUG: 0 + ports: ["45666:4566"] + + vault: + image: hashicorp/vault:latest + cap_add: [IPC_LOCK] + environment: + VAULT_DEV_ROOT_TOKEN_ID: dev-root-token + VAULT_DEV_LISTEN_ADDRESS: 0.0.0.0:8200 + ports: ["18201:8200"] + command: vault server -dev + + fake-github: + image: python:3.13-alpine + working_dir: /app + volumes: ["./fake-github:/app:ro"] + command: ["sh", "-c", "pip install --quiet flask && python /app/app.py"] + ports: ["7115:7000"] diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/docker/fake-github/app.py b/PROJECTS/intermediate/credential-rotation-enforcer/docker/fake-github/app.py new file mode 100644 index 00000000..4461348d --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/docker/fake-github/app.py @@ -0,0 +1,42 @@ +""" +©AngelaMos | 2026 +app.py +""" + +from flask import Flask, jsonify, request + +app = Flask(__name__) +TOKENS: dict[int, dict] = {} +NEXT_ID = 100000 + + +@app.route("/user", methods=["GET"]) +def user(): + auth = request.headers.get("Authorization", "") + if not auth.startswith("Bearer "): + return jsonify({"message": "Bad credentials"}), 401 + return jsonify({"login": "fake-bot", "id": 1}) + + +@app.route("/user/personal-access-tokens", methods=["POST"]) +def create_pat(): + global NEXT_ID + body = request.get_json() or {} + pat_id = NEXT_ID + NEXT_ID += 1 + TOKENS[pat_id] = body + return jsonify({ + "id": pat_id, + "token": f"ghp_fake_{pat_id}", + "expires_at": "2026-12-31T00:00:00Z", + }) + + +@app.route("/user/personal-access-tokens/", methods=["DELETE"]) +def delete_pat(pat_id): + TOKENS.pop(pat_id, None) + return "", 200 + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=7000) diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/justfile b/PROJECTS/intermediate/credential-rotation-enforcer/justfile new file mode 100644 index 00000000..553f7bfa --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/justfile @@ -0,0 +1,211 @@ +# ============================================================================= +# AngelaMos | 2026 +# Justfile - Credential Rotation Enforcer (cre) +# ============================================================================= + +set export +set shell := ["bash", "-uc"] +set windows-shell := ["powershell.exe", "-NoLogo", "-Command"] + +project := file_name(justfile_directory()) +version := `git describe --tags --always 2>/dev/null || echo "dev"` +binary := "bin/cre" +db_default := "sqlite:cre.db" +test_db_url := "postgres://cre_test:cre_test@localhost:5432/cre_test" + +# ============================================================================= +# Default +# ============================================================================= + +default: + @just --list --unsorted + +# ============================================================================= +# Build +# ============================================================================= + +[group('build')] +build: + shards build cre --release --no-debug + +[group('build')] +build-dev: + shards build cre + +[group('build')] +deps: + shards install + +[group('build')] +clean: + rm -rf bin lib .shards .crystal coverage tmp + +[group('build')] +rebuild: clean deps build + +# ============================================================================= +# Run (cre lifecycle) +# ============================================================================= + +[group('run')] +run db=db_default: + shards build cre && {{binary}} run --db={{db}} + +[group('run')] +watch db=db_default: + shards build cre && {{binary}} watch --db={{db}} + +[group('run')] +check db=":memory:": + shards build cre && {{binary}} check --db={{db}} + +[group('run')] +rotate ID db=db_default: + shards build cre && {{binary}} rotate {{ID}} --db={{db}} + +[group('run')] +audit-verify db=db_default: + shards build cre && {{binary}} audit verify --db={{db}} + +[group('run')] +policy-list: + shards build cre && {{binary}} policy list + +[group('run')] +policy-show name: + shards build cre && {{binary}} policy show {{name}} + +[group('run')] +export framework="soc2" out="evidence.zip" db=db_default: + shards build cre && {{binary}} export --framework={{framework}} --out={{out}} --db={{db}} + +# ============================================================================= +# Demos (Tier 1 / Tier 2 / Tier 3) +# ============================================================================= + +[group('demo')] +demo: + shards build cre && {{binary}} demo + +[group('demo')] +tui-demo seconds="8": + shards build cre && {{binary}} tui-demo --seconds={{seconds}} + +[group('demo')] +demo-full: + docker compose -f docker/docker-compose.yml up -d + @echo "Waiting for services to be healthy..." + @sleep 8 + shards build cre + @echo "" + @echo "Stack up. Daemon will run against Postgres on port 6022." + @echo "Press Ctrl+C to stop the daemon, then 'just demo-full-down' to tear down the stack." + @echo "" + DATABASE_URL=postgres://cre:cre@localhost:6022/cre \ + AWS_ENDPOINT=http://localhost:45666 \ + VAULT_ADDR=http://localhost:18201 \ + GITHUB_API_BASE=http://localhost:7115 \ + {{binary}} run --db=postgres://cre:cre@localhost:6022/cre + +[group('demo')] +demo-full-down: + docker compose -f docker/docker-compose.yml down -v + +[group('demo')] +demo-full-logs: + docker compose -f docker/docker-compose.yml logs -f --tail=50 + +[group('demo')] +demo-full-status: + docker compose -f docker/docker-compose.yml ps + +# ============================================================================= +# Test +# ============================================================================= + +[group('test')] +test: + crystal spec --order=random + +[group('test')] +test-unit: + crystal spec spec/unit --order=random + +[group('test')] +test-integration: + DATABASE_URL={{test_db_url}} crystal spec spec/integration --order=random + +[group('test')] +test-watch: + @echo "Watching spec/ for changes..." + @while true; do \ + inotifywait -qre close_write src/ spec/ 2>/dev/null && crystal spec --order=random; \ + done + +[group('test')] +coverage: + @echo "Coverage requires kcov. Skipping if not installed." + kcov --include-path=src coverage/ ./bin/cre || true + +# ============================================================================= +# Quality (format / lint) +# ============================================================================= + +[group('quality')] +format: + crystal tool format + +[group('quality')] +format-check: + crystal tool format --check + +[group('quality')] +lint: + @if [ -x ./bin/ameba ]; then \ + ./bin/ameba; \ + else \ + echo "ameba not installed (requires libpcre3-dev on Debian 13+); skipping lint"; \ + fi + +[group('quality')] +check-all: format-check lint test + +[group('quality')] +ci: check-all + +# ============================================================================= +# Database (Tier 2 helpers) +# ============================================================================= + +[group('db')] +db-up: + docker run -d --rm --name cre-pg -e POSTGRES_USER=cre_test -e POSTGRES_PASSWORD=cre_test -e POSTGRES_DB=cre_test -p 5432:5432 postgres:16 + +[group('db')] +db-down: + docker stop cre-pg 2>/dev/null || true + +[group('db')] +db-shell: + docker exec -it cre-pg psql -U cre_test cre_test + +# ============================================================================= +# Utility +# ============================================================================= + +[group('util')] +version: + @echo "{{project}} {{version}}" + +[group('util')] +loc: + @echo "Source LOC:" + @find src -name "*.cr" -exec wc -l {} \; | awk '{total+=$1} END{print " " total}' + @echo "Spec LOC:" + @find spec -name "*.cr" -exec wc -l {} \; | awk '{total+=$1} END{print " " total}' + @echo "Spec files: $(find spec -name '*_spec.cr' | wc -l)" + +[group('util')] +binary-info: + @ls -la {{binary}} 2>/dev/null || echo "binary not built; run 'just build'" + @file {{binary}} 2>/dev/null || true diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/learn/00-OVERVIEW.md b/PROJECTS/intermediate/credential-rotation-enforcer/learn/00-OVERVIEW.md new file mode 100644 index 00000000..92b5d363 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/learn/00-OVERVIEW.md @@ -0,0 +1,93 @@ + + +# Credential Rotation Enforcer - Overview + +A Crystal daemon that **tracks** credentials, **enforces** rotation policies as code, and **executes** the four-step rotation contract against AWS Secrets Manager, HashiCorp Vault, GitHub fine-grained PATs, and local `.env` files. Single binary. Live TUI. Bidirectional Telegram bot. Tamper-evident audit log. Signed compliance evidence export. + +## What This Project Demonstrates + +| Concept | What you'll see in the code | +|---|---| +| Statically-validated policy DSL | `policies/*.cr` evaluated by the Crystal compiler; single-symbol enum args (`enforce :rotate_immediately`) and `match {}` block typos fail `crystal build`. Splat-symbol args (`notify_via :telegram, :slack`) and missing required fields raise `BuilderError` at policy registration time. Either way, a misformed policy never reaches a running daemon. | +| Bus + plugin architecture | Typed events fan out across Crystal channels; subscribers (audit, TUI, Telegram, log) react independently; rotators register at compile time via `register_as :kind` macro | +| 4-step rotation contract | `generate -> apply -> verify -> commit`, dual-version safe (AWSCURRENT / AWSPENDING analog), with rollback on failure between apply and commit | +| Tamper-evident audit log | SHA-256 hash chain + ratcheting HMAC-SHA256 + Ed25519-signed Merkle batches (3 independent layers of integrity) | +| AEAD envelope encryption | AES-256-GCM with per-row DEKs wrapped by a KEK; AAD-bound to `tenant_id || credential_id || version_id`; reserved `algorithm_id` byte for crypto agility | +| Hand-rolled live TUI | ANSI escapes only (no `crysterm` dependency); event-driven repaints coalesced to a tick interval; works against any IO so it's testable | + +## Prerequisites + +- Crystal **1.20.0+** (see `https://crystal-lang.org/install/`) +- For Tier 1 demo: nothing else +- For Tier 2 demo: Docker + Docker Compose +- For Tier 3 (real cloud): AWS account, Vault server, GitHub Apps token + +## Three-Tier Demo Path + +Each tier teaches a different lesson. Run them in order to see the system evolve. + +### Tier 1 - Zero Deps + +``` +$ git clone && cd credential-rotation-enforcer +$ shards install && shards build cre +$ ./bin/cre demo +``` + +What you'll see: +- A temp `.env` file with `API_KEY=oldvalue-aaa` +- A simulated 60-day-old credential triggering policy violation +- Live narration of all 4 rotation steps +- The same `.env` file with a fresh random `API_KEY=...` value +- Audit chain verification confirming integrity + +Runtime: under 1 second. + +### Tier 2 - Docker Compose + +``` +$ just demo-full +``` + +Brings up: PostgreSQL 16, LocalStack (AWS Secrets Manager), HashiCorp Vault dev mode, a fake-GitHub Flask service. CRE connects to all four and rotates one credential through each rotator. Demonstrates real network calls, real auth (SigV4 to LocalStack, token to Vault, bearer to fake-GitHub), real persistence to Postgres, real append-only audit triggers. + +Setup time: ~2 minutes (mostly image pulls). + +### Tier 3 - Real Cloud + +`cre run` and `cre watch` refuse to start without two 32-byte secrets: + +``` +export CRE_HMAC_KEY_HEX=$(openssl rand -hex 32) # audit log seed key +export CRE_KEK_HEX=$(openssl rand -hex 32) # envelope KEK +export CRE_SIGNING_KEY_HEX=$(openssl rand -hex 32) # optional: enables Merkle-batch sealing +``` + +Then copy `config/demo-full.cr.example`, set the AWS / Vault / GitHub env vars it documents, and run `cre run` headless or `cre watch` for the live TUI. Without `CRE_SIGNING_KEY_HEX`, the daemon still runs but skips Layer 3 of the audit log — `cre audit verify` will skip the Merkle layer too. + +## Subcommand Cheat Sheet + +| Command | Purpose | +|---|---| +| `cre run` | Headless daemon (production / systemd) — requires `CRE_HMAC_KEY_HEX` + `CRE_KEK_HEX` | +| `cre watch` | Engine + live TUI in one process — same env requirements | +| `cre check` | One-shot policy eval, exit code by violations (CI-friendly) | +| `cre rotate ` | Manual rotation of a single credential — uses the same env-driven rotators as `cre run` | +| `cre policy list` | List compiled-in policies | +| `cre policy show ` | Inspect one policy in detail | +| `cre export --framework=soc2` | Generate signed compliance evidence ZIP | +| `cre audit verify` | Hash chain + HMAC ratchet (Merkle layer adds when `--public-key=PATH` or `CRE_AUDIT_PUBLIC_KEY_HEX`) | +| `cre verify-bundle ` | Offline re-verify of an evidence bundle (sha256 + manifest sig + chain + Merkle) | +| `cre demo` | Tier 1 zero-deps demo | +| `cre tui-demo` | 8-second TUI preview using synthetic events (no daemon, no DB) | +| `cre version` | Print version | + +## Where to Read Next + +- **Architecture** -> `02-ARCHITECTURE.md` (event bus, persistence, crypto layers) +- **Concepts** -> `01-CONCEPTS.md` (rotation theory, NIST/SOC2 framework controls, real breaches) +- **Code walkthrough** -> `03-IMPLEMENTATION.md` (key functions, where to make changes) +- **Extension ideas** -> `04-CHALLENGES.md` (add a 5th rotator, ML-KEM hybrid wrap, web UI) diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/learn/01-CONCEPTS.md b/PROJECTS/intermediate/credential-rotation-enforcer/learn/01-CONCEPTS.md new file mode 100644 index 00000000..132381dc --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/learn/01-CONCEPTS.md @@ -0,0 +1,99 @@ + + +# Concepts - Credential Rotation, in Practice and in History + +## Why credential rotation is its own discipline + +A credential is a fact in shared state: "this token authorizes this principal." The longer that fact stays in shared state, the more places it can leak from. Compromise has a half-life: every commit, every CI log, every laptop, every backup tape extends the radius. Rotation is the discipline of forcing the fact to expire on a schedule **shorter than the time-to-discover** of the leakage paths you can't see. + +The post-2020 industry consensus has shifted significantly: + +- **NIST SP 800-63B-4** (final July 2025): *prohibits* periodic password rotation for human credentials, BUT continues to require rotation for service accounts, API keys, machine identities. +- **NIST SP 800-57 Pt1 Rev5**: cryptoperiod-driven rotation per key type (DEKs, KEKs, signing keys, MACs). +- **PCI DSS v4.0.1** (mandatory March 2025): the 90-day rule still defaults; the "Customized Approach" off-ramp lets you replace it with continuous monitoring + risk-based rotation. +- **CA/Browser Forum SC-081v3**: TLS certificate lifetimes shrink to 47 days by 2029. + +So the practical answer in 2026 is not "rotate everything every 90 days" - it's **risk-based rotation** for human credentials, **cryptoperiod-driven rotation** for keys, and **JIT / ephemeral / workload-identity** for the highest-risk service-to-service paths. + +## Real breaches that motivated this design + +| Year | Incident | Root credential failure | +|---|---|---| +| 2020 | SolarWinds Sunburst | Service account token reused for ~9 months across attacker dwell | +| 2021 | Codecov bash uploader | One leaked GCS upload key, no rotation, 2 months of supply-chain access | +| 2022 | Heroku/Travis OAuth | OAuth tokens for npm reuse - no rotation, no scope reduction | +| 2023 | Storm-0558 (Microsoft) | MSA signing key generated 2016, never rotated, leaked via crash dump | +| 2023 | Okta support breach | HAR files containing session tokens - no exfil-detection, no token binding | +| 2024 | Snowflake / UNC5537 | Customer credentials leaked years prior, never rotated, no MFA | +| 2024 | Microsoft Midnight Blizzard | Legacy non-prod tenant test creds, never rotated | +| 2025 | tj-actions CVE-2025-30066 | GitHub Actions token theft via supply-chain action | + +The pattern repeats: **time** is the attacker's ally. Each row above had at least one credential that lived too long in shared state. + +## What this enforcer prevents (and doesn't) + +**Prevents:** +- Stale credentials living past their expected lifetime (policy violation -> notify or auto-rotate) +- Silent rotation drift (current-vs-DB-fingerprint detection) +- Forgetting to log a rotation (audit-log automatic via bus subscriber - the orchestrator can't bypass it) +- Audit-log tampering (3-layer integrity: chain + HMAC ratchet + Ed25519 batch signing) +- Unauthorized rotation triggers (Telegram bot ACL, CLI requires explicit credential ID) + +**Does NOT prevent:** +- Compromise of the KEK itself (use AWS KMS / HSM in production) +- Attacker who already exfiltrated a valid credential before rotation (rotate ASAP, but the fact already escaped) +- Insider running `cre rotate ` legitimately but with malicious intent (audit log captures it; doesn't stop it) +- DNS hijack of api.telegram.org (use webhooks with mTLS for hardened deployments) + +## The Four-Step Rotation Contract, Explained + +Borrowed verbatim from AWS Secrets Manager's Rotation Lambda template. The rule is: **between step 2 and step 4, both old AND new credentials are valid.** This is the dual-version safety guarantee. Concurrent consumers using either credential succeed; nobody crashes mid-rotation. + +``` + time --> + step 1 (generate) step 2 (apply) step 3 (verify) step 4 (commit) + | | | | + old: usable old: usable old: usable old: REVOKED + new: pending new: usable new: usable new: current + | | + +-- rollback OK --+ +--+--+ v + upstream pending verify failed? | irreversible + artifact deletable rollback_apply | + revokes new | + v + if verify passes, + proceed to commit +``` + +Step 4 is the only **irreversible** step. By design. If step 4 fails partially (commit succeeded for new but old wasn't actually revoked), the orchestrator marks the rotation `inconsistent` and surfaces an alert - we honestly tell you "this needs a human" rather than silently corrupting state. + +## Audit-log integrity, three layers deep + +| Layer | Mechanism | Defends against | +|---|---|---| +| **Hash chain** | Each row's `content_hash = SHA256(prev_hash || canonical_payload)` | Silent edits - any change breaks the forward chain | +| **HMAC ratchet** | Each row HMAC'd with key K_v; every 1024 rows derive K_{v+1} = HKDF(K_v, "ratchet") and zeroize K_v | An attacker who later gets DB write + current key still cannot rewrite past entries (the old key is gone) | +| **Ed25519 Merkle batches** | Hourly: build Merkle root over `content_hash` leaves; sign root with Ed25519 | Auditor can verify with **only the public key + the batches**, no DB access required | + +Verification is exposed as a CLI command: +``` +$ cre audit verify --public-key=/etc/cre/audit_pubkey.hex + ✓ hash chain: OK + ✓ HMAC ratchet: OK + ✓ Merkle batches: OK +✓ audit chain valid: 14892 entries +``` + +The HMAC ratchet replays from the seed key supplied via `CRE_HMAC_KEY_HEX`, so the verifier needs the *same* seed the writer used. Merkle batches are signed under `CRE_SIGNING_KEY_HEX` and verified with the matching public key — bundled in the `cre export` ZIP so an offline auditor can `cre verify-bundle` without DB access. + +## Compliance Framework Coverage + +The export bundle (`cre export --framework=soc2`) maps audit events to specific framework controls. Per `src/cre/compliance/control_mapping.cr`: + +- **SOC 2** - CC6.1 (logical access mgmt), CC6.6 (vulnerability mgmt), CC6.7 (access review), CC4.1 (monitoring), CC7.1 / CC7.2 (incident detection) +- **PCI DSS v4.0.1** - 8.3.9 / 8.6.3 (auth & rotation), 10.5.x (audit log integrity), 3.7.4 (key management) +- **ISO 27001:2022** - A.5.16 / A.5.17 / A.5.18 (identity & access), A.8.5 (secure auth), A.8.15 / A.8.16 (logging & monitoring), A.8.24 (cryptography) +- **HIPAA Security Rule** - 164.308(a)(5)(ii)(D) (password mgmt), 164.312(b) (audit controls) diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/learn/02-ARCHITECTURE.md b/PROJECTS/intermediate/credential-rotation-enforcer/learn/02-ARCHITECTURE.md new file mode 100644 index 00000000..34363075 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/learn/02-ARCHITECTURE.md @@ -0,0 +1,178 @@ + + +# Architecture + +## System overview + +``` +┌─────────────────────────────────────────────────────────────┐ +│ cre (single Crystal binary) │ +│ │ +│ ┌──────────────────────────────────────────────────────┐ │ +│ │ Event Bus │ │ +│ │ (typed Crystal channels) │ │ +│ └────┬─────┬─────┬─────┬─────┬─────┬─────┬────────────┘ │ +│ │ │ │ │ │ │ │ │ +│ ┌────▼─┐ ┌─▼──┐ ┌▼───┐ ┌▼──┐ ┌▼────┐ ┌──▼──┐ ┌──────┐ │ +│ │Sched │ │Rot.│ │Pol.│ │TUI│ │Tele.│ │Audit│ │Notify│ │ +│ │ulers │ │Reg │ │Eval│ │ │ │Bot │ │Log │ │ │ │ +│ └──┬───┘ └─┬──┘ └─┬──┘ └───┘ └─────┘ └──┬──┘ └──────┘ │ +│ │ │ │ │ │ +│ └───────┴──────┴─────────────────────┘ │ +│ │ │ +│ ┌────────▼─────────┐ │ +│ │ Persistence │ ◄── SQLite (Tier 1) │ +│ │ (PG / SQLite) │ ◄── PostgreSQL (T2/T3) │ +│ └──────────────────┘ │ +└─────────────────────────────────────────────────────────────┘ +``` + +All long-lived components are **fibers in one OS process**. The bus is in-process - Crystal channels are nanosecond-scale, so the architectural overhead is essentially free. + +## Components + +### Event Bus (`src/cre/engine/event_bus.cr`) + +Fanout dispatch via Crystal channels. Each subscriber gets its own bounded channel and chooses an overflow policy: + +| Subscriber | Overflow | Reason | +|---|---|---| +| `AuditSubscriber` | `Block` | Never drop audit events; compliance requirement | +| `Tui` | `Drop` | Stale UI is fine; can't block engine | +| `LogNotifier` | `Drop` | Best-effort structured logs | +| `TelegramSubscriber` | `Drop` (buffer 128) | Network-flaky anyway | +| `RotationWorker` | `Block` (buffer 32) | Must dispatch scheduled rotations | + +The dispatcher is a single fiber reading from the inbox channel and writing to subscriber channels. Both overflow modes use `select` so a stuck subscriber can't pin the bus indefinitely: + +- `Drop`: non-blocking `select … else …` — full buffer logs a warn and drops the event. +- `Block`: `select … when timeout(@block_send_timeout) …` — if a subscriber's buffer stays full past the timeout (default 5s), the bus drops that one event, logs the stall, and moves on. Operators tune the timeout up for slow downstreams they trust (audit DB writes) and down for unreliable ones. + +### Rotators (`src/cre/rotators/`) + +The abstract `Rotator` class exposes the four lifecycle methods plus `rollback_apply`. Concrete rotators self-register at compile time: + +```crystal +class AwsSecretsRotator < Rotator + register_as :aws_secretsmgr + ... +end +``` + +Adding a fifth rotator means dropping a single file in `src/cre/rotators/`. The macro hooks it into the registry at compile time. No central wiring to update. + +Rotators receive their cloud client through their constructor (DI). The CLI `run` command wires the right client based on env vars / config. + +### Persistence (`src/cre/persistence/`) + +Two adapters behind one interface: +- `Sqlite::SqlitePersistence` - single connection (`max_pool_size=1`) so SQLite's writer-serialization is safe; `synchronous=NORMAL`; `BEFORE UPDATE` and `BEFORE DELETE` triggers on `audit_events` raise `audit_events is append-only`. Application-level mutex for advisory-lock simulation (the abstraction is in-process only on SQLite). Used for Tier 1 demo. +- `Postgres::PostgresPersistence` - JSONB tags, `BIGSERIAL` audit seq, `audit_events_no_update` trigger refusing UPDATE/DELETE/TRUNCATE, `pg_advisory_xact_lock` for cross-process locking, and a partial unique index on `rotations(credential_id) WHERE state NOT IN ('completed','failed','aborted','inconsistent')` so two daemons can never insert overlapping in-flight rotations for the same credential. Used for Tier 2/3. + +Both backends share the same migration runner (`schema_migrations` table + version-tracked `Step` records), so adding a column is a one-line `Step.new(N, ["ALTER TABLE ..."])` instead of editing a soup of `IF NOT EXISTS`. The repo contracts (`CredentialsRepo`, `VersionsRepo`, `RotationsRepo`, `AuditRepo`) are identical between adapters; `Persistence` exposes `transaction(&)` and `with_advisory_lock(key, &)` so the rest of the system stays backend-agnostic. + +### Crypto layers (`src/cre/crypto/`, `src/cre/audit/`) + +``` ++--------------------+ +| Plaintext | ++--------------------+ + | + | AES-256-GCM(plain, DEK, AAD = tenant||cred||version, nonce 96b) + v ++--------------------+ +| ciphertext + tag | -> credential_versions.ciphertext ++--------------------+ + ++----+ +| DEK| (32 random bytes per row) ++----+ + | + | KEK_v.wrap(DEK) (envelope encryption) + v ++--------------------+ +| wrapped DEK | -> credential_versions.dek_wrapped + kek_version ++--------------------+ + +KEK source (per tier): + Tier 1: env var CRE_KEK_HEX (64-hex chars = 32 bytes) + Tier 2: AWS KMS via LocalStack + Tier 3: real AWS KMS or HSM +``` + +Per-row DEKs collapse the AES-GCM nonce-reuse birthday concern (each row's DEK encrypts exactly one message). AAD-binding prevents ciphertext-swap attacks where an attacker with DB write tries to swap a low-privilege row's ciphertext into a high-privilege row. + +`algorithm_id` is reserved for crypto agility: +- `0x01` = AES-256-GCM (today) +- `0x02` = XChaCha20-Poly1305 (long nonce, simpler) +- `0x03` = ML-KEM hybrid wrap (post-quantum forward secrecy) + +### Audit log integrity stack + +Three layers, increasingly hard to bypass: + +``` ++-------------------------------------------------+ +| Layer 3: Ed25519-signed Merkle batches | +| audit_batches table, hourly seal, signed | +| over (start_seq, end_seq, root) | +| Auditor verifies with public key only. | ++-------------------------------------------------+ + | + | leaves: content_hash[] + v ++-------------------------------------------------+ +| Layer 2: HMAC ratchet | +| K_v signs each row's content_hash; every | +| 1024 rows -> K_{v+1} = HKDF(K_v, "ratchet"); | +| K_v zeroized in memory | ++-------------------------------------------------+ + | + v ++-------------------------------------------------+ +| Layer 1: Hash chain | +| content_hash = SHA256(prev_hash || | +| canonical_payload) | +| rendering single-row tampering visible | ++-------------------------------------------------+ + | + v ++-------------------------------------------------+ +| PostgreSQL audit_events table | +| - INSERT-only role grant | +| - UPDATE/DELETE/TRUNCATE trigger refuses | ++-------------------------------------------------+ +``` + +The PG triggers are not strictly necessary (the chain catches tampering anyway), but they fail loud at write-time which is much friendlier for operators. SQLite tier 1 documents the relaxed guarantee. + +## Concurrency + +| Scope | Bound | Mechanism | +|---|---|---| +| Per-credential | 1 active rotation | `RotationWorker` checks `rotations.in_flight` before dispatching; PG also enforces a partial unique index so cross-process duplicates fail at the DB | +| Per-rotation lifecycle | 1 step at a time | Orchestrator runs `generate -> apply -> verify -> commit` sequentially; `rollback_apply` fires on apply/verify failure; commit failure marks the rotation `inconsistent` and raises a critical alert | +| Engine event bus | per-subscriber buffer + timeout | `EventBus#dispatch` uses `select` for both Block and Drop overflow (see Bus subscribers table above) | + +Crystal fibers + bounded channels = clean rate limiting without threads or locks. + +## Lifecycle (cre run) + +``` +1. Bootstrap: validate CRE_HMAC_KEY_HEX + CRE_KEK_HEX (hard-fail if missing) +2. Open persistence (PG or SQLite); migrate! (versioned Step list) +3. Build Envelope from KEK; build optional Ed25519Signer from CRE_SIGNING_KEY_HEX +4. Load compiled-in policies (REGISTRY) + register rotators from env vars +5. Start EventBus.run (dispatcher fiber) +6. Start subscribers: AuditSubscriber, LogNotifier, RotationWorker, PolicyEvaluator +7. Start Scheduler (SchedulerTick every CRE_TICK_SECONDS) +8. Start BatchSealerScheduler if signer present (default every 5min) +9. Wire Telegram bot if TELEGRAM_TOKEN + chat IDs are set +10. Optionally start TUI + Snapshotter (cre watch) +11. Block on stop_signal channel; SIGINT triggers graceful drain +``` + +Graceful shutdown: `engine.stop` publishes `ShutdownRequested` and waits up to 2s on `audit_subscriber.await_drain` — the audit subscriber sends on a private completion channel as soon as it processes that event, which proves it has handled everything queued before it. Then the bus closes its inbox and subscriber channels; each subscriber fiber exits on `Channel::ClosedError`. diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/learn/03-IMPLEMENTATION.md b/PROJECTS/intermediate/credential-rotation-enforcer/learn/03-IMPLEMENTATION.md new file mode 100644 index 00000000..e12a1d09 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/learn/03-IMPLEMENTATION.md @@ -0,0 +1,158 @@ + + +# Implementation Walkthrough + +This document points you at the most important code paths. Read it with `tree src/` open in another window. + +## The Policy DSL (statically- and registration-time validated) + +`src/cre/policy/dsl.cr` declares the DSL inside `module CRE::Policy::Dsl`. Consumers opt in explicitly: + +```crystal +require "cre/policy/dsl" +include CRE::Policy::Dsl + +policy "production-aws-secrets" do + match { |c| c.kind.aws_secretsmgr? && c.tag(:env) == "prod" } + max_age 30.days + enforce :rotate_immediately + notify_via :telegram, :structured_log +end +``` + +`with builder yield` makes every Builder method callable receiver-less inside the block. Two flavors of typo-detection apply: + +- **Compile time** — `enforce :rotate_immediatly` (single Symbol arg → `Action` enum) is rejected by Crystal's autocast. `match { |c| c.kund }` (typo on a Credential getter) breaks compilation pointing at the policy file. +- **Registration time** — `notify_via :telegrm, :slak` uses a splat-Symbol overload that runs `Channel.parse?` on each value and raises `BuilderError("unknown channel 'telegrm' in policy ''")` when the file is loaded. Splat autocast doesn't reach into Symbols, so this layer is the next-best thing. + +`Builder#build` also raises `BuilderError` on missing required fields (`matcher`, `max_age`, `enforce_action`). Either way, a misformed policy never reaches a running daemon. + +## The Event Bus (fanout via Crystal channels) + +`src/cre/engine/event_bus.cr` exposes `subscribe(buffer:, overflow:)` returning a `Channel(Event)`. The `run` method spawns a single dispatcher fiber that reads from `@inbox` and forwards to each subscriber's channel. + +`dispatch` uses Crystal's `select` for both overflow modes: +- `Drop` — `select … else` drops the event when the buffer is full and logs a warn. +- `Block` — `select … when timeout(@block_send_timeout)` waits up to `@block_send_timeout` (default 5s) and only then drops, logging the stall. This isolates the bus from a stuck subscriber: head-of-line blocking is bounded. + +## The Rotator Plugin Registration + +`src/cre/rotators/rotator.cr` declares an abstract base with a class-level `REGISTRY = {} of Symbol => Rotator.class`. The macro `register_as` populates this at compile time: + +```crystal +abstract class Rotator + REGISTRY = {} of Symbol => Rotator.class + + macro register_as(kind) + ::CRE::Rotators::Rotator::REGISTRY[{{ kind }}] = self + end +end +``` + +When a file like `src/cre/rotators/aws_secrets.cr` is required, the `register_as :aws_secretsmgr` line runs at *compile time* and the class shows up in `Rotator::REGISTRY[:aws_secretsmgr]`. No central list to maintain. + +## The 4-step Orchestrator + +`src/cre/engine/rotation_orchestrator.cr` runs the contract: + +``` +generate -> rotator-specific (often produces the new value + cloud version_id) +apply -> rotator-specific (often no-op for cloud rotators where generate already exposed) +verify -> read back, byte-equal check +commit -> promote new -> AWSCURRENT, demote old -> AWSPREVIOUS +``` + +Each step publishes `RotationStepStarted` and either `RotationStepCompleted` or `RotationStepFailed` to the bus. + +Failure handling has two regimes: + +- **apply or verify fails** — `rotator.rollback_apply(c, new_secret)` reverses the cloud-side mutation; rotation moves to `Failed`; bus emits `RotationStepFailed` + `RotationFailed`. +- **commit fails** — partial cross-call commit sequences (e.g., AWS `UpdateSecretVersionStage` 5xx half-way through) cannot be reliably reversed client-side. The rotation transitions to `Inconsistent` (a terminal state distinct from `Failed`), and the orchestrator emits a critical `AlertRaised` so operators know to intervene. + +Success path is now the heavyweight one: when the four steps complete, the orchestrator +1. seals `new_secret.ciphertext` with the optional `Crypto::Envelope` (AES-256-GCM, AAD = `cred=|kind=`), +2. inserts a `credential_versions` row with the wrapped DEK + KEK version, +3. updates the credential row to bump `last_rotated_at`, set `current_version_id` to the new version's id, and demote the old one to `previous_version_id`. + +That last step is what stops the policy evaluator from re-scheduling the same rotation on every tick — `Policy#overdue?` keys on `c.rotation_anchor` (which is `last_rotated_at || created_at`), not on `updated_at`. + +The orchestrator never directly calls audit. Audit happens automatically because `AuditSubscriber` is on the bus listening for these exact event types — the orchestrator can't forget to log. And because the orchestrator's path is the only path that runs `versions.insert` + `credentials.update`, persistence-side state stays consistent with the audit-log narrative. + +## SigV4 Signer (the AWS-flavored work) + +`src/cre/aws/signer.cr` implements RFC-style AWS SigV4: + +``` +canonical_request = method + canonical_uri + canonical_query + + canonical_headers + signed_headers + payload_hash +string_to_sign = "AWS4-HMAC-SHA256\n" + amz_date + "\n" + + credential_scope + "\n" + sha256(canonical_request) +signing_key = HMAC chain (kSecret -> kDate -> kRegion -> kService -> kSigning) +signature = HMAC(signing_key, string_to_sign) +``` + +The `Authorization` header is built from `algorithm + Credential=... + SignedHeaders=... + Signature=...`. Includes `X-Amz-Security-Token` when an STS session token is supplied. + +Two test files cover the signer: +- `spec/unit/aws/signer_spec.cr` — idempotence + Authorization-header regex shape. +- `spec/unit/aws/signer_aws_vector_spec.cr` — uses the AWS reference suite's `get-vanilla` inputs (access key, secret, region, service, fixed timestamp) and locks in a regression vector for the exact signature our signer produces. Because we always emit `X-Amz-Content-SHA256` (required by Secrets Manager and other JSON-protocol services), the signed-headers list is `host;x-amz-content-sha256;x-amz-date` — slightly different from AWS's vanilla vector, so we lock in our own bytes rather than match theirs. Any future change to canonicalization, key derivation, or header ordering trips the test. + +## Audit Log Integrity (three-layer) + +`src/cre/audit/audit_log.cr` writes Layers 1 + 2 on every `append`: +- `latest_hash` from the DB (genesis = 32 zero bytes for an empty log) +- `content_hash = HashChain.next_hash(prev_hash, canonical_payload)` +- `hmac = HmacRatchet#sign(content_hash)`; ratchet rolls every 1024 rows +- All three columns plus `hmac_key_version` get persisted in one `INSERT` per row + +Verification is split into three independently-callable methods: +- `verify_hash_chain` — walks every entry, recomputes `SHA256(prev_hash || payload)`, compares against `content_hash`. +- `verify_hmac_ratchet(seed_key)` — replays the ratchet from the seed `CRE_HMAC_KEY_HEX`, recomputes each row's HMAC against `content_hash`, and checks `hmac_key_version` matches the ratchet's view of where rotation should be. Catches an attacker who fixed up the hash chain but doesn't have the seed. +- `verify_batches(verifier)` — for every row in `audit_batches`, refetch the corresponding `content_hash` leaves, recompute the Merkle root, then verify the Ed25519 signature over `(start_seq, end_seq, root)`. + +`src/cre/audit/batch_sealer.cr` builds Layer 3 entries: +- Walk new audit_events since `last_sealed_seq` +- Build a Merkle tree (`Merkle.root`) over each row's `content_hash` +- Sign `(start_seq, end_seq, root)` with Ed25519 via `Signing::Ed25519Signer` +- Insert into `audit_batches` + +`src/cre/audit/batch_sealer_scheduler.cr` is the fiber that actually drives the sealer in `cre run` / `cre watch`: it calls `seal_pending` once on start, again every `CRE_SEAL_INTERVAL_SECONDS` (default 300s), and once more on shutdown. Every successful seal publishes a typed `AuditBatchSealed` event, which the audit subscriber writes back into the audit log under `audit.batch.sealed` — closing the loop with the SOC 2 / PCI-DSS / ISO / HIPAA control mapping that already keys on that event type. + +Crystal's stdlib OpenSSL doesn't expose Ed25519 high-level wrappers, so `src/cre/audit/signing.cr` reaches into LibCrypto via FFI: `EVP_PKEY_new_raw_private_key`, `EVP_DigestSign`, etc. Public-key verification is symmetrical: `Ed25519Verifier#verify(message, signature)`. + +## AEAD Envelope Encryption + +`src/cre/crypto/aead.cr` does AES-256-GCM via LibCrypto FFI (stdlib `OpenSSL::Cipher` doesn't expose `auth_data=` / `auth_tag` for GCM). The envelope (`src/cre/crypto/envelope.cr`) generates a 32-byte DEK per row, encrypts plaintext with AES-256-GCM(plaintext, DEK, AAD), then wraps the DEK with KEK using a separate AEAD (with its own AAD `kek-wrap|v`). Both ciphertexts are `nonce(12) || tag(16) || body`. + +Decrypting requires the KEK to unwrap the DEK, then the DEK + AAD to decrypt the payload. AAD mismatch fails tag verification at the inner layer; KEK version mismatch fails at unwrap. + +## TUI + +`src/cre/tui/state.cr` holds a rolling view of active rotations + recent events. `apply(ev)` is the single entry point that mutates state; pure update logic, easy to test. + +`src/cre/tui/renderer.cr` paints the four panels to any IO. ANSI escapes via `src/cre/tui/ansi.cr` (stdlib only). The renderer's `pad` helper accounts for ANSI escape widths so column alignment is correct under colors. + +`src/cre/tui/tui.cr` ties it together: subscribes to the bus (Drop overflow), spawns a tick fiber + an event fiber, both calling `maybe_render` which throttles to `refresh_interval`. + +## Telegram Bot + +`src/cre/notifiers/telegram.cr` is a thin HTTP::Client wrapper for the Telegram Bot API (no tourmaline dependency for the notification path). Errors get the bot token redacted before they hit logs — Telegram requires the token in the URL path, so the redaction is best-effort, but it stops the obvious leak. + +`src/cre/notifiers/telegram_bot.cr` does long-poll `getUpdates` and dispatches commands. Auth is by chat-ID allowlist; viewer tier (`/status`, `/queue`, `/history`, `/alerts`) is read-only; operator tier adds `/rotate`. `/rotate ` publishes `RotationScheduled` to the bus, which the `RotationWorker` consumes (see `src/cre/engine/rotation_worker.cr`) — the worker resolves the credential, looks up the right `Rotator` from the env-driven dispatch table, checks `rotations.in_flight` to dedupe, and hands off to `RotationOrchestrator`. + +## Persistence Layer Shape + +`src/cre/persistence/repos.cr` declares the abstract repos (`CredentialsRepo`, `VersionsRepo`, `RotationsRepo`, `AuditRepo`) and the record types (`RotationRecord`, `AuditEntry`, `AuditBatch`, plus the `RotatorKind` and `RotationState` enums). `RotationState::Inconsistent` is included in `TERMINAL_STATES` alongside `Completed` / `Failed` / `Aborted`. + +Both adapters apply schema changes through `Migrations::Step` records keyed on a monotonic `version`. The `schema_migrations` table tracks which versions have run; new alterations land as new `Step.new(N, ["ALTER TABLE ..."])` entries instead of editing the soup of `IF NOT EXISTS` statements. + +`audit_events` is the most carefully guarded table in the schema: +- Postgres has the original `audit_events_no_update` trigger (raises `audit_events is append-only` on UPDATE/DELETE/TRUNCATE). +- SQLite gets parity via two `BEFORE UPDATE` / `BEFORE DELETE` triggers using `RAISE(ABORT, '...')`. +- The repo's `INSERT` no longer uses `OR IGNORE` / `ON CONFLICT … DO NOTHING`, so a constraint failure raises into the application instead of silently dropping. +- The audit subscriber's rescue path publishes a critical `AlertRaised` and (by default) panics the process via `CRE_AUDIT_FAILURE_MODE=panic`. + +Two independent layers; both must be subverted to forge history. diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/learn/04-CHALLENGES.md b/PROJECTS/intermediate/credential-rotation-enforcer/learn/04-CHALLENGES.md new file mode 100644 index 00000000..845605e4 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/learn/04-CHALLENGES.md @@ -0,0 +1,53 @@ + + +# Extension Challenges + +Pick one and ship it as a PR. + +## Beginner + +### 1. Add a fifth rotator: PostgreSQL `ALTER USER` +A new file `src/cre/rotators/postgres_user.cr` that rotates a Postgres role's password directly via `ALTER USER ... PASSWORD ...`. Use the existing 4-step contract; verify by opening a fresh connection with the new password. Drop the file in - the macro registers it automatically. Add unit specs in `spec/unit/rotators/postgres_user_spec.cr`. + +### 2. Slack notifier subscriber +Mirror `TelegramSubscriber` against Slack's `chat.postMessage`. Add chat ID allowlist, channel-id parameterization, and message formatting. Single new file in `src/cre/notifiers/`. + +### 3. Add `notify_via :slack` to the Channel enum +Once you have a Slack notifier, add `Slack` to `Channel` in `src/cre/policy/policy.cr`, dispatch on it in the evaluator, and write a policy in `policies/` that uses it. + +## Intermediate + +### 4. Web dashboard via SSE +Add `src/cre/web/` with a Lucky/Kemal HTTP server that subscribes to the bus and pushes events as Server-Sent Events to an HTMX dashboard. Reuse `Tui::State` as the data model - it already has the right shape. The point of the bus + plugin architecture is that this is a *new subscriber*, not a rewrite. + +### 5. ML-KEM hybrid wrap for KEK +Add `algorithm_id = 0x03` to envelope encryption: hybrid Curve25519 + ML-KEM-768 (Kyber) for the DEK wrap. Provides forward secrecy against future quantum-attack on captured ciphertexts. Note: ML-KEM is in OpenSSL 3.x; you may need to update LibCrypto FFI bindings. + +### 6. OpenTimestamps anchoring +Anchor each `audit_batches` Merkle root to the Bitcoin blockchain via OpenTimestamps. Adds a fourth integrity layer: even if the entire DB and signing key are compromised, an offline auditor with a Bitcoin full node can verify when each batch existed. Update `src/cre/audit/batch_sealer.cr` to publish OTS proofs alongside Ed25519 signatures. + +## Advanced + +### 7. SPIFFE/SPIRE workload identity rotator +Add a rotator that *replaces* static credentials with SPIFFE SVIDs (X.509 + JWT). Demonstrates the post-2024 industry shift away from rotation entirely toward attestation-based ephemeral identity. Touch points: new client in `src/cre/spiffe/`, new rotator in `src/cre/rotators/spiffe.cr`, new credential kind in `src/cre/domain/credential.cr`. + +### 8. Crash recovery state machine +The orchestrator already marks commit-step failures as `Inconsistent` and emits a critical alert, so single-step partial failures surface loudly. What's still missing is the *boot-time* recovery sweep: if the daemon was killed between, say, a successful `apply` and the start of `verify`, the `rotations` row is left in `Verifying` state with no fiber driving it forward. Implement the recovery protocol: on boot, scan `rotations` for non-terminal states; for each, decide based on `(rotator_kind, last_step)` whether to invoke `rollback_apply`, retry from the failed step, or transition to `Inconsistent`. Add `src/cre/engine/recovery.cr` with explicit state-machine semantics, wire it into `Engine#start`, and add a SQL fixture spec in `spec/unit/engine/recovery_spec.cr` that builds each kind of "stale" row and asserts the right outcome. + +### 9. Multi-tenant support +Wire `tenant_id` end-to-end: a new migration adds the column on `credentials` / `credential_versions` / `rotations` / `audit_events`; the AAD construction in `RotationOrchestrator#persist_credential_version` extends to `cred=|kind=|tenant=`; policy matchers gain `c.tenant == "tenant-x"`; and Postgres row-level security policies enforce isolation at the DB level. The biggest design decision: per-tenant KEKs (each tenant rotates independently, but bootstrap juggles N keys) vs shared KEK with tenant-bound DEKs (simpler config, the AAD does the isolation work). + +### 10. JIT credential broker +Replace the rotation contract entirely for some credential types: instead of rotating, *issue* a fresh ephemeral credential on each access (5-15 minute TTL). Requires a new `Broker` abstraction alongside `Rotator`, integration with AWS STS / GCP service account impersonation / Vault dynamic, and consumer-side token refresh logic in the example apps. + +## Evaluation rubric (for self-review) + +A great extension PR: +- Has unit tests in `spec/unit//` mirroring the source layout +- Has a focused commit message explaining the *why*, not just the *what* +- Doesn't break existing tests (`crystal spec spec/` should be green) +- Adds 1-3 file-level changes; if it touches more than 5 files, the abstraction is probably wrong +- Surfaces failure modes honestly (e.g., the JIT broker should clearly document the consumer-side complexity it shifts) diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/scripts/install.sh b/PROJECTS/intermediate/credential-rotation-enforcer/scripts/install.sh new file mode 100755 index 00000000..74c74822 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/scripts/install.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# ©AngelaMos | 2026 +# install.sh + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +INSTALL_PREFIX="${INSTALL_PREFIX:-/usr/local}" + +bold() { printf "\033[1m%s\033[0m\n" "$*"; } +green() { printf "\033[32m%s\033[0m\n" "$*"; } +yellow() { printf "\033[33m%s\033[0m\n" "$*"; } +red() { printf "\033[31m%s\033[0m\n" "$*"; } + +bold "Credential Rotation Enforcer - install.sh" + +# 1) Crystal +if ! command -v crystal >/dev/null 2>&1; then + yellow "Crystal not found. Install instructions: https://crystal-lang.org/install/" + yellow "Or, on Linux:" + yellow " curl -fsSL https://crystal-lang.org/install.sh | sudo bash" + yellow "Or, on macOS:" + yellow " brew install crystal" + exit 1 +fi +crystal_version=$(crystal --version | head -1 | awk '{print $2}') +green "Crystal $crystal_version found" + +# 2) System deps (libpcre2 for regex, libssl for crypto) +case "$(uname -s)" in + Linux) + if ! ldconfig -p 2>/dev/null | grep -q libpcre2-8; then + yellow "libpcre2 not detected. On Debian/Ubuntu: sudo apt-get install -y libpcre2-dev" + yellow "On Alpine: apk add pcre2-dev" + fi + ;; + Darwin) + : # macOS bundles what's needed + ;; +esac + +cd "$PROJECT_ROOT" + +# 3) Shards +bold "Resolving shard dependencies..." +shards install +green "shards installed" + +# 4) Build +bold "Building cre (release mode)..." +shards build cre --release +green "cre binary built at bin/cre ($(stat -c %s bin/cre 2>/dev/null || stat -f %z bin/cre) bytes)" + +# 5) Optional install to PATH +if [ "${INSTALL_TO_PATH:-0}" = "1" ]; then + bold "Installing to ${INSTALL_PREFIX}/bin/cre" + if [ -w "${INSTALL_PREFIX}/bin" ]; then + cp bin/cre "${INSTALL_PREFIX}/bin/cre" + else + sudo cp bin/cre "${INSTALL_PREFIX}/bin/cre" + fi + green "Installed: $(which cre)" +fi + +bold "" +bold "Try the zero-deps demo:" +echo " ./bin/cre demo" +bold "" +bold "Or start the daemon:" +echo " ./bin/cre run --db=sqlite:cre.db" +bold "" +bold "See learn/00-OVERVIEW.md for the full walkthrough." diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/shard.lock b/PROJECTS/intermediate/credential-rotation-enforcer/shard.lock new file mode 100644 index 00000000..4da0ce31 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/shard.lock @@ -0,0 +1,33 @@ +version: 2.0 +shards: + db: + git: https://github.com/crystal-lang/crystal-db.git + version: 0.11.0 + + html5: + git: https://github.com/naqvis/crystal-html5.git + version: 0.4.0 + + http_proxy: + git: https://github.com/mamantoha/http_proxy.git + version: 0.14.0+git.commit.5a02af05c5531c639efdf651431a86ec90905f71 + + pg: + git: https://github.com/will/crystal-pg.git + version: 0.26.0 + + sqlite3: + git: https://github.com/crystal-lang/crystal-sqlite3.git + version: 0.19.0 + + tourmaline: + git: https://github.com/protoncr/tourmaline.git + version: 0.28.0 + + webmock: + git: https://github.com/manastech/webmock.cr.git + version: 0.14.0 + + xpath2: + git: https://github.com/naqvis/crystal-xpath2.git + version: 0.2.0 diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/shard.yml b/PROJECTS/intermediate/credential-rotation-enforcer/shard.yml new file mode 100644 index 00000000..0afcc30e --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/shard.yml @@ -0,0 +1,35 @@ +# ©AngelaMos | 2026 +# shard.yml + +name: cre +version: 0.1.0 +description: | + Credential Rotation Enforcer - tracks and enforces credential rotation + policies across cloud secret managers, vaults, and developer tooling. +authors: + - Carter Perez +license: MIT +crystal: ">= 1.20.0" + +targets: + cre: + main: src/cre.cr + +dependencies: + db: + github: crystal-lang/crystal-db + version: ~> 0.9 + pg: + github: will/crystal-pg + version: ~> 0.9 + sqlite3: + github: crystal-lang/crystal-sqlite3 + version: ~> 0.9 + tourmaline: + github: protoncr/tourmaline + version: ~> 0.28 + +development_dependencies: + webmock: + github: manastech/webmock.cr + version: ~> 0.9 diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/fixtures/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/fixtures/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/fixtures/policies/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/fixtures/policies/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/aws/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/aws/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/demo/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/demo/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/demo/tier_1_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/demo/tier_1_spec.cr new file mode 100644 index 00000000..9e472330 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/demo/tier_1_spec.cr @@ -0,0 +1,22 @@ +# =================== +# ©AngelaMos | 2026 +# tier_1_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/demo/tier_1" + +describe CRE::Demo::Tier1 do + it "runs end-to-end and reports rotation success" do + io = IO::Memory.new + code = CRE::Demo::Tier1.run(io) + code.should eq 0 + + out = CRE::Tui::Ansi.strip(io.to_s) + out.should contain "Tier 1 demo" + out.should contain "BEFORE" + out.should contain "AFTER" + out.should contain "rotation completed" + out.should contain "audit events, hash chain valid" + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/engine/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/engine/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/persistence/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/persistence/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/persistence/postgres_persistence_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/persistence/postgres_persistence_spec.cr new file mode 100644 index 00000000..0308d4a8 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/persistence/postgres_persistence_spec.cr @@ -0,0 +1,100 @@ +# =================== +# ©AngelaMos | 2026 +# postgres_persistence_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/persistence/postgres/postgres_persistence" + +DATABASE_URL = ENV["DATABASE_URL"]? || "postgres://cre_test:cre_test@localhost:5433/cre_test" + +private def fresh_persistence : CRE::Persistence::Postgres::PostgresPersistence + persist = CRE::Persistence::Postgres::PostgresPersistence.new(DATABASE_URL) + persist.migrate! + persist.db.exec("TRUNCATE credentials, credential_versions, rotations CASCADE") + persist.db.exec("ALTER TABLE audit_events DISABLE TRIGGER audit_events_no_update") + persist.db.exec("DELETE FROM audit_events") + persist.db.exec("ALTER TABLE audit_events ENABLE TRIGGER audit_events_no_update") + persist.db.exec("DELETE FROM audit_batches") + persist +end + +describe CRE::Persistence::Postgres::PostgresPersistence do + it "round-trips a credential through PG" do + persist = fresh_persistence + + c = CRE::Domain::Credential.new( + id: UUID.random, + external_id: "pg-1", + kind: CRE::Domain::CredentialKind::AwsSecretsmgr, + name: "pg-test", + tags: {"env" => "prod", "team" => "platform"} of String => String, + ) + persist.credentials.insert(c) + found = persist.credentials.find(c.id).not_nil! + found.name.should eq "pg-test" + found.tag("env").should eq "prod" + found.tag("team").should eq "platform" + ensure + persist.try(&.close) + end + + it "stores and retrieves binary credential versions" do + persist = fresh_persistence + + cred = CRE::Domain::Credential.new( + id: UUID.random, external_id: "pg-bin", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + ) + persist.credentials.insert(cred) + + bytes = Bytes.new(64) { |i| i.to_u8 } + v = CRE::Domain::CredentialVersion.new( + id: UUID.random, credential_id: cred.id, + ciphertext: bytes, dek_wrapped: Bytes[0xde, 0xad, 0xbe, 0xef], + kek_version: 7, algorithm_id: 1_i16, + metadata: {"version_id" => "abc"}, + ) + persist.versions.insert(v) + found = persist.versions.find(v.id).not_nil! + found.ciphertext.should eq bytes + found.dek_wrapped.should eq Bytes[0xde, 0xad, 0xbe, 0xef] + found.kek_version.should eq 7 + found.metadata["version_id"].should eq "abc" + ensure + persist.try(&.close) + end + + it "audit_events trigger refuses UPDATE" do + persist = fresh_persistence + + entry = CRE::Persistence::AuditEntry.new( + seq: 0_i64, event_id: UUID.random, occurred_at: Time.utc, + event_type: "test", actor: "system", target_id: nil, + payload: %({"k":"v"}), + prev_hash: Bytes.new(32, 0_u8), + content_hash: Bytes.new(32, 0xaa_u8), + hmac: Bytes.new(32, 0xbb_u8), + hmac_key_version: 1, + ) + persist.audit.append(entry) + + expect_raises(Exception, /append-only/) do + persist.db.exec("UPDATE audit_events SET event_type = 'forged' WHERE seq = 1") + end + ensure + persist.try(&.close) + end + + it "advisory lock holds across the block" do + persist = fresh_persistence + counter = 0 + persist.with_advisory_lock(42_i64) do + counter += 1 + end + counter.should eq 1 + ensure + persist.try(&.close) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/rotators/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/rotators/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/tui/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/tui/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/vault/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/integration/vault/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/spec_helper.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/spec_helper.cr new file mode 100644 index 00000000..0b70b0dd --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/spec_helper.cr @@ -0,0 +1,7 @@ +# =================== +# ©AngelaMos | 2026 +# spec_helper.cr +# =================== + +require "spec" +require "../src/cre" diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/audit_log_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/audit_log_spec.cr new file mode 100644 index 00000000..ea09a298 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/audit_log_spec.cr @@ -0,0 +1,83 @@ +# =================== +# ©AngelaMos | 2026 +# audit_log_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/audit/audit_log" +require "../../../src/cre/persistence/sqlite/sqlite_persistence" + +describe CRE::Audit::AuditLog do + it "appends and reads back entries with valid hash chain" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, 1024) + + log.append("rotation.completed", "system", nil, {"x" => "y"}) + log.append("policy.violation", "system", nil, {"a" => "b"}) + + persist.audit.latest_seq.should eq 2_i64 + log.verify_chain.should be_true + ensure + persist.try(&.close) + end + + it "verify_chain detects when a row is tampered in DB directly" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, 1024) + + log.append("a", "s", nil, {"k" => "v"}) + log.append("b", "s", nil, {"k" => "v2"}) + + # The append-only trigger blocks tampering in the live DB; drop it + # for this test so we can exercise the verify_chain code path against + # a forced inconsistency. + persist.db.exec("DROP TRIGGER audit_events_no_update") + persist.db.exec("UPDATE audit_events SET payload = ? WHERE seq = 2", %({"event_type":"b","actor":"s","target_id":null,"payload":{"k":"BAD"}})) + + log.verify_chain.should be_false + ensure + persist.try(&.close) + end + + it "append-only triggers exist on audit_events (SQLite)" do + # The crystal-sqlite3 driver caches prepared statements at the connection + # level; a failed UPDATE leaves the cached statement in error state and the + # error re-surfaces at connection close, which conflates 'expect_raises' + # bookkeeping. We verify the trigger by inspecting sqlite_master directly. + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + triggers = persist.db.query_all( + "SELECT name FROM sqlite_master WHERE type='trigger' AND tbl_name='audit_events'", + as: String, + ) + triggers.should contain "audit_events_no_update" + triggers.should contain "audit_events_no_delete" + ensure + persist.try(&.close) + end + + it "verify_chain returns true on empty log" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, 1024) + log.verify_chain.should be_true + ensure + persist.try(&.close) + end + + it "ratchets version after configured threshold" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, ratchet_every: 2) + + log.append("a", "s", nil, {"i" => "1"}) + log.append("a", "s", nil, {"i" => "2"}) + log.ratchet_version.should eq 1 + log.append("a", "s", nil, {"i" => "3"}) + log.ratchet_version.should eq 2 + ensure + persist.try(&.close) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/batch_sealer_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/batch_sealer_spec.cr new file mode 100644 index 00000000..d1f1e2e0 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/batch_sealer_spec.cr @@ -0,0 +1,73 @@ +# =================== +# ©AngelaMos | 2026 +# batch_sealer_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/audit/audit_log" +require "../../../src/cre/audit/batch_sealer" +require "../../../src/cre/audit/signing" +require "../../../src/cre/persistence/sqlite/sqlite_persistence" + +describe CRE::Audit::BatchSealer do + it "seals pending audit events into a signed Merkle batch" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, 1024) + log.append("a", "s", nil, {"i" => "1"}) + log.append("b", "s", nil, {"i" => "2"}) + log.append("c", "s", nil, {"i" => "3"}) + + kp = CRE::Audit::Signing::Ed25519Keypair.generate(version: 1) + signer = CRE::Audit::Signing::Ed25519Signer.from_keypair(kp) + sealer = CRE::Audit::BatchSealer.new(persist, signer) + + batch = sealer.seal_pending.not_nil! + batch.start_seq.should eq 1_i64 + batch.end_seq.should eq 3_i64 + batch.signing_key_version.should eq 1 + batch.merkle_root.size.should eq 32 + batch.signature.size.should eq 64 + + verifier = CRE::Audit::Signing::Ed25519Verifier.new(kp.public_key) + msg = CRE::Audit::BatchSealer.pack_message(batch.start_seq, batch.end_seq, batch.merkle_root) + verifier.verify(msg, batch.signature).should be_true + + persist.audit.last_sealed_seq.should eq 3_i64 + ensure + persist.try(&.close) + end + + it "returns nil when nothing pending" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + + kp = CRE::Audit::Signing::Ed25519Keypair.generate + signer = CRE::Audit::Signing::Ed25519Signer.from_keypair(kp) + sealer = CRE::Audit::BatchSealer.new(persist, signer) + sealer.seal_pending.should be_nil + ensure + persist.try(&.close) + end + + it "subsequent seal covers only new events" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, 1024) + kp = CRE::Audit::Signing::Ed25519Keypair.generate + signer = CRE::Audit::Signing::Ed25519Signer.from_keypair(kp) + sealer = CRE::Audit::BatchSealer.new(persist, signer) + + log.append("a", "s", nil, {"i" => "1"}) + log.append("b", "s", nil, {"i" => "2"}) + sealer.seal_pending.not_nil!.end_seq.should eq 2_i64 + + log.append("c", "s", nil, {"i" => "3"}) + second = sealer.seal_pending.not_nil! + second.start_seq.should eq 3_i64 + second.end_seq.should eq 3_i64 + ensure + persist.try(&.close) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/hash_chain_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/hash_chain_spec.cr new file mode 100644 index 00000000..278a087f --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/hash_chain_spec.cr @@ -0,0 +1,63 @@ +# =================== +# ©AngelaMos | 2026 +# hash_chain_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/audit/hash_chain" + +describe CRE::Audit::HashChain do + it "first hash is 32 zero bytes" do + g = CRE::Audit::HashChain.genesis + g.size.should eq 32 + g.all? { |b| b == 0_u8 }.should be_true + end + + it "next_hash is deterministic" do + prev = CRE::Audit::HashChain.genesis + payload = "hello".to_slice + a = CRE::Audit::HashChain.next_hash(prev, payload) + b = CRE::Audit::HashChain.next_hash(prev, payload) + a.should eq b + a.size.should eq 32 + end + + it "different prev produces different hash" do + payload = "x".to_slice + a = CRE::Audit::HashChain.next_hash(Bytes.new(32, 0_u8), payload) + b = CRE::Audit::HashChain.next_hash(Bytes.new(32, 1_u8), payload) + a.should_not eq b + end + + it "different payload produces different hash" do + prev = CRE::Audit::HashChain.genesis + a = CRE::Audit::HashChain.next_hash(prev, "a".to_slice) + b = CRE::Audit::HashChain.next_hash(prev, "b".to_slice) + a.should_not eq b + end + + it "verify_chain detects tampering" do + pairs = [] of {Bytes, Bytes} + h = CRE::Audit::HashChain.genesis + payloads = ["a", "b", "c", "d"].map(&.to_slice) + payloads.each do |p| + next_h = CRE::Audit::HashChain.next_hash(h, p) + pairs << {h, next_h} + h = next_h + end + + CRE::Audit::HashChain.verify(pairs, payloads).should be_true + + tampered = payloads.dup + tampered[2] = "BAD".to_slice + CRE::Audit::HashChain.verify(pairs, tampered).should be_false + end + + it "verify_chain returns true for empty input" do + CRE::Audit::HashChain.verify([] of {Bytes, Bytes}, [] of Bytes).should be_true + end + + it "verify_chain returns false on mismatched array sizes" do + CRE::Audit::HashChain.verify([] of {Bytes, Bytes}, ["x".to_slice]).should be_false + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/hmac_ratchet_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/hmac_ratchet_spec.cr new file mode 100644 index 00000000..8cfd0195 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/hmac_ratchet_spec.cr @@ -0,0 +1,43 @@ +# =================== +# ©AngelaMos | 2026 +# hmac_ratchet_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/audit/hmac_ratchet" + +describe CRE::Audit::HmacRatchet do + it "produces 32-byte HMAC" do + r = CRE::Audit::HmacRatchet.new(Bytes.new(32, 0_u8), version: 1, ratchet_every: 1024) + h = r.sign("payload".to_slice) + h.size.should eq 32 + r.version.should eq 1 + end + + it "rotates after N entries" do + r = CRE::Audit::HmacRatchet.new(Bytes.new(32, 0_u8), version: 1, ratchet_every: 3) + 3.times { r.sign("x".to_slice) } + r.version.should eq 1 # not yet rotated + r.sign("x".to_slice) + r.version.should eq 2 # rotated on the 4th call + end + + it "different keys produce different HMACs" do + a = CRE::Audit::HmacRatchet.new(Bytes.new(32, 0_u8), 1, 1024).sign("x".to_slice) + b = CRE::Audit::HmacRatchet.new(Bytes.new(32, 1_u8), 1, 1024).sign("x".to_slice) + a.should_not eq b + end + + it "rejects keys of incorrect size" do + expect_raises(ArgumentError) do + CRE::Audit::HmacRatchet.new(Bytes.new(16), 1, 1024) + end + end + + it "verify (static) round-trips" do + key = Bytes.new(32, 0xff_u8) + payload = "p".to_slice + h = OpenSSL::HMAC.digest(:sha256, key, payload) + CRE::Audit::HmacRatchet.verify(payload, h, key).should be_true + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/merkle_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/merkle_spec.cr new file mode 100644 index 00000000..4cd7dcce --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/merkle_spec.cr @@ -0,0 +1,38 @@ +# =================== +# ©AngelaMos | 2026 +# merkle_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/audit/merkle" + +describe CRE::Audit::Merkle do + it "single leaf root equals the leaf" do + leaf = "x".to_slice + CRE::Audit::Merkle.root([leaf]).should eq leaf + end + + it "balanced tree root is deterministic" do + leaves = ["a", "b", "c", "d"].map(&.to_slice) + r1 = CRE::Audit::Merkle.root(leaves) + r2 = CRE::Audit::Merkle.root(leaves) + r1.should eq r2 + r1.size.should eq 32 + end + + it "different leaves produce different roots" do + a = CRE::Audit::Merkle.root(["a", "b"].map(&.to_slice)) + b = CRE::Audit::Merkle.root(["a", "c"].map(&.to_slice)) + a.should_not eq b + end + + it "odd leaf count is supported (last is promoted)" do + leaves = ["a", "b", "c"].map(&.to_slice) + r = CRE::Audit::Merkle.root(leaves) + r.size.should eq 32 + end + + it "raises on empty input" do + expect_raises(ArgumentError) { CRE::Audit::Merkle.root([] of Bytes) } + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/signing_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/signing_spec.cr new file mode 100644 index 00000000..e3292c9d --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/audit/signing_spec.cr @@ -0,0 +1,55 @@ +# =================== +# ©AngelaMos | 2026 +# signing_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/audit/signing" + +describe CRE::Audit::Signing do + it "generates a keypair" do + kp = CRE::Audit::Signing::Ed25519Keypair.generate(version: 1) + kp.private_key.size.should eq 32 + kp.public_key.size.should eq 32 + kp.version.should eq 1 + end + + it "signs and verifies a message" do + kp = CRE::Audit::Signing::Ed25519Keypair.generate + signer = CRE::Audit::Signing::Ed25519Signer.from_keypair(kp) + verifier = CRE::Audit::Signing::Ed25519Verifier.new(kp.public_key) + + msg = "audit batch root".to_slice + sig = signer.sign(msg) + sig.size.should eq 64 + verifier.verify(msg, sig).should be_true + end + + it "rejects tampered message" do + kp = CRE::Audit::Signing::Ed25519Keypair.generate + signer = CRE::Audit::Signing::Ed25519Signer.from_keypair(kp) + verifier = CRE::Audit::Signing::Ed25519Verifier.new(kp.public_key) + + msg = "original".to_slice + sig = signer.sign(msg) + verifier.verify("tampered".to_slice, sig).should be_false + end + + it "rejects tampered signature" do + kp = CRE::Audit::Signing::Ed25519Keypair.generate + signer = CRE::Audit::Signing::Ed25519Signer.from_keypair(kp) + verifier = CRE::Audit::Signing::Ed25519Verifier.new(kp.public_key) + + msg = "x".to_slice + sig = signer.sign(msg) + sig[0] ^= 0x01_u8 + verifier.verify(msg, sig).should be_false + end + + it "two keypairs produce different keys" do + a = CRE::Audit::Signing::Ed25519Keypair.generate + b = CRE::Audit::Signing::Ed25519Keypair.generate + a.private_key.should_not eq b.private_key + a.public_key.should_not eq b.public_key + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/secrets_client_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/secrets_client_spec.cr new file mode 100644 index 00000000..114674d0 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/secrets_client_spec.cr @@ -0,0 +1,76 @@ +# =================== +# ©AngelaMos | 2026 +# secrets_client_spec.cr +# =================== + +require "../../spec_helper" +require "webmock" +require "../../../src/cre/aws/secrets_client" + +WebMock.allow_net_connect = false + +private def fresh_client : CRE::Aws::SecretsManagerClient + CRE::Aws::SecretsManagerClient.new( + access_key_id: "AKID", + secret_access_key: "secret", + region: "us-east-1", + ) +end + +describe CRE::Aws::SecretsManagerClient do + before_each { WebMock.reset } + + it "calls PutSecretValue and returns version_id" do + WebMock.stub(:post, "https://secretsmanager.us-east-1.amazonaws.com/") + .with(headers: {"X-Amz-Target" => "secretsmanager.PutSecretValue"}) + .to_return(body: %({"VersionId":"v-123","ARN":"arn:fake"})) + + version = fresh_client.put_secret_value("my-secret", "newpassword") + version.version_id.should eq "v-123" + version.secret_string.should eq "newpassword" + end + + it "calls GetSecretValue and returns the value" do + WebMock.stub(:post, "https://secretsmanager.us-east-1.amazonaws.com/") + .with(headers: {"X-Amz-Target" => "secretsmanager.GetSecretValue"}) + .to_return(body: %({"VersionId":"v-1","SecretString":"theval"})) + + sv = fresh_client.get_secret_value("my-secret") + sv.version_id.should eq "v-1" + sv.secret_string.should eq "theval" + end + + it "calls UpdateSecretVersionStage" do + WebMock.stub(:post, "https://secretsmanager.us-east-1.amazonaws.com/") + .with(headers: {"X-Amz-Target" => "secretsmanager.UpdateSecretVersionStage"}) + .to_return(body: "{}") + + fresh_client.update_secret_version_stage( + "my-secret", + "AWSCURRENT", + move_to_version_id: "v2", + remove_from_version_id: "v1", + ) + end + + it "raises AwsApiError on HTTP non-2xx" do + WebMock.stub(:post, "https://secretsmanager.us-east-1.amazonaws.com/") + .to_return(status: 400, body: %({"__type":"ResourceNotFoundException","message":"nope"})) + + expect_raises(CRE::Aws::AwsApiError) do + fresh_client.get_secret_value("missing") + end + end + + it "respects custom endpoint (LocalStack)" do + WebMock.stub(:post, "http://localstack-test/") + .with(headers: {"X-Amz-Target" => "secretsmanager.PutSecretValue"}) + .to_return(body: %({"VersionId":"local-v1"})) + + client = CRE::Aws::SecretsManagerClient.new( + access_key_id: "test", secret_access_key: "test", + region: "us-east-1", endpoint: "http://localstack-test:4566/", + ) + client.put_secret_value("any", "val").version_id.should eq "local-v1" + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/signer_aws_vector_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/signer_aws_vector_spec.cr new file mode 100644 index 00000000..ab2bf137 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/signer_aws_vector_spec.cr @@ -0,0 +1,123 @@ +# =================== +# ©AngelaMos | 2026 +# signer_aws_vector_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/aws/signer" + +# AWS publishes a reference SigV4 test suite at +# https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html with +# golden values for canonical request, string-to-sign, and signature. +# +# Our signer always emits X-Amz-Content-SHA256 (required by Secrets Manager +# and all the JSON-protocol services we target), which AWS's "vanilla" +# reference vectors deliberately omit. So instead of matching the vanilla +# vector byte-for-byte, we lock in: +# 1. The exact AWS-spec credential-scope and signed-headers list, +# 2. A regression-stable signature for a known input set with our +# always-on X-Amz-Content-SHA256 header. +# Any change to canonicalization, key derivation, or header ordering +# breaks the regression vector — which is the failure mode we care about. +# +# Inputs match the published reference suite for everything except the +# extra signed header: +# access_key: AKIDEXAMPLE +# secret_key: wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY +# region: us-east-1 +# service: service +# date: 20150830T123600Z (UTC) +describe CRE::Aws::SigV4 do + it "produces the AWS-spec credential-scope and signed-headers list" do + signer = CRE::Aws::SigV4.new( + access_key_id: "AKIDEXAMPLE", + secret_access_key: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", + region: "us-east-1", + service: "service", + ) + + headers = HTTP::Headers.new + uri = URI.parse("https://example.amazonaws.com/") + fixed_time = Time.utc(2015, 8, 30, 12, 36, 0) + + signer.sign("GET", uri, headers, "", fixed_time) + + headers["X-Amz-Date"].should eq "20150830T123600Z" + headers["Host"].should eq "example.amazonaws.com" + + auth = headers["Authorization"] + auth.should start_with "AWS4-HMAC-SHA256 " + auth.should contain "Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request" + auth.should contain "SignedHeaders=host;x-amz-content-sha256;x-amz-date" + auth.should match(/Signature=[a-f0-9]{64}\z/) + end + + it "regression vector: locks in the bytewise signature for a fixed input" do + signer = CRE::Aws::SigV4.new( + access_key_id: "AKIDEXAMPLE", + secret_access_key: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", + region: "us-east-1", + service: "service", + ) + headers = HTTP::Headers.new + uri = URI.parse("https://example.amazonaws.com/") + fixed_time = Time.utc(2015, 8, 30, 12, 36, 0) + + signer.sign("GET", uri, headers, "", fixed_time) + + # If any of canonicalization / key derivation / signed-headers + # ordering / content-sha256 logic changes, this assertion catches it. + expected = "726c5c4879a6b4ccbbd3b24edbd6b8826d34f87450fbbf4e85546fc7ba9c1642" + headers["Authorization"].should contain "Signature=#{expected}" + end + + it "matches a POST with body — content-sha256 changes the signature" do + signer = CRE::Aws::SigV4.new( + access_key_id: "AKIDEXAMPLE", + secret_access_key: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", + region: "us-east-1", + service: "service", + ) + + fixed_time = Time.utc(2015, 8, 30, 12, 36, 0) + body = "Param1=value1" + + h_a = HTTP::Headers{"Content-Type" => "application/x-www-form-urlencoded"} + h_b = HTTP::Headers{"Content-Type" => "application/x-www-form-urlencoded"} + + signer.sign("POST", URI.parse("https://example.amazonaws.com/"), h_a, body, fixed_time) + signer.sign("POST", URI.parse("https://example.amazonaws.com/"), h_b, "different-body", fixed_time) + + # Two bodies, two different content-sha256 inputs, two different + # signatures — proves the body actually flows into the signature. + h_a["X-Amz-Content-SHA256"].should_not eq h_b["X-Amz-Content-SHA256"] + h_a["Authorization"].should_not eq h_b["Authorization"] + end + + it "different regions produce different signing keys (and signatures)" do + east = CRE::Aws::SigV4.new("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "us-east-1", "service") + west = CRE::Aws::SigV4.new("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "us-west-2", "service") + fixed = Time.utc(2015, 8, 30, 12, 36, 0) + + h_e = HTTP::Headers.new + h_w = HTTP::Headers.new + east.sign("GET", URI.parse("https://example.amazonaws.com/"), h_e, "", fixed) + west.sign("GET", URI.parse("https://example.amazonaws.com/"), h_w, "", fixed) + + h_e["Authorization"].should_not eq h_w["Authorization"] + end + + it "session token participates in the signed-headers list" do + signer = CRE::Aws::SigV4.new( + access_key_id: "AKIDEXAMPLE", + secret_access_key: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", + region: "us-east-1", + service: "service", + session_token: "TOKENVALUE", + ) + h = HTTP::Headers.new + fixed = Time.utc(2015, 8, 30, 12, 36, 0) + signer.sign("GET", URI.parse("https://example.amazonaws.com/"), h, "", fixed) + h["Authorization"].should contain "x-amz-security-token" + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/signer_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/signer_spec.cr new file mode 100644 index 00000000..4e80e61d --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/aws/signer_spec.cr @@ -0,0 +1,69 @@ +# =================== +# ©AngelaMos | 2026 +# signer_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/aws/signer" + +# Reference SigV4 vector from AWS docs: +# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-test-suite.html +# Using the well-known "get-vanilla" test vector adapted for our API. +describe CRE::Aws::SigV4 do + it "signs a request idempotently for the same time" do + signer = CRE::Aws::SigV4.new( + access_key_id: "AKIDEXAMPLE", + secret_access_key: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", + region: "us-east-1", + service: "secretsmanager", + ) + + headers1 = HTTP::Headers{"Content-Type" => "application/x-amz-json-1.1"} + headers2 = HTTP::Headers{"Content-Type" => "application/x-amz-json-1.1"} + uri = URI.parse("https://secretsmanager.us-east-1.amazonaws.com/") + body = %({"SecretId":"test"}) + fixed_time = Time.utc(2026, 4, 28, 12, 0, 0) + + signer.sign("POST", uri, headers1, body, fixed_time) + signer.sign("POST", uri, headers2, body, fixed_time) + + headers1["Authorization"].should eq headers2["Authorization"] + end + + it "produces a well-formed Authorization header" do + signer = CRE::Aws::SigV4.new("AKID", "secret", "us-east-1", "secretsmanager") + h = HTTP::Headers{"Content-Type" => "application/x-amz-json-1.1"} + signer.sign("POST", URI.parse("https://secretsmanager.us-east-1.amazonaws.com/"), h, "{}") + + h["Authorization"].should match(/^AWS4-HMAC-SHA256 Credential=AKID\/\d{8}\/us-east-1\/secretsmanager\/aws4_request, SignedHeaders=[^,]+, Signature=[a-f0-9]{64}$/) + h["X-Amz-Date"].should match(/^\d{8}T\d{6}Z$/) + h["X-Amz-Content-SHA256"].size.should eq 64 + h["Host"].should eq "secretsmanager.us-east-1.amazonaws.com" + end + + it "different bodies produce different signatures" do + signer = CRE::Aws::SigV4.new("AKID", "secret", "us-east-1", "secretsmanager") + h1 = HTTP::Headers{"Content-Type" => "application/x-amz-json-1.1"} + h2 = HTTP::Headers{"Content-Type" => "application/x-amz-json-1.1"} + uri = URI.parse("https://secretsmanager.us-east-1.amazonaws.com/") + fixed = Time.utc(2026, 1, 1) + + signer.sign("POST", uri, h1, %({"a":1}), fixed) + signer.sign("POST", uri, h2, %({"a":2}), fixed) + h1["Authorization"].should_not eq h2["Authorization"] + end + + it "includes session token header when provided" do + signer = CRE::Aws::SigV4.new( + access_key_id: "AKID", + secret_access_key: "secret", + region: "us-east-1", + service: "secretsmanager", + session_token: "FAKETOKEN", + ) + h = HTTP::Headers{"Content-Type" => "application/x-amz-json-1.1"} + signer.sign("POST", URI.parse("https://secretsmanager.us-east-1.amazonaws.com/"), h, "{}") + h["X-Amz-Security-Token"].should eq "FAKETOKEN" + h["Authorization"].should contain "x-amz-security-token" + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/cli/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/cli/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/cli/cli_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/cli/cli_spec.cr new file mode 100644 index 00000000..1f5c49f5 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/cli/cli_spec.cr @@ -0,0 +1,58 @@ +# =================== +# ©AngelaMos | 2026 +# cli_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/cli/cli" + +describe CRE::Cli do + it "prints usage when no args given and exits 64" do + io = IO::Memory.new + code = CRE::Cli.dispatch([] of String, io) + code.should eq 64 + io.to_s.should contain "Subcommands" + end + + it "prints usage on help" do + io = IO::Memory.new + code = CRE::Cli.dispatch(["help"], io) + code.should eq 0 + io.to_s.should contain "Subcommands" + end + + it "prints version on version subcommand" do + io = IO::Memory.new + code = CRE::Cli.dispatch(["version"], io) + code.should eq 0 + io.to_s.strip.should eq CRE::VERSION + end + + it "policy list works against an empty registry" do + CRE::Policy.clear_registry! + io = IO::Memory.new + code = CRE::Cli.dispatch(["policy", "list"], io) + code.should eq 0 + io.to_s.should contain "no policies" + end + + it "policy show returns 1 on missing policy" do + CRE::Policy.clear_registry! + io = IO::Memory.new + code = CRE::Cli.dispatch(["policy", "show", "nonexistent"], io) + code.should eq 1 + end + + it "rejects unknown subcommands" do + io = IO::Memory.new + code = CRE::Cli.dispatch(["thisisbad"], io) + code.should eq 64 + io.to_s.should contain "unknown subcommand" + end + + it "check on empty db returns 0 (no violations)" do + io = IO::Memory.new + code = CRE::Cli.dispatch(["check", "--db=:memory:"], io) + code.should eq 0 + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/compliance/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/compliance/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/compliance/bundle_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/compliance/bundle_spec.cr new file mode 100644 index 00000000..e9b2f7c9 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/compliance/bundle_spec.cr @@ -0,0 +1,86 @@ +# =================== +# ©AngelaMos | 2026 +# bundle_spec.cr +# =================== + +require "../../spec_helper" +require "compress/zip" +require "../../../src/cre/compliance/bundle" +require "../../../src/cre/audit/audit_log" +require "../../../src/cre/persistence/sqlite/sqlite_persistence" + +private def fresh_persistence + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + persist +end + +describe CRE::Compliance::Bundle do + it "writes a zip with required files" do + persist = fresh_persistence + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, 1024) + log.append("rotation.completed", "system", UUID.random, {"k" => "v"}) + log.append("policy.violation", "system", UUID.random, {"r" => "stale"}) + + out_path = File.tempname("evidence", ".zip") + bundle = CRE::Compliance::Bundle.new(persist, "soc2") + bundle.write(out_path) + + File.exists?(out_path).should be_true + + names = [] of String + Compress::Zip::File.open(out_path) do |zip| + zip.entries.each { |e| names << e.filename } + end + + names.should contain "audit_log.ndjson" + names.should contain "audit_batches.json" + names.should contain "control_mapping.json" + names.should contain "manifest.json" + names.should contain "README.md" + ensure + File.delete(out_path) if out_path && File.exists?(out_path) + persist.try(&.close) + end + + it "manifest.json lists every file with sha256" do + persist = fresh_persistence + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, 1024) + log.append("test", "system", nil, {"x" => "y"}) + + out_path = File.tempname("evidence-m", ".zip") + CRE::Compliance::Bundle.new(persist, "soc2").write(out_path) + + manifest_text = "" + Compress::Zip::File.open(out_path) do |zip| + manifest_text = zip.entries.find!(&.filename.==("manifest.json")).open(&.gets_to_end) + end + + parsed = JSON.parse(manifest_text) + parsed["framework"].as_s.should eq "soc2" + parsed["files"].as_a.size.should be > 0 + parsed["files"].as_a.each do |f| + f["sha256"].as_s.size.should eq 64 + end + ensure + File.delete(out_path) if out_path && File.exists?(out_path) + persist.try(&.close) + end + + it "control_mapping.json carries the right framework controls" do + persist = fresh_persistence + out_path = File.tempname("evidence-cm", ".zip") + CRE::Compliance::Bundle.new(persist, "pci_dss").write(out_path) + + cm = "" + Compress::Zip::File.open(out_path) do |zip| + cm = zip.entries.find!(&.filename.==("control_mapping.json")).open(&.gets_to_end) + end + + parsed = JSON.parse(cm) + parsed["rotation.completed"].as_a.map(&.as_s).should contain "8.3.9" + ensure + File.delete(out_path) if out_path && File.exists?(out_path) + persist.try(&.close) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/compliance/control_mapping_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/compliance/control_mapping_spec.cr new file mode 100644 index 00000000..da51ba9d --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/compliance/control_mapping_spec.cr @@ -0,0 +1,31 @@ +# =================== +# ©AngelaMos | 2026 +# control_mapping_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/compliance/control_mapping" + +describe CRE::Compliance::ControlMapping do + it "maps SOC2 controls" do + map = CRE::Compliance::ControlMapping.for("soc2") + map["rotation.completed"].should contain "CC6.1" + map["rotation.completed"].should contain "CC6.6" + map["audit.batch.sealed"].should contain "CC4.1" + end + + it "maps PCI-DSS controls" do + map = CRE::Compliance::ControlMapping.for("pci_dss") + map["rotation.completed"].should contain "8.3.9" + map["audit.batch.sealed"].should contain "10.5.2" + end + + it "raises on unknown framework" do + expect_raises(ArgumentError) { CRE::Compliance::ControlMapping.for("not-real") } + end + + it "lists frameworks" do + CRE::Compliance::ControlMapping.frameworks.should contain "soc2" + CRE::Compliance::ControlMapping.frameworks.should contain "pci_dss" + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/aead_property_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/aead_property_spec.cr new file mode 100644 index 00000000..9cf1a285 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/aead_property_spec.cr @@ -0,0 +1,24 @@ +# =================== +# ©AngelaMos | 2026 +# aead_property_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/crypto/aead" +require "../../../src/cre/crypto/random" + +describe CRE::Crypto::Aead do + it "encrypt -> decrypt is identity for 100 random plaintexts of varying sizes" do + rng = ::Random.new(42) + 100.times do + size = rng.rand(0..1024) + plaintext = Bytes.new(size) { rng.rand(0_u8..255_u8) } + key = CRE::Crypto::Random.bytes(32) + aad = CRE::Crypto::Random.bytes(rng.rand(0..64)) + + ct, nonce, tag = CRE::Crypto::Aead.encrypt(plaintext, key, aad) + decrypted = CRE::Crypto::Aead.decrypt(ct, key, aad, nonce, tag) + decrypted.should eq plaintext + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/aead_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/aead_spec.cr new file mode 100644 index 00000000..d3e9942c --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/aead_spec.cr @@ -0,0 +1,50 @@ +# =================== +# ©AngelaMos | 2026 +# aead_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/crypto/aead" +require "../../../src/cre/crypto/random" + +describe CRE::Crypto::Aead do + it "round-trips AES-256-GCM with AAD" do + key = CRE::Crypto::Random.bytes(32) + plaintext = "secret value 123".to_slice + aad = "tenant=t1|cred=c1|ver=v1".to_slice + + ct, nonce, tag = CRE::Crypto::Aead.encrypt(plaintext, key, aad) + decrypted = CRE::Crypto::Aead.decrypt(ct, key, aad, nonce, tag) + decrypted.should eq plaintext + end + + it "fails to decrypt with wrong AAD" do + key = CRE::Crypto::Random.bytes(32) + plaintext = "secret".to_slice + aad = "right".to_slice + + ct, nonce, tag = CRE::Crypto::Aead.encrypt(plaintext, key, aad) + expect_raises(CRE::Crypto::Aead::Error) do + CRE::Crypto::Aead.decrypt(ct, key, "wrong".to_slice, nonce, tag) + end + end + + it "fails to decrypt with tampered ciphertext" do + key = CRE::Crypto::Random.bytes(32) + plaintext = "abc-def".to_slice + aad = "x".to_slice + + ct, nonce, tag = CRE::Crypto::Aead.encrypt(plaintext, key, aad) + ct[0] ^= 0x01_u8 + expect_raises(CRE::Crypto::Aead::Error) do + CRE::Crypto::Aead.decrypt(ct, key, aad, nonce, tag) + end + end + + it "rejects keys of incorrect size" do + bad_key = Bytes.new(16) + expect_raises(ArgumentError) do + CRE::Crypto::Aead.encrypt("x".to_slice, bad_key, "a".to_slice) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/envelope_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/envelope_spec.cr new file mode 100644 index 00000000..9c96569c --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/envelope_spec.cr @@ -0,0 +1,55 @@ +# =================== +# ©AngelaMos | 2026 +# envelope_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/crypto/envelope" +require "../../../src/cre/crypto/kek" + +describe CRE::Crypto::Envelope do + it "encrypts and decrypts with envelope" do + ENV["KEK_TEST_HEX"] = "0" * 64 + kek = CRE::Crypto::Kek::EnvKek.new("KEK_TEST_HEX", version: 1) + env = CRE::Crypto::Envelope.new(kek) + + plaintext = "very secret".to_slice + aad = "ctx".to_slice + + sealed = env.seal(plaintext, aad) + sealed.algorithm_id.should eq CRE::Crypto::ALGORITHM_AES_256_GCM + sealed.kek_version.should eq 1 + + opened = env.open(sealed, aad) + opened.should eq plaintext + ensure + ENV.delete("KEK_TEST_HEX") + end + + it "fails to open with mismatched AAD" do + ENV["KEK_TEST_HEX2"] = "0" * 64 + kek = CRE::Crypto::Kek::EnvKek.new("KEK_TEST_HEX2", version: 1) + env = CRE::Crypto::Envelope.new(kek) + + sealed = env.seal("plaintext".to_slice, "good-aad".to_slice) + expect_raises(CRE::Crypto::Aead::Error) do + env.open(sealed, "bad-aad".to_slice) + end + ensure + ENV.delete("KEK_TEST_HEX2") + end + + it "produces different ciphertexts for the same plaintext (random DEK + nonce)" do + ENV["KEK_TEST_HEX3"] = "0" * 64 + kek = CRE::Crypto::Kek::EnvKek.new("KEK_TEST_HEX3", version: 1) + env = CRE::Crypto::Envelope.new(kek) + + aad = "x".to_slice + a = env.seal("same".to_slice, aad) + b = env.seal("same".to_slice, aad) + a.ciphertext.should_not eq b.ciphertext + a.dek_wrapped.should_not eq b.dek_wrapped + ensure + ENV.delete("KEK_TEST_HEX3") + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/kek_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/kek_spec.cr new file mode 100644 index 00000000..d189af3c --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/kek_spec.cr @@ -0,0 +1,35 @@ +# =================== +# ©AngelaMos | 2026 +# kek_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/crypto/kek" + +describe CRE::Crypto::Kek do + it "loads a 32-byte KEK from env hex" do + hex = "0" * 64 + ENV["TEST_KEK_HEX"] = hex + kek = CRE::Crypto::Kek::EnvKek.new("TEST_KEK_HEX", version: 1) + kek.bytes.size.should eq 32 + kek.version.should eq 1 + kek.source.should eq "env:TEST_KEK_HEX" + ensure + ENV.delete("TEST_KEK_HEX") + end + + it "raises on wrong-length hex" do + ENV["BAD_KEK"] = "abcd" + expect_raises(CRE::Crypto::Kek::InvalidKekError) do + CRE::Crypto::Kek::EnvKek.new("BAD_KEK", version: 1) + end + ensure + ENV.delete("BAD_KEK") + end + + it "raises on missing env var" do + expect_raises(CRE::Crypto::Kek::InvalidKekError) do + CRE::Crypto::Kek::EnvKek.new("DOES_NOT_EXIST_XYZ_KEK", version: 1) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/random_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/random_spec.cr new file mode 100644 index 00000000..3a4c1391 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/crypto/random_spec.cr @@ -0,0 +1,46 @@ +# =================== +# ©AngelaMos | 2026 +# random_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/crypto/random" + +describe CRE::Crypto::Random do + it "generates 32 secure bytes" do + bytes = CRE::Crypto::Random.bytes(32) + bytes.size.should eq 32 + end + + it "two calls produce different bytes (overwhelmingly likely)" do + a = CRE::Crypto::Random.bytes(32) + b = CRE::Crypto::Random.bytes(32) + a.should_not eq b + end + + it "hex returns 2n hex chars" do + h = CRE::Crypto::Random.hex(16) + h.size.should eq 32 + h.each_char { |c| ("0123456789abcdef".includes?(c)).should be_true } + end + + describe "constant_time_equal?" do + it "returns true for equal slices" do + a = Bytes[1, 2, 3, 4] + b = Bytes[1, 2, 3, 4] + CRE::Crypto::Random.constant_time_equal?(a, b).should be_true + end + + it "returns false for different slices" do + a = Bytes[1, 2, 3, 4] + b = Bytes[1, 2, 3, 5] + CRE::Crypto::Random.constant_time_equal?(a, b).should be_false + end + + it "returns false for different sizes" do + a = Bytes[1, 2, 3] + b = Bytes[1, 2, 3, 4] + CRE::Crypto::Random.constant_time_equal?(a, b).should be_false + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/credential_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/credential_spec.cr new file mode 100644 index 00000000..0cefa391 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/credential_spec.cr @@ -0,0 +1,81 @@ +# =================== +# ©AngelaMos | 2026 +# credential_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/domain/credential" + +describe CRE::Domain::Credential do + it "constructs with required fields" do + c = CRE::Domain::Credential.new( + id: UUID.random, + external_id: "arn:aws:secretsmanager:us-east-1:1:secret:db-prod", + kind: CRE::Domain::CredentialKind::AwsSecretsmgr, + name: "db-prod", + tags: {"env" => "prod"} of String => String, + ) + c.kind.aws_secretsmgr?.should be_true + c.tag(:env).should eq "prod" + end + + it "returns nil for missing tag" do + c = CRE::Domain::Credential.new( + id: UUID.random, + external_id: "x", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", + tags: {} of String => String, + ) + c.tag(:env).should be_nil + end + + it "supports kind predicates" do + c = CRE::Domain::Credential.new( + id: UUID.random, + external_id: "x", + kind: CRE::Domain::CredentialKind::GithubPat, + name: "n", + tags: {} of String => String, + ) + c.kind.github_pat?.should be_true + c.kind.env_file?.should be_false + end + + it "tag() accepts both string and symbol keys" do + c = CRE::Domain::Credential.new( + id: UUID.random, external_id: "x", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {"foo" => "bar"} of String => String, + ) + c.tag("foo").should eq "bar" + c.tag(:foo).should eq "bar" + end + + it "rotation_anchor falls back to created_at when never rotated" do + created = Time.utc - 3.days + c = CRE::Domain::Credential.new( + id: UUID.random, + external_id: "x", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", + tags: {} of String => String, + created_at: created, + ) + c.rotation_anchor.should eq created + end + + it "rotation_anchor uses last_rotated_at once set" do + rotated = Time.utc - 1.hour + c = CRE::Domain::Credential.new( + id: UUID.random, + external_id: "x", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", + tags: {} of String => String, + created_at: Time.utc - 30.days, + last_rotated_at: rotated, + ) + c.rotation_anchor.should eq rotated + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/credential_version_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/credential_version_spec.cr new file mode 100644 index 00000000..a032c645 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/credential_version_spec.cr @@ -0,0 +1,51 @@ +# =================== +# ©AngelaMos | 2026 +# credential_version_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/domain/credential_version" + +describe CRE::Domain::CredentialVersion do + it "constructs with all fields" do + v = CRE::Domain::CredentialVersion.new( + id: UUID.random, + credential_id: UUID.random, + ciphertext: "x".to_slice, + dek_wrapped: "y".to_slice, + kek_version: 1, + algorithm_id: 1_i16, + metadata: {} of String => String, + ) + v.kek_version.should eq 1 + v.algorithm_id.should eq 1_i16 + v.revoked_at.should be_nil + end + + it "reports revocation" do + revoked_at = Time.utc - 1.hour + v = CRE::Domain::CredentialVersion.new( + id: UUID.random, + credential_id: UUID.random, + ciphertext: Bytes.new(0), + dek_wrapped: Bytes.new(0), + kek_version: 1, + algorithm_id: 1_i16, + revoked_at: revoked_at, + ) + v.revoked?.should be_true + v.revoked_at.should eq revoked_at + end + + it "is not revoked by default" do + v = CRE::Domain::CredentialVersion.new( + id: UUID.random, + credential_id: UUID.random, + ciphertext: Bytes.new(0), + dek_wrapped: Bytes.new(0), + kek_version: 1, + algorithm_id: 1_i16, + ) + v.revoked?.should be_false + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/new_secret_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/new_secret_spec.cr new file mode 100644 index 00000000..a20635ad --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/domain/new_secret_spec.cr @@ -0,0 +1,29 @@ +# =================== +# ©AngelaMos | 2026 +# new_secret_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/domain/new_secret" + +describe CRE::Domain::NewSecret do + it "wraps ciphertext + metadata + timestamp" do + s = CRE::Domain::NewSecret.new( + ciphertext: "abc".to_slice, + metadata: {"version_id" => "v123"}, + ) + s.ciphertext.should eq "abc".to_slice + s.metadata["version_id"].should eq "v123" + s.generated_at.should be_close(Time.utc, 5.seconds) + end + + it "defaults metadata to empty hash" do + s = CRE::Domain::NewSecret.new(ciphertext: Bytes.new(8)) + s.metadata.should be_empty + end + + it "ciphertext is exposed as Bytes" do + s = CRE::Domain::NewSecret.new(ciphertext: Bytes[1, 2, 3]) + s.ciphertext.size.should eq 3 + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/audit_subscriber_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/audit_subscriber_spec.cr new file mode 100644 index 00000000..8db93e9f --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/audit_subscriber_spec.cr @@ -0,0 +1,62 @@ +# =================== +# ©AngelaMos | 2026 +# audit_subscriber_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/engine/event_bus" +require "../../../src/cre/engine/subscribers/audit_subscriber" +require "../../../src/cre/audit/audit_log" +require "../../../src/cre/persistence/sqlite/sqlite_persistence" +require "../../../src/cre/events/credential_events" + +describe CRE::Engine::Subscribers::AuditSubscriber do + it "writes RotationCompleted events to the audit log" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, 1024) + + bus = CRE::Engine::EventBus.new + sub = CRE::Engine::Subscribers::AuditSubscriber.new(bus, log) + sub.start + bus.run + + cred_id = UUID.random + rot_id = UUID.random + bus.publish(CRE::Events::RotationCompleted.new(cred_id, rot_id)) + sleep 0.1.seconds + + persist.audit.latest_seq.should eq 1_i64 + entry = persist.audit.range(1_i64, 1_i64).first + entry.event_type.should eq "rotation.completed" + entry.target_id.should eq cred_id + ensure + bus.try(&.stop) + sub.try(&.stop) + persist.try(&.close) + end + + it "writes multiple event types correctly" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, 1024) + bus = CRE::Engine::EventBus.new + sub = CRE::Engine::Subscribers::AuditSubscriber.new(bus, log) + sub.start + bus.run + + cred_id = UUID.random + bus.publish(CRE::Events::PolicyViolation.new(cred_id, "test-policy", "stale")) + bus.publish(CRE::Events::DriftDetected.new(cred_id, "h1", "h2")) + sleep 0.1.seconds + + persist.audit.latest_seq.should eq 2_i64 + entries = persist.audit.range(1_i64, 2_i64) + entries.map(&.event_type).should eq ["policy.violation", "drift.detected"] + log.verify_chain.should be_true + ensure + bus.try(&.stop) + sub.try(&.stop) + persist.try(&.close) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/engine_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/engine_spec.cr new file mode 100644 index 00000000..b9e7bee3 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/engine_spec.cr @@ -0,0 +1,42 @@ +# =================== +# ©AngelaMos | 2026 +# engine_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/engine/engine" +require "../../../src/cre/persistence/sqlite/sqlite_persistence" +require "../../../src/cre/events/credential_events" + +describe CRE::Engine::Engine do + it "boots, accepts events, and shuts down cleanly" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + + engine = CRE::Engine::Engine.new(persist, Bytes.new(32, 0_u8)) + engine.start + + cred_id = UUID.random + rot_id = UUID.random + engine.bus.publish(CRE::Events::RotationCompleted.new(cred_id, rot_id)) + sleep 0.1.seconds + + persist.audit.latest_seq.should eq 1_i64 + engine.audit_log.verify_chain.should be_true + + engine.stop + ensure + persist.try(&.close) + end + + it "raises if started twice" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + engine = CRE::Engine::Engine.new(persist, Bytes.new(32, 0_u8)) + engine.start + expect_raises(Exception, "already started") { engine.start } + engine.stop + ensure + persist.try(&.close) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/event_bus_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/event_bus_spec.cr new file mode 100644 index 00000000..0b10fa1c --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/event_bus_spec.cr @@ -0,0 +1,91 @@ +# =================== +# ©AngelaMos | 2026 +# event_bus_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/engine/event_bus" +require "../../../src/cre/events/system_events" + +describe CRE::Engine::EventBus do + it "delivers events to subscribers" do + bus = CRE::Engine::EventBus.new + bus.run + received = [] of String + received_mutex = Mutex.new + ch = bus.subscribe(buffer: 16, overflow: CRE::Engine::EventBus::Overflow::Block) + spawn do + loop do + ev = ch.receive + received_mutex.synchronize { received << ev.class.name } + rescue Channel::ClosedError + break + end + end + + bus.publish(CRE::Events::AlertRaised.new(severity: CRE::Events::Severity::Warn, message: "hi")) + sleep 0.1.seconds + + received_mutex.synchronize { received.should contain("CRE::Events::AlertRaised") } + ensure + bus.try(&.stop) + end + + it "fans out to multiple subscribers" do + bus = CRE::Engine::EventBus.new + bus.run + + counter1 = Atomic(Int32).new(0) + counter2 = Atomic(Int32).new(0) + ch1 = bus.subscribe + ch2 = bus.subscribe + spawn do + loop do + ch1.receive + counter1.add(1) + rescue Channel::ClosedError + break + end + end + spawn do + loop do + ch2.receive + counter2.add(1) + rescue Channel::ClosedError + break + end + end + + 3.times { bus.publish(CRE::Events::SchedulerTick.new) } + sleep 0.1.seconds + + counter1.get.should eq 3 + counter2.get.should eq 3 + ensure + bus.try(&.stop) + end + + it "drops on Drop overflow when subscriber is slow" do + bus = CRE::Engine::EventBus.new + bus.run + ch = bus.subscribe(buffer: 1, overflow: CRE::Engine::EventBus::Overflow::Drop) + 5.times { bus.publish(CRE::Events::SchedulerTick.new) } + sleep 0.1.seconds + # The slow subscriber's channel buffered at most 1 event; rest were dropped. + # Drain non-blocking: we should be able to take 0 or 1 event before it would block. + delivered = 0 + drained = false + until drained + select + when ch.receive + delivered += 1 + else + drained = true + end + end + delivered.should be <= 5 + delivered.should be < 5 # at least one was dropped + ensure + bus.try(&.stop) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/rotation_orchestrator_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/rotation_orchestrator_spec.cr new file mode 100644 index 00000000..6b14d618 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/rotation_orchestrator_spec.cr @@ -0,0 +1,250 @@ +# =================== +# ©AngelaMos | 2026 +# rotation_orchestrator_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/engine/rotation_orchestrator" +require "../../../src/cre/persistence/sqlite/sqlite_persistence" +require "../../../src/cre/rotators/env_file" +require "../../../src/cre/crypto/envelope" +require "../../../src/cre/crypto/kek" + +private def drain(ch : ::Channel(CRE::Events::Event)) : Array(CRE::Events::Event) + out = [] of CRE::Events::Event + loop do + select + when ev = ch.receive + out << ev + else + break + end + end + out +end + +private def env_credential(path : String, key : String) : CRE::Domain::Credential + CRE::Domain::Credential.new( + id: UUID.random, + external_id: "#{path}::#{key}", + kind: CRE::Domain::CredentialKind::EnvFile, + name: key, + tags: {"path" => path, "key" => key} of String => String, + ) +end + +describe CRE::Engine::RotationOrchestrator do + it "publishes the full event sequence on success" do + tmp = File.tempfile("cre_rot_") { |f| f << "K=v\n" } + cred = env_credential(tmp.path, "K") + + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + persist.credentials.insert(cred) + + bus = CRE::Engine::EventBus.new + ch = bus.subscribe + bus.run + + orchestrator = CRE::Engine::RotationOrchestrator.new(bus, persist) + state = orchestrator.run(cred, CRE::Rotators::EnvFileRotator.new) + + sleep 0.1.seconds + state.completed?.should be_true + + events = drain(ch).map(&.class.name) + events.should contain "CRE::Events::RotationStarted" + events.count("CRE::Events::RotationStepCompleted").should eq 4 + events.should contain "CRE::Events::RotationCompleted" + events.should_not contain "CRE::Events::RotationFailed" + + # rotation row recorded as completed + persist.rotations.in_flight.size.should eq 0 + ensure + bus.try(&.stop) + persist.try(&.close) + tmp.try(&.delete) + end + + it "handles a rotator that raises during apply via rollback" do + tmp = File.tempfile("cre_rot_fail_") { |f| f << "K=v\n" } + cred = env_credential(tmp.path, "K") + + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + persist.credentials.insert(cred) + + bus = CRE::Engine::EventBus.new + ch = bus.subscribe + bus.run + + failing = FailingRotator.new + state = CRE::Engine::RotationOrchestrator.new(bus, persist).run(cred, failing) + sleep 0.1.seconds + + state.failed?.should be_true + failing.rolled_back.should be_true + + events = drain(ch).map(&.class.name) + events.should contain "CRE::Events::RotationStepFailed" + events.should contain "CRE::Events::RotationFailed" + ensure + bus.try(&.stop) + persist.try(&.close) + tmp.try(&.delete) + end + + it "bumps credential.last_rotated_at on successful rotation" do + tmp = File.tempfile("cre_rot_anchor_") { |f| f << "K=v\n" } + cred = env_credential(tmp.path, "K") + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + persist.credentials.insert(cred) + + bus = CRE::Engine::EventBus.new + bus.run + + floor = Time.utc.at_beginning_of_second + state = CRE::Engine::RotationOrchestrator.new(bus, persist).run(cred, CRE::Rotators::EnvFileRotator.new) + sleep 0.05.seconds + state.completed?.should be_true + + refreshed = persist.credentials.find(cred.id).not_nil! + refreshed.last_rotated_at.not_nil!.should be >= floor + refreshed.rotation_anchor.should be >= floor + ensure + bus.try(&.stop) + persist.try(&.close) + tmp.try(&.delete) + end + + it "writes an encrypted credential_version when an Envelope is configured" do + ENV["TEST_KEK_ROT"] = "0" * 64 + kek = CRE::Crypto::Kek::EnvKek.new("TEST_KEK_ROT", version: 1) + envelope = CRE::Crypto::Envelope.new(kek) + + tmp = File.tempfile("cre_rot_env_") { |f| f << "K=v\n" } + cred = env_credential(tmp.path, "K") + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + persist.credentials.insert(cred) + + bus = CRE::Engine::EventBus.new + bus.run + + state = CRE::Engine::RotationOrchestrator.new(bus, persist, envelope).run(cred, CRE::Rotators::EnvFileRotator.new) + sleep 0.05.seconds + state.completed?.should be_true + + versions = persist.versions.for_credential(cred.id) + versions.size.should eq 1 + v = versions.first + v.kek_version.should eq 1 + v.algorithm_id.should eq CRE::Crypto::ALGORITHM_AES_256_GCM + v.ciphertext.size.should be > 0 + + sealed = CRE::Crypto::SealedSecret.new(v.ciphertext, v.dek_wrapped, v.kek_version, v.algorithm_id) + plaintext = envelope.open(sealed, "cred=#{cred.id}|kind=#{cred.kind}".to_slice) + plaintext.size.should be > 0 + + refreshed = persist.credentials.find(cred.id).not_nil! + refreshed.current_version_id.should eq v.id + ensure + ENV.delete("TEST_KEK_ROT") + bus.try(&.stop) + persist.try(&.close) + tmp.try(&.delete) + end + + it "marks rotation Inconsistent when commit step fails" do + tmp = File.tempfile("cre_rot_commit_fail_") { |f| f << "K=v\n" } + cred = env_credential(tmp.path, "K") + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + persist.credentials.insert(cred) + + bus = CRE::Engine::EventBus.new + ch = bus.subscribe + bus.run + + state = CRE::Engine::RotationOrchestrator.new(bus, persist).run(cred, CommitFailingRotator.new) + sleep 0.05.seconds + + state.should eq CRE::Persistence::RotationState::Inconsistent + persist.rotations.in_flight.size.should eq 0 + + types = drain(ch).map(&.class.name) + types.should contain "CRE::Events::AlertRaised" + ensure + bus.try(&.stop) + persist.try(&.close) + tmp.try(&.delete) + end +end + +class CommitFailingRotator < CRE::Rotators::Rotator + def kind : Symbol + :env_file + end + + def can_rotate?(c : CRE::Domain::Credential) : Bool + _ = c + true + end + + def generate(c : CRE::Domain::Credential) : CRE::Domain::NewSecret + _ = c + CRE::Domain::NewSecret.new(ciphertext: "x".to_slice) + end + + def apply(c : CRE::Domain::Credential, s : CRE::Domain::NewSecret) : Nil + _ = {c, s} + end + + def verify(c : CRE::Domain::Credential, s : CRE::Domain::NewSecret) : Bool + _ = {c, s} + true + end + + def commit(c : CRE::Domain::Credential, s : CRE::Domain::NewSecret) : Nil + _ = {c, s} + raise CRE::Rotators::RotatorError.new("commit network 503") + end +end + +class FailingRotator < CRE::Rotators::Rotator + property rolled_back = false + + def kind : Symbol + :env_file + end + + def can_rotate?(c : CRE::Domain::Credential) : Bool + _ = c + true + end + + def generate(c : CRE::Domain::Credential) : CRE::Domain::NewSecret + _ = c + CRE::Domain::NewSecret.new(ciphertext: "x".to_slice) + end + + def apply(c : CRE::Domain::Credential, s : CRE::Domain::NewSecret) : Nil + _ = {c, s} + raise CRE::Rotators::RotatorError.new("apply boom") + end + + def verify(c : CRE::Domain::Credential, s : CRE::Domain::NewSecret) : Bool + _ = {c, s} + true + end + + def commit(c : CRE::Domain::Credential, s : CRE::Domain::NewSecret) : Nil + _ = {c, s} + end + + def rollback_apply(c : CRE::Domain::Credential, s : CRE::Domain::NewSecret) : Nil + _ = {c, s} + @rolled_back = true + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/rotation_worker_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/rotation_worker_spec.cr new file mode 100644 index 00000000..aa4f5b45 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/rotation_worker_spec.cr @@ -0,0 +1,197 @@ +# =================== +# ©AngelaMos | 2026 +# rotation_worker_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/engine/event_bus" +require "../../../src/cre/engine/rotation_worker" +require "../../../src/cre/engine/rotation_orchestrator" +require "../../../src/cre/persistence/sqlite/sqlite_persistence" +require "../../../src/cre/rotators/env_file" + +private def env_credential(path : String, key : String) : CRE::Domain::Credential + CRE::Domain::Credential.new( + id: UUID.random, + external_id: "#{path}::#{key}", + kind: CRE::Domain::CredentialKind::EnvFile, + name: key, + tags: {"path" => path, "key" => key} of String => String, + ) +end + +private def setup_worker + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + bus = CRE::Engine::EventBus.new + bus.run + orchestrator = CRE::Engine::RotationOrchestrator.new(bus, persist) + worker = CRE::Engine::RotationWorker.new(bus, orchestrator, persist) + {persist, bus, worker} +end + +class StubRotator < CRE::Rotators::Rotator + property generate_count = 0 + property apply_count = 0 + property commit_count = 0 + property declined_credentials = [] of UUID + + def initialize(@kind_sym : Symbol = :env_file, @can_rotate : Bool = true) + end + + def kind : Symbol + @kind_sym + end + + def can_rotate?(c : CRE::Domain::Credential) : Bool + @declined_credentials << c.id unless @can_rotate + @can_rotate + end + + def generate(c : CRE::Domain::Credential) : CRE::Domain::NewSecret + _ = c + @generate_count += 1 + CRE::Domain::NewSecret.new(ciphertext: "x".to_slice) + end + + def apply(c : CRE::Domain::Credential, s : CRE::Domain::NewSecret) : Nil + _ = {c, s} + @apply_count += 1 + end + + def verify(c : CRE::Domain::Credential, s : CRE::Domain::NewSecret) : Bool + _ = {c, s} + true + end + + def commit(c : CRE::Domain::Credential, s : CRE::Domain::NewSecret) : Nil + _ = {c, s} + @commit_count += 1 + end +end + +describe CRE::Engine::RotationWorker do + it "dispatches RotationScheduled to the registered rotator" do + persist, bus, worker = setup_worker + persist.credentials.insert(env_credential("/tmp/x.env", "K")) + rotator = StubRotator.new + worker.register(:env_file, rotator) + worker.start + + cred = persist.credentials.all.first + bus.publish CRE::Events::RotationScheduled.new(cred.id, "env_file") + sleep 0.15.seconds + + rotator.generate_count.should eq 1 + ensure + worker.try(&.stop) + bus.try(&.stop) + persist.try(&.close) + end + + it "skips when no rotator is registered for the credential's kind" do + persist, bus, worker = setup_worker + persist.credentials.insert(env_credential("/tmp/y.env", "K")) + worker.start + + cred = persist.credentials.all.first + bus.publish CRE::Events::RotationScheduled.new(cred.id, "env_file") + sleep 0.1.seconds + + persist.rotations.in_flight.size.should eq 0 + ensure + worker.try(&.stop) + bus.try(&.stop) + persist.try(&.close) + end + + it "skips when rotator.can_rotate? returns false" do + persist, bus, worker = setup_worker + persist.credentials.insert(env_credential("/tmp/z.env", "K")) + rotator = StubRotator.new(can_rotate: false) + worker.register(:env_file, rotator) + worker.start + + cred = persist.credentials.all.first + bus.publish CRE::Events::RotationScheduled.new(cred.id, "env_file") + sleep 0.1.seconds + + rotator.generate_count.should eq 0 + rotator.declined_credentials.should contain(cred.id) + ensure + worker.try(&.stop) + bus.try(&.stop) + persist.try(&.close) + end + + it "ignores events that aren't RotationScheduled" do + persist, bus, worker = setup_worker + persist.credentials.insert(env_credential("/tmp/w.env", "K")) + rotator = StubRotator.new + worker.register(:env_file, rotator) + worker.start + + cred = persist.credentials.all.first + bus.publish CRE::Events::RotationCompleted.new(cred.id, UUID.random) + sleep 0.1.seconds + + rotator.generate_count.should eq 0 + ensure + worker.try(&.stop) + bus.try(&.stop) + persist.try(&.close) + end + + it "deduplicates: a duplicate schedule while one is in_flight is dropped" do + persist, bus, worker = setup_worker + persist.credentials.insert(env_credential("/tmp/dedup.env", "K")) + cred = persist.credentials.all.first + + record = CRE::Persistence::RotationRecord.new( + id: UUID.random, + credential_id: cred.id, + rotator_kind: CRE::Persistence::RotatorKind::EnvFile, + state: CRE::Persistence::RotationState::Generating, + started_at: Time.utc, + completed_at: nil, + failure_reason: nil, + ) + persist.rotations.insert(record) + + rotator = StubRotator.new + worker.register(:env_file, rotator) + worker.start + + bus.publish CRE::Events::RotationScheduled.new(cred.id, "env_file") + sleep 0.1.seconds + + rotator.generate_count.should eq 0 # blocked by in_flight check + ensure + worker.try(&.stop) + bus.try(&.stop) + persist.try(&.close) + end + + it "warns and skips when credential is missing from persistence" do + persist, bus, worker = setup_worker + rotator = StubRotator.new + worker.register(:env_file, rotator) + worker.start + + bus.publish CRE::Events::RotationScheduled.new(UUID.random, "env_file") + sleep 0.1.seconds + + rotator.generate_count.should eq 0 + ensure + worker.try(&.stop) + bus.try(&.stop) + persist.try(&.close) + end + + it "rotator_for_kind returns nil for unregistered kinds" do + _, _, worker = setup_worker + worker.register(:env_file, StubRotator.new) + worker.rotator_for_kind(CRE::Domain::CredentialKind::EnvFile).should_not be_nil + worker.rotator_for_kind(CRE::Domain::CredentialKind::AwsSecretsmgr).should be_nil + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/scheduler_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/scheduler_spec.cr new file mode 100644 index 00000000..7e197951 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/engine/scheduler_spec.cr @@ -0,0 +1,76 @@ +# =================== +# ©AngelaMos | 2026 +# scheduler_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/engine/scheduler" +require "../../../src/cre/engine/event_bus" + +private def drain(ch : ::Channel(CRE::Events::Event)) : Array(CRE::Events::Event) + out = [] of CRE::Events::Event + loop do + select + when ev = ch.receive + out << ev + else + break + end + end + out +end + +describe CRE::Engine::Scheduler do + it "publishes a tick immediately on start" do + bus = CRE::Engine::EventBus.new + ch = bus.subscribe + bus.run + + scheduler = CRE::Engine::Scheduler.new(bus, interval: 5.seconds) + scheduler.start + sleep 0.1.seconds + scheduler.stop + + ticks = drain(ch).count(&.is_a?(CRE::Events::SchedulerTick)) + ticks.should be >= 1 + ensure + bus.try(&.stop) + end + + it "publishes ticks at the configured interval" do + bus = CRE::Engine::EventBus.new + ch = bus.subscribe(buffer: 64) + bus.run + + scheduler = CRE::Engine::Scheduler.new(bus, interval: 0.05.seconds) + scheduler.start + sleep 0.18.seconds + scheduler.stop + sleep 0.05.seconds # let final tick land + + ticks = drain(ch).count(&.is_a?(CRE::Events::SchedulerTick)) + # Initial + ~3 interval ticks = 3-5 expected; allow some scheduling variance + ticks.should be >= 2 + ticks.should be <= 6 + ensure + bus.try(&.stop) + end + + it "stop halts publication" do + bus = CRE::Engine::EventBus.new + ch = bus.subscribe + bus.run + + scheduler = CRE::Engine::Scheduler.new(bus, interval: 0.05.seconds) + scheduler.start + sleep 0.06.seconds + scheduler.stop + drain(ch) # drain whatever was already published + sleep 0.2.seconds + + later = drain(ch).count(&.is_a?(CRE::Events::SchedulerTick)) + later.should be <= 1 # at most one in-flight tick from the last sleep cycle + ensure + bus.try(&.stop) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/events/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/events/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/github/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/github/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/github/client_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/github/client_spec.cr new file mode 100644 index 00000000..c5511049 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/github/client_spec.cr @@ -0,0 +1,51 @@ +# =================== +# ©AngelaMos | 2026 +# client_spec.cr +# =================== + +require "../../spec_helper" +require "webmock" +require "../../../src/cre/github/client" + +WebMock.allow_net_connect = false + +private def fresh_client + CRE::Github::Client.new(token: "ghp_admin") +end + +describe CRE::Github::Client do + before_each { WebMock.reset } + + it "creates a fine-grained PAT" do + WebMock.stub(:post, "https://api.github.com/user/personal-access-tokens") + .with(headers: {"Authorization" => "Bearer ghp_admin"}) + .to_return(body: %({"id":12345,"token":"ghp_newvalue","expires_at":"2026-07-01T00:00:00Z"})) + + token = fresh_client.create_pat("my-pat", ["repo", "read:org"], 90) + token.id.should eq 12345_i64 + token.token_value.should eq "ghp_newvalue" + token.expires_at.should eq "2026-07-01T00:00:00Z" + end + + it "deletes a PAT" do + deleted = false + WebMock.stub(:delete, "https://api.github.com/user/personal-access-tokens/12345") + .with(headers: {"Authorization" => "Bearer ghp_admin"}) + .to_return { |_| deleted = true; HTTP::Client::Response.new(200, body: "{}") } + fresh_client.delete_pat(12345_i64) + deleted.should be_true + end + + it "fetches the authenticated user" do + WebMock.stub(:get, "https://api.github.com/user") + .to_return(body: %({"login":"octocat","id":1})) + user = fresh_client.me + user["login"].as_s.should eq "octocat" + end + + it "raises GithubError on non-2xx" do + WebMock.stub(:get, "https://api.github.com/user") + .to_return(status: 401, body: %({"message":"Bad credentials"})) + expect_raises(CRE::Github::GithubError) { fresh_client.me } + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/log_notifier_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/log_notifier_spec.cr new file mode 100644 index 00000000..ed4c7379 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/log_notifier_spec.cr @@ -0,0 +1,27 @@ +# =================== +# ©AngelaMos | 2026 +# log_notifier_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/notifiers/log_notifier" +require "../../../src/cre/events/credential_events" + +describe CRE::Notifiers::LogNotifier do + it "subscribes and emits without errors on rotation events" do + bus = CRE::Engine::EventBus.new + notifier = CRE::Notifiers::LogNotifier.new(bus) + notifier.start + bus.run + + cred_id = UUID.random + bus.publish CRE::Events::RotationCompleted.new(cred_id, UUID.random) + bus.publish CRE::Events::RotationFailed.new(cred_id, UUID.random, "test") + bus.publish CRE::Events::PolicyViolation.new(cred_id, "p", "stale") + bus.publish CRE::Events::AlertRaised.new(CRE::Events::Severity::Warn, "hi") + + sleep 0.1.seconds + notifier.stop + bus.stop + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/telegram_bot_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/telegram_bot_spec.cr new file mode 100644 index 00000000..f5a182ed --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/telegram_bot_spec.cr @@ -0,0 +1,93 @@ +# =================== +# ©AngelaMos | 2026 +# telegram_bot_spec.cr +# =================== + +require "../../spec_helper" +require "webmock" +require "../../../src/cre/notifiers/telegram_bot" +require "../../../src/cre/persistence/sqlite/sqlite_persistence" + +WebMock.allow_net_connect = false + +private def fresh_setup + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + bus = CRE::Engine::EventBus.new + bus.run + telegram = CRE::Notifiers::Telegram.new("FAKE") + bot = CRE::Notifiers::TelegramBot.new( + bus: bus, + telegram: telegram, + persistence: persist, + viewer_chats: [100_i64], + operator_chats: [200_i64], + ) + {persist, bus, telegram, bot} +end + +describe CRE::Notifiers::TelegramBot do + it "viewer can run /status" do + persist, bus, _, bot = fresh_setup + reply = bot.handle_command(100_i64, "/status") + reply.should contain "live" + reply.should contain "Credentials" + ensure + bus.try(&.stop) + persist.try(&.close) + end + + it "viewer cannot /rotate" do + persist, bus, _, bot = fresh_setup + reply = bot.handle_command(100_i64, "/rotate 00000000-0000-0000-0000-000000000000") + reply.should contain "operator-only" + ensure + bus.try(&.stop) + persist.try(&.close) + end + + it "operator can /rotate; publishes RotationScheduled" do + persist, bus, _, bot = fresh_setup + + received = [] of CRE::Events::Event + received_mutex = Mutex.new + ch = bus.subscribe + spawn do + loop do + begin + ev = ch.receive + received_mutex.synchronize { received << ev } + rescue ::Channel::ClosedError + break + end + end + end + + cred_id = UUID.random + reply = bot.handle_command(200_i64, "/rotate #{cred_id}") + reply.should contain "rotation scheduled" + sleep 0.1.seconds + received_mutex.synchronize { received.any?(&.is_a?(CRE::Events::RotationScheduled)).should be_true } + ensure + bus.try(&.stop) + persist.try(&.close) + end + + it "unauthorized chat is blocked" do + persist, bus, _, bot = fresh_setup + bot.handle_command(999_i64, "/status").should eq "unauthorized" + ensure + bus.try(&.stop) + persist.try(&.close) + end + + it "/help lists commands" do + persist, bus, _, bot = fresh_setup + reply = bot.handle_command(100_i64, "/help") + reply.should contain "/status" + reply.should contain "/rotate" + ensure + bus.try(&.stop) + persist.try(&.close) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/telegram_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/telegram_spec.cr new file mode 100644 index 00000000..5c74ab8a --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/notifiers/telegram_spec.cr @@ -0,0 +1,100 @@ +# =================== +# ©AngelaMos | 2026 +# telegram_spec.cr +# =================== + +require "../../spec_helper" +require "webmock" +require "../../../src/cre/notifiers/telegram" +require "../../../src/cre/notifiers/telegram_subscriber" +require "../../../src/cre/events/credential_events" + +WebMock.allow_net_connect = false + +describe CRE::Notifiers::Telegram do + before_each { WebMock.reset } + + it "sends a message" do + sent_body = nil + WebMock.stub(:post, "https://api.telegram.org/botFAKE/sendMessage") + .to_return { |req| sent_body = req.body.try(&.gets_to_end); HTTP::Client::Response.new(200, body: %({"ok":true})) } + CRE::Notifiers::Telegram.new("FAKE").send_message(12345_i64, "hello world") + sent_body.try(&.includes?("hello world")).should be_true + sent_body.try(&.includes?(%("chat_id":12345))).should be_true + end + + it "raises TelegramError on non-2xx" do + WebMock.stub(:post, "https://api.telegram.org/botFAKE/sendMessage") + .to_return(status: 401, body: %({"ok":false,"description":"Unauthorized"})) + expect_raises(CRE::Notifiers::Telegram::TelegramError) do + CRE::Notifiers::Telegram.new("FAKE").send_message(1_i64, "x") + end + end + + it "parses getUpdates with messages" do + WebMock.stub(:post, "https://api.telegram.org/botFAKE/getUpdates") + .to_return(body: %({ + "ok":true, + "result":[{ + "update_id":42, + "message":{ + "message_id":7, + "chat":{"id":99}, + "text":"/status" + } + }] + })) + updates = CRE::Notifiers::Telegram.new("FAKE").get_updates + updates.size.should eq 1 + updates[0].chat_id.should eq 99 + updates[0].text.should eq "/status" + end +end + +describe CRE::Notifiers::TelegramSubscriber do + before_each { WebMock.reset } + + it "fires Telegram message on RotationFailed" do + sent = [] of String + WebMock.stub(:post, "https://api.telegram.org/botFAKE/sendMessage") + .to_return { |req| + body = req.body.try(&.gets_to_end) || "" + sent << body + HTTP::Client::Response.new(200, body: %({"ok":true})) + } + + bus = CRE::Engine::EventBus.new + sub = CRE::Notifiers::TelegramSubscriber.new( + bus, CRE::Notifiers::Telegram.new("FAKE"), [12345_i64], + ) + sub.start + bus.run + + bus.publish CRE::Events::RotationFailed.new(UUID.random, UUID.random, "boom") + sleep 0.1.seconds + + sent.size.should eq 1 + sent[0].should contain "FAILED" + ensure + bus.try(&.stop) + sub.try(&.stop) + end + + it "does not fire on RotationCompleted unless notify_on_success" do + sent = [] of String + WebMock.stub(:post, "https://api.telegram.org/botFAKE/sendMessage") + .to_return { |req| sent << (req.body.try(&.gets_to_end) || ""); HTTP::Client::Response.new(200, body: %({"ok":true})) } + + bus = CRE::Engine::EventBus.new + sub = CRE::Notifiers::TelegramSubscriber.new( + bus, CRE::Notifiers::Telegram.new("FAKE"), [1_i64], notify_on_success: false) + sub.start + bus.run + bus.publish CRE::Events::RotationCompleted.new(UUID.random, UUID.random) + sleep 0.1.seconds + sent.size.should eq 0 + ensure + bus.try(&.stop) + sub.try(&.stop) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/persistence/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/persistence/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/persistence/sqlite/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/persistence/sqlite/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/persistence/sqlite/sqlite_persistence_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/persistence/sqlite/sqlite_persistence_spec.cr new file mode 100644 index 00000000..9ffb07bd --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/persistence/sqlite/sqlite_persistence_spec.cr @@ -0,0 +1,209 @@ +# =================== +# ©AngelaMos | 2026 +# sqlite_persistence_spec.cr +# =================== + +require "../../../spec_helper" +require "../../../../src/cre/persistence/sqlite/sqlite_persistence" + +describe CRE::Persistence::Sqlite::SqlitePersistence do + describe "credentials repo" do + it "round-trips a credential" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + + c = CRE::Domain::Credential.new( + id: UUID.random, + external_id: "ext-1", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "test", + tags: {"env" => "dev"} of String => String, + ) + + persist.credentials.insert(c) + found = persist.credentials.find(c.id).not_nil! + + found.name.should eq "test" + found.tag("env").should eq "dev" + found.kind.env_file?.should be_true + ensure + persist.try(&.close) + end + + it "find_by_external returns the right credential" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + + c = CRE::Domain::Credential.new( + id: UUID.random, external_id: "uniq-x", + kind: CRE::Domain::CredentialKind::GithubPat, + name: "n", tags: {} of String => String, + ) + persist.credentials.insert(c) + + found = persist.credentials.find_by_external( + CRE::Domain::CredentialKind::GithubPat, "uniq-x", + ).not_nil! + found.id.should eq c.id + ensure + persist.try(&.close) + end + + it "all returns every credential" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + 3.times do |i| + persist.credentials.insert( + CRE::Domain::Credential.new( + id: UUID.random, external_id: "e#{i}", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n#{i}", tags: {} of String => String, + ) + ) + end + persist.credentials.all.size.should eq 3 + ensure + persist.try(&.close) + end + + it "update mutates name and tags" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + id = UUID.random + persist.credentials.insert( + CRE::Domain::Credential.new( + id: id, external_id: "e", kind: CRE::Domain::CredentialKind::EnvFile, + name: "before", tags: {} of String => String, + ) + ) + persist.credentials.update( + CRE::Domain::Credential.new( + id: id, external_id: "e", kind: CRE::Domain::CredentialKind::EnvFile, + name: "after", tags: {"k" => "v"} of String => String, + ) + ) + found = persist.credentials.find(id).not_nil! + found.name.should eq "after" + found.tag("k").should eq "v" + ensure + persist.try(&.close) + end + end + + describe "versions repo" do + it "round-trips a credential version with bytes" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + + cred = CRE::Domain::Credential.new( + id: UUID.random, external_id: "v-test", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "v", tags: {} of String => String, + ) + persist.credentials.insert(cred) + + v = CRE::Domain::CredentialVersion.new( + id: UUID.random, + credential_id: cred.id, + ciphertext: Bytes[1, 2, 3, 4], + dek_wrapped: Bytes[9, 8, 7], + kek_version: 1, + algorithm_id: 1_i16, + ) + persist.versions.insert(v) + + found = persist.versions.find(v.id).not_nil! + found.ciphertext.should eq Bytes[1, 2, 3, 4] + found.dek_wrapped.should eq Bytes[9, 8, 7] + found.algorithm_id.should eq 1_i16 + ensure + persist.try(&.close) + end + + it "revoke marks revoked_at" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + cred = CRE::Domain::Credential.new( + id: UUID.random, external_id: "rev", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + ) + persist.credentials.insert(cred) + v = CRE::Domain::CredentialVersion.new( + id: UUID.random, credential_id: cred.id, + ciphertext: Bytes.new(0), dek_wrapped: Bytes.new(0), + kek_version: 1, algorithm_id: 1_i16, + ) + persist.versions.insert(v) + persist.versions.revoke(v.id) + + found = persist.versions.find(v.id).not_nil! + found.revoked?.should be_true + ensure + persist.try(&.close) + end + end + + describe "rotations repo" do + it "tracks state transitions and in_flight filtering" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + cred_id = UUID.random + persist.credentials.insert( + CRE::Domain::Credential.new( + id: cred_id, external_id: "rot", kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + ) + ) + + r1 = CRE::Persistence::RotationRecord.new( + id: UUID.random, credential_id: cred_id, + rotator_kind: :env_file, state: :generating, + started_at: Time.utc, completed_at: nil, failure_reason: nil, + ) + r2 = CRE::Persistence::RotationRecord.new( + id: UUID.random, credential_id: cred_id, + rotator_kind: :env_file, state: :completed, + started_at: Time.utc, completed_at: Time.utc, failure_reason: nil, + ) + persist.rotations.insert(r1) + persist.rotations.insert(r2) + + persist.rotations.in_flight.size.should eq 1 + persist.rotations.update_state(r1.id, :completed) + persist.rotations.in_flight.size.should eq 0 + ensure + persist.try(&.close) + end + end + + describe "audit repo" do + it "appends and reads back entries; latest_hash returns genesis when empty" do + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + + persist.audit.latest_hash.should eq CRE::Persistence::Sqlite::AuditRepo::GENESIS_HASH + persist.audit.latest_seq.should eq 0_i64 + + entry = CRE::Persistence::AuditEntry.new( + seq: 0_i64, event_id: UUID.random, + occurred_at: Time.utc, event_type: "test", + actor: "system", target_id: nil, + payload: %({"k":"v"}), + prev_hash: Bytes.new(32, 0_u8), + content_hash: Bytes.new(32, 0xaa_u8), + hmac: Bytes.new(32, 0xbb_u8), + hmac_key_version: 1, + ) + persist.audit.append(entry) + + persist.audit.latest_seq.should eq 1_i64 + persist.audit.latest_hash.should eq Bytes.new(32, 0xaa_u8) + rng = persist.audit.range(1_i64, 1_i64) + rng.size.should eq 1 + rng[0].event_type.should eq "test" + ensure + persist.try(&.close) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/builder_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/builder_spec.cr new file mode 100644 index 00000000..3878313b --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/builder_spec.cr @@ -0,0 +1,50 @@ +# =================== +# ©AngelaMos | 2026 +# builder_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/policy/builder" + +describe CRE::Policy::Builder do + it "builds a complete policy" do + b = CRE::Policy::Builder.new("p1") + b.description("desc") + b.match { |c| c.kind.env_file? } + b.max_age(30.days) + b.warn_at(25.days) + b.enforce(CRE::Policy::Action::RotateImmediately) + b.notify_via(CRE::Policy::Channel::Telegram, CRE::Policy::Channel::StructuredLog) + b.on_rotation_failure(CRE::Policy::Action::Quarantine) + + p = b.build + p.name.should eq "p1" + p.description.should eq "desc" + p.max_age.should eq 30.days + p.warn_at.should eq 25.days + p.enforce_action.should eq CRE::Policy::Action::RotateImmediately + p.notify_channels.size.should eq 2 + p.trigger_action_for(CRE::Policy::Trigger::OnRotationFailure).should eq CRE::Policy::Action::Quarantine + end + + it "raises on missing match" do + b = CRE::Policy::Builder.new("p") + b.max_age(7.days) + b.enforce(CRE::Policy::Action::NotifyOnly) + expect_raises(CRE::Policy::BuilderError, /match/) { b.build } + end + + it "raises on missing max_age" do + b = CRE::Policy::Builder.new("p") + b.match { |_c| true } + b.enforce(CRE::Policy::Action::NotifyOnly) + expect_raises(CRE::Policy::BuilderError, /max_age/) { b.build } + end + + it "raises on missing enforce" do + b = CRE::Policy::Builder.new("p") + b.match { |_c| true } + b.max_age(7.days) + expect_raises(CRE::Policy::BuilderError, /enforce/) { b.build } + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/dsl_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/dsl_spec.cr new file mode 100644 index 00000000..7164eb35 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/dsl_spec.cr @@ -0,0 +1,78 @@ +# =================== +# ©AngelaMos | 2026 +# dsl_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/policy/dsl" + +include CRE::Policy::Dsl + +describe "Policy DSL" do + before_each { CRE::Policy.clear_registry! } + + it "registers a policy with full DSL syntax" do + policy "production-aws-secrets" do + description "Prod AWS secret rotation" + match { |c| c.kind.aws_secretsmgr? && c.tag(:env) == "prod" } + max_age 30.days + warn_at 25.days + enforce :rotate_immediately + notify_via :telegram, :structured_log + on_rotation_failure :quarantine + end + + CRE::Policy.registry.size.should eq 1 + p = CRE::Policy.registry.first + p.name.should eq "production-aws-secrets" + p.description.should eq "Prod AWS secret rotation" + p.max_age.should eq 30.days + p.warn_at.should eq 25.days + p.enforce_action.should eq CRE::Policy::Action::RotateImmediately + p.notify_channels.should contain(CRE::Policy::Channel::Telegram) + p.trigger_action_for(CRE::Policy::Trigger::OnRotationFailure).should eq CRE::Policy::Action::Quarantine + end + + it "supports symbol autocast for enum params" do + policy "x" do + match { |_c| true } + max_age 1.day + enforce :notify_only + notify_via :email, :pagerduty + end + + p = CRE::Policy.registry.first + p.enforce_action.should eq CRE::Policy::Action::NotifyOnly + p.notify_channels.should eq [CRE::Policy::Channel::Email, CRE::Policy::Channel::PagerDuty] + end + + it "matcher is a real Crystal closure that captures state" do + threshold = 100 + policy "captured" do + match { |c| c.tags["score"]?.try(&.to_i.>=(threshold)) || false } + max_age 1.day + enforce :notify_only + end + + p = CRE::Policy.registry.first + above = CRE::Domain::Credential.new( + id: UUID.random, external_id: "a", kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {"score" => "150"} of String => String, + ) + below = CRE::Domain::Credential.new( + id: UUID.random, external_id: "b", kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {"score" => "50"} of String => String, + ) + p.matches?(above).should be_true + p.matches?(below).should be_false + end + + it "raises BuilderError for missing required fields" do + expect_raises(CRE::Policy::BuilderError, /match/) do + policy "incomplete" do + max_age 1.day + enforce :notify_only + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/evaluator_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/evaluator_spec.cr new file mode 100644 index 00000000..f76ba920 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/evaluator_spec.cr @@ -0,0 +1,167 @@ +# =================== +# ©AngelaMos | 2026 +# evaluator_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/policy/evaluator" +require "../../../src/cre/policy/dsl" +require "../../../src/cre/persistence/sqlite/sqlite_persistence" + +include CRE::Policy::Dsl + +private def fresh_persistence + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + persist +end + +# Drain non-blocking; returns whatever events arrived without waiting. +private def drain(ch : ::Channel(CRE::Events::Event)) : Array(CRE::Events::Event) + out = [] of CRE::Events::Event + loop do + select + when ev = ch.receive + out << ev + else + break + end + end + out +end + +# Run the bus dispatcher inline for a few ticks so subscribers see events. +private def settle(bus : CRE::Engine::EventBus, duration : Time::Span = 0.1.seconds) + sleep duration +end + +describe CRE::Policy::Evaluator do + before_each { CRE::Policy.clear_registry! } + + it "publishes PolicyViolation + RotationScheduled when overdue with rotate_immediately" do + policy "test-rotate" do + match { |c| c.kind.env_file? } + max_age 7.days + enforce :rotate_immediately + end + + persist = fresh_persistence + persist.credentials.insert( + CRE::Domain::Credential.new( + id: UUID.random, external_id: "x", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + created_at: Time.utc - 30.days, + updated_at: Time.utc - 30.days, + ) + ) + + bus = CRE::Engine::EventBus.new + ch = bus.subscribe(buffer: 256, overflow: CRE::Engine::EventBus::Overflow::Block) + bus.run + + CRE::Policy::Evaluator.new(bus, persist).evaluate_all + settle(bus) + + events = drain(ch) + types = events.map(&.class.name) + types.should contain "CRE::Events::PolicyViolation" + types.should contain "CRE::Events::RotationScheduled" + ensure + bus.try(&.stop) + persist.try(&.close) + end + + it "publishes AlertRaised for notify_only action" do + policy "test-notify" do + match { |c| c.kind.env_file? } + max_age 7.days + enforce :notify_only + end + + persist = fresh_persistence + persist.credentials.insert( + CRE::Domain::Credential.new( + id: UUID.random, external_id: "y", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + created_at: Time.utc - 30.days, updated_at: Time.utc - 30.days, + ) + ) + + bus = CRE::Engine::EventBus.new + ch = bus.subscribe(buffer: 256, overflow: CRE::Engine::EventBus::Overflow::Block) + bus.run + + CRE::Policy::Evaluator.new(bus, persist).evaluate_all + settle(bus) + + events = drain(ch) + types = events.map(&.class.name) + types.should contain "CRE::Events::PolicyViolation" + types.should contain "CRE::Events::AlertRaised" + types.should_not contain "CRE::Events::RotationScheduled" + ensure + bus.try(&.stop) + persist.try(&.close) + end + + it "does not fire for fresh credentials" do + policy "test-fresh" do + match { |c| c.kind.env_file? } + max_age 30.days + enforce :rotate_immediately + end + + persist = fresh_persistence + persist.credentials.insert( + CRE::Domain::Credential.new( + id: UUID.random, external_id: "f", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + ) + ) + + bus = CRE::Engine::EventBus.new + ch = bus.subscribe(buffer: 256, overflow: CRE::Engine::EventBus::Overflow::Block) + bus.run + + CRE::Policy::Evaluator.new(bus, persist).evaluate_all + settle(bus) + + drain(ch).should be_empty + ensure + bus.try(&.stop) + persist.try(&.close) + end + + it "skips policies that don't match the credential" do + policy "github-only" do + match { |c| c.kind.github_pat? } + max_age 7.days + enforce :rotate_immediately + end + + persist = fresh_persistence + persist.credentials.insert( + CRE::Domain::Credential.new( + id: UUID.random, external_id: "envx", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + updated_at: Time.utc - 30.days, + ) + ) + + bus = CRE::Engine::EventBus.new + ch = bus.subscribe(buffer: 256, overflow: CRE::Engine::EventBus::Overflow::Block) + bus.run + + CRE::Policy::Evaluator.new(bus, persist).evaluate_all + settle(bus) + + drain(ch).should be_empty + ensure + bus.try(&.stop) + persist.try(&.close) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/policy_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/policy_spec.cr new file mode 100644 index 00000000..a4fbba3f --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/policy/policy_spec.cr @@ -0,0 +1,132 @@ +# =================== +# ©AngelaMos | 2026 +# policy_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/policy/policy" + +describe CRE::Policy::Policy do + it "matches via the matcher" do + p = CRE::Policy::Policy.new( + name: "p1", + description: nil, + matcher: ->(c : CRE::Domain::Credential) { c.kind.env_file? }, + max_age: 30.days, + warn_at: nil, + enforce_action: CRE::Policy::Action::NotifyOnly, + notify_channels: [] of CRE::Policy::Channel, + triggers: {} of CRE::Policy::Trigger => CRE::Policy::Action, + ) + + matching = CRE::Domain::Credential.new( + id: UUID.random, external_id: "x", kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + ) + other = CRE::Domain::Credential.new( + id: UUID.random, external_id: "y", kind: CRE::Domain::CredentialKind::GithubPat, + name: "n", tags: {} of String => String, + ) + + p.matches?(matching).should be_true + p.matches?(other).should be_false + end + + it "detects overdue based on rotation_anchor + max_age" do + p = CRE::Policy::Policy.new( + name: "p", description: nil, + matcher: ->(_c : CRE::Domain::Credential) { true }, + max_age: 7.days, warn_at: nil, + enforce_action: CRE::Policy::Action::NotifyOnly, + notify_channels: [] of CRE::Policy::Channel, + triggers: {} of CRE::Policy::Trigger => CRE::Policy::Action, + ) + + fresh = CRE::Domain::Credential.new( + id: UUID.random, external_id: "f", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + last_rotated_at: Time.utc - 1.day, + ) + stale = CRE::Domain::Credential.new( + id: UUID.random, external_id: "s", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + last_rotated_at: Time.utc - 30.days, + ) + + p.overdue?(fresh).should be_false + p.overdue?(stale).should be_true + end + + it "treats never-rotated credentials by created_at" do + p = CRE::Policy::Policy.new( + name: "p", description: nil, + matcher: ->(_c : CRE::Domain::Credential) { true }, + max_age: 7.days, warn_at: nil, + enforce_action: CRE::Policy::Action::NotifyOnly, + notify_channels: [] of CRE::Policy::Channel, + triggers: {} of CRE::Policy::Trigger => CRE::Policy::Action, + ) + + aged = CRE::Domain::Credential.new( + id: UUID.random, external_id: "a", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + created_at: Time.utc - 30.days, + ) + p.overdue?(aged).should be_true + end + + it "ignores updated_at (renaming a credential does not reset rotation clock)" do + p = CRE::Policy::Policy.new( + name: "p", description: nil, + matcher: ->(_c : CRE::Domain::Credential) { true }, + max_age: 7.days, warn_at: nil, + enforce_action: CRE::Policy::Action::NotifyOnly, + notify_channels: [] of CRE::Policy::Channel, + triggers: {} of CRE::Policy::Trigger => CRE::Policy::Action, + ) + + just_renamed = CRE::Domain::Credential.new( + id: UUID.random, external_id: "x", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + created_at: Time.utc - 30.days, + updated_at: Time.utc, # tag/name was just edited + last_rotated_at: Time.utc - 30.days, + ) + p.overdue?(just_renamed).should be_true + end + + it "computes warning window" do + p = CRE::Policy::Policy.new( + name: "p", description: nil, + matcher: ->(_c : CRE::Domain::Credential) { true }, + max_age: 30.days, warn_at: 25.days, + enforce_action: CRE::Policy::Action::NotifyOnly, + notify_channels: [] of CRE::Policy::Channel, + triggers: {} of CRE::Policy::Trigger => CRE::Policy::Action, + ) + + young = CRE::Domain::Credential.new( + id: UUID.random, external_id: "y", kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + last_rotated_at: Time.utc - 10.days, + ) + warning = CRE::Domain::Credential.new( + id: UUID.random, external_id: "w", kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + last_rotated_at: Time.utc - 27.days, + ) + overdue = CRE::Domain::Credential.new( + id: UUID.random, external_id: "o", kind: CRE::Domain::CredentialKind::EnvFile, + name: "n", tags: {} of String => String, + last_rotated_at: Time.utc - 31.days, + ) + + p.in_warning_window?(young).should be_false + p.in_warning_window?(warning).should be_true + p.in_warning_window?(overdue).should be_false + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/aws_secrets_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/aws_secrets_spec.cr new file mode 100644 index 00000000..0f2e591d --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/aws_secrets_spec.cr @@ -0,0 +1,109 @@ +# =================== +# ©AngelaMos | 2026 +# aws_secrets_spec.cr +# =================== + +require "../../spec_helper" +require "webmock" +require "../../../src/cre/rotators/aws_secrets" + +WebMock.allow_net_connect = false + +private def aws_credential + CRE::Domain::Credential.new( + id: UUID.random, + external_id: "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-db-prod", + kind: CRE::Domain::CredentialKind::AwsSecretsmgr, + name: "my-db-prod", + tags: { + "secret_arn" => "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-db-prod", + "value_length" => "16", + } of String => String, + ) +end + +private def fresh_client : CRE::Aws::SecretsManagerClient + CRE::Aws::SecretsManagerClient.new( + access_key_id: "AKID", + secret_access_key: "secret", + region: "us-east-1", + ) +end + +describe CRE::Rotators::AwsSecretsRotator do + before_each { WebMock.reset } + + it "executes the full 4-step contract" do + cred = aws_credential + + WebMock.stub(:post, "https://secretsmanager.us-east-1.amazonaws.com/") + .with(headers: {"X-Amz-Target" => "secretsmanager.PutSecretValue"}) + .to_return(body: %({"VersionId":"new-v"})) + + rotator = CRE::Rotators::AwsSecretsRotator.new(fresh_client) + rotator.can_rotate?(cred).should be_true + + new_secret = rotator.generate(cred) + new_secret.metadata["version_id"].should eq "new-v" + new_secret.metadata["secret_arn"].should eq cred.tag("secret_arn") + + rotator.apply(cred, new_secret) # no-op + + expected_value = String.new(new_secret.ciphertext) + WebMock.stub(:post, "https://secretsmanager.us-east-1.amazonaws.com/") + .with(headers: {"X-Amz-Target" => "secretsmanager.GetSecretValue"}) + .to_return(body: %({"VersionId":"new-v","SecretString":#{expected_value.to_json}})) + + rotator.verify(cred, new_secret).should be_true + + # Commit: GetSecretValue (current) + UpdateSecretVersionStage (move) + UpdateSecretVersionStage (remove pending) + WebMock.stub(:post, "https://secretsmanager.us-east-1.amazonaws.com/") + .with(headers: {"X-Amz-Target" => "secretsmanager.GetSecretValue"}) + .to_return(body: %({"VersionId":"old-v","SecretString":"oldval"})) + WebMock.stub(:post, "https://secretsmanager.us-east-1.amazonaws.com/") + .with(headers: {"X-Amz-Target" => "secretsmanager.UpdateSecretVersionStage"}) + .to_return(body: "{}") + + rotator.commit(cred, new_secret) + end + + it "verify returns false on retrieved-value mismatch" do + cred = aws_credential + WebMock.stub(:post, "https://secretsmanager.us-east-1.amazonaws.com/") + .with(headers: {"X-Amz-Target" => "secretsmanager.GetSecretValue"}) + .to_return(body: %({"VersionId":"v","SecretString":"different"})) + + rotator = CRE::Rotators::AwsSecretsRotator.new(fresh_client) + s = CRE::Domain::NewSecret.new( + ciphertext: "expected".to_slice, + metadata: {"version_id" => "v", "secret_arn" => cred.tag("secret_arn").not_nil!}, + ) + rotator.verify(cred, s).should be_false + end + + it "rollback_apply removes AWSPENDING stage" do + cred = aws_credential + rotator = CRE::Rotators::AwsSecretsRotator.new(fresh_client) + s = CRE::Domain::NewSecret.new( + ciphertext: "x".to_slice, + metadata: {"version_id" => "v", "secret_arn" => cred.tag("secret_arn").not_nil!}, + ) + + called = false + WebMock.stub(:post, "https://secretsmanager.us-east-1.amazonaws.com/") + .with(headers: {"X-Amz-Target" => "secretsmanager.UpdateSecretVersionStage"}) + .to_return { |_req| called = true; HTTP::Client::Response.new(200, body: "{}") } + + rotator.rollback_apply(cred, s) + called.should be_true + end + + it "can_rotate? returns false without secret_arn tag" do + bad = CRE::Domain::Credential.new( + id: UUID.random, external_id: "x", + kind: CRE::Domain::CredentialKind::AwsSecretsmgr, + name: "x", tags: {} of String => String, + ) + CRE::Rotators::AwsSecretsRotator.new(fresh_client).can_rotate?(bad).should be_false + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/env_file_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/env_file_spec.cr new file mode 100644 index 00000000..7c9eaee0 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/env_file_spec.cr @@ -0,0 +1,91 @@ +# =================== +# ©AngelaMos | 2026 +# env_file_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/rotators/env_file" + +private def credential_for(path : String, key : String, bytes : Int32 = 32) + CRE::Domain::Credential.new( + id: UUID.random, + external_id: "#{path}::#{key}", + kind: CRE::Domain::CredentialKind::EnvFile, + name: key, + tags: {"path" => path, "key" => key, "bytes" => bytes.to_s} of String => String, + ) +end + +describe CRE::Rotators::EnvFileRotator do + it "executes the full 4-step contract" do + tmp = File.tempfile("cre_env_test_") do |f| + f << "API_KEY=oldvalue\nOTHER=keep\n" + end + path = tmp.path + cred = credential_for(path, "API_KEY") + rotator = CRE::Rotators::EnvFileRotator.new + + rotator.can_rotate?(cred).should be_true + + new_secret = rotator.generate(cred) + new_secret.metadata["key"].should eq "API_KEY" + new_secret.ciphertext.size.should be > 0 + + rotator.apply(cred, new_secret) + File.exists?("#{path}.pending.#{Process.pid}").should be_true + rotator.verify(cred, new_secret).should be_true + + rotator.commit(cred, new_secret) + File.exists?("#{path}.pending.#{Process.pid}").should be_false + + final = File.read(path) + new_value = String.new(new_secret.ciphertext) + final.includes?("API_KEY=#{new_value}").should be_true + final.includes?("OTHER=keep").should be_true + final.includes?("API_KEY=oldvalue").should be_false + ensure + tmp.try(&.delete) + end + + it "rollback_apply removes the pending file" do + tmp = File.tempfile("cre_env_rb_") do |f| + f << "K=v\n" + end + cred = credential_for(tmp.path, "K") + rotator = CRE::Rotators::EnvFileRotator.new + + s = rotator.generate(cred) + rotator.apply(cred, s) + File.exists?("#{tmp.path}.pending.#{Process.pid}").should be_true + + rotator.rollback_apply(cred, s) + File.exists?("#{tmp.path}.pending.#{Process.pid}").should be_false + File.read(tmp.path).should eq "K=v\n" + ensure + tmp.try(&.delete) + end + + it "can_rotate? returns false without required tags" do + bad_cred = CRE::Domain::Credential.new( + id: UUID.random, external_id: "x", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "x", tags: {} of String => String, + ) + CRE::Rotators::EnvFileRotator.new.can_rotate?(bad_cred).should be_false + end + + it "creates the file if missing" do + path = File.tempname("cre_env_new_", ".env") + cred = credential_for(path, "FRESH") + rotator = CRE::Rotators::EnvFileRotator.new + + s = rotator.generate(cred) + rotator.apply(cred, s) + rotator.verify(cred, s).should be_true + rotator.commit(cred, s) + File.exists?(path).should be_true + File.read(path).includes?("FRESH=").should be_true + ensure + File.delete(path) if path && File.exists?(path) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/github_pat_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/github_pat_spec.cr new file mode 100644 index 00000000..214d0288 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/github_pat_spec.cr @@ -0,0 +1,87 @@ +# =================== +# ©AngelaMos | 2026 +# github_pat_spec.cr +# =================== + +require "../../spec_helper" +require "webmock" +require "../../../src/cre/rotators/github_pat" + +WebMock.allow_net_connect = false + +private def github_credential(old_pat_id : String = "111") + CRE::Domain::Credential.new( + id: UUID.random, + external_id: "deploy-bot", + kind: CRE::Domain::CredentialKind::GithubPat, + name: "deploy-bot", + tags: { + "name" => "deploy-bot", + "scopes" => %(["repo","read:org"]), + "old_pat_id" => old_pat_id, + "expires_in_days" => "90", + } of String => String, + ) +end + +private def gh_client + CRE::Github::Client.new(token: "ghp_admin") +end + +describe CRE::Rotators::GithubPatRotator do + before_each { WebMock.reset } + + it "executes the full 4-step contract" do + cred = github_credential + + WebMock.stub(:post, "https://api.github.com/user/personal-access-tokens") + .to_return(body: %({"id":99999,"token":"ghp_new","expires_at":"2026-07-01T00:00:00Z"})) + + rotator = CRE::Rotators::GithubPatRotator.new(gh_client) + rotator.can_rotate?(cred).should be_true + + new_secret = rotator.generate(cred) + new_secret.metadata["new_pat_id"].should eq "99999" + new_secret.metadata["old_pat_id"].should eq "111" + String.new(new_secret.ciphertext).should eq "ghp_new" + + rotator.apply(cred, new_secret) # no-op + + WebMock.stub(:get, "https://api.github.com/user") + .with(headers: {"Authorization" => "Bearer ghp_new"}) + .to_return(body: %({"login":"deploy-bot"})) + rotator.verify(cred, new_secret).should be_true + + deleted_old = false + WebMock.stub(:delete, "https://api.github.com/user/personal-access-tokens/111") + .to_return { |_| deleted_old = true; HTTP::Client::Response.new(200, body: "{}") } + rotator.commit(cred, new_secret) + deleted_old.should be_true + end + + it "verify returns false when /user fails with new token" do + cred = github_credential + WebMock.stub(:get, "https://api.github.com/user") + .to_return(status: 401, body: %({"message":"bad"})) + rotator = CRE::Rotators::GithubPatRotator.new(gh_client) + s = CRE::Domain::NewSecret.new( + ciphertext: "ghp_bad".to_slice, + metadata: {"new_pat_id" => "1", "old_pat_id" => "0"}, + ) + rotator.verify(cred, s).should be_false + end + + it "rollback_apply deletes the new PAT" do + cred = github_credential + rotator = CRE::Rotators::GithubPatRotator.new(gh_client) + s = CRE::Domain::NewSecret.new( + ciphertext: "ghp_new".to_slice, + metadata: {"new_pat_id" => "888"}, + ) + deleted = false + WebMock.stub(:delete, "https://api.github.com/user/personal-access-tokens/888") + .to_return { |_| deleted = true; HTTP::Client::Response.new(200, body: "{}") } + rotator.rollback_apply(cred, s) + deleted.should be_true + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/rotator_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/rotator_spec.cr new file mode 100644 index 00000000..897abb63 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/rotator_spec.cr @@ -0,0 +1,20 @@ +# =================== +# ©AngelaMos | 2026 +# rotator_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/rotators/rotator" +require "../../../src/cre/rotators/env_file" + +describe CRE::Rotators::Rotator do + it "registers concrete rotator subclasses via register_as macro" do + CRE::Rotators::Rotator::REGISTRY[:env_file]?.should_not be_nil + CRE::Rotators::Rotator.for(:env_file).should eq CRE::Rotators::EnvFileRotator + CRE::Rotators::Rotator.registered_kinds.should contain(:env_file) + end + + it "for returns nil for unknown kinds" do + CRE::Rotators::Rotator.for(:nonexistent).should be_nil + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/vault_dynamic_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/vault_dynamic_spec.cr new file mode 100644 index 00000000..e1a71482 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/rotators/vault_dynamic_spec.cr @@ -0,0 +1,95 @@ +# =================== +# ©AngelaMos | 2026 +# vault_dynamic_spec.cr +# =================== + +require "../../spec_helper" +require "webmock" +require "../../../src/cre/rotators/vault_dynamic" + +WebMock.allow_net_connect = false + +private def vault_credential(current_lease : String? = nil) + tags = {"role_path" => "database/creds/myrole"} of String => String + tags["current_lease_id"] = current_lease if current_lease + CRE::Domain::Credential.new( + id: UUID.random, + external_id: "database/creds/myrole", + kind: CRE::Domain::CredentialKind::VaultDynamic, + name: "myrole", + tags: tags, + ) +end + +private def vault_client + CRE::Vault::Client.new(addr: "http://vault.test", token: "tok") +end + +describe CRE::Rotators::VaultDynamicRotator do + before_each { WebMock.reset } + + it "executes the full 4-step contract with lease revocation on commit" do + cred = vault_credential(current_lease: "database/creds/myrole/old") + + WebMock.stub(:get, "http://vault.test/v1/database/creds/myrole") + .to_return(body: %({"lease_id":"database/creds/myrole/new","lease_duration":3600,"data":{"username":"u","password":"p"}})) + + rotator = CRE::Rotators::VaultDynamicRotator.new(vault_client) + rotator.can_rotate?(cred).should be_true + + new_secret = rotator.generate(cred) + new_secret.metadata["lease_id"].should eq "database/creds/myrole/new" + new_secret.metadata["old_lease_id"].should eq "database/creds/myrole/old" + + rotator.apply(cred, new_secret) # no-op + + WebMock.stub(:put, "http://vault.test/v1/sys/leases/renew") + .to_return(body: %({"lease_id":"database/creds/myrole/new","lease_duration":3600})) + rotator.verify(cred, new_secret).should be_true + + revoked = false + WebMock.stub(:put, "http://vault.test/v1/sys/leases/revoke") + .with(body: %({"lease_id":"database/creds/myrole/old"})) + .to_return { |_| revoked = true; HTTP::Client::Response.new(200, body: "{}") } + rotator.commit(cred, new_secret) + revoked.should be_true + end + + it "verify returns false on Vault error" do + cred = vault_credential + WebMock.stub(:put, "http://vault.test/v1/sys/leases/renew") + .to_return(status: 403, body: %({"errors":["denied"]})) + rotator = CRE::Rotators::VaultDynamicRotator.new(vault_client) + s = CRE::Domain::NewSecret.new( + ciphertext: "{}".to_slice, + metadata: {"lease_id" => "x"}, + ) + rotator.verify(cred, s).should be_false + end + + it "rollback_apply revokes the new lease" do + cred = vault_credential + rotator = CRE::Rotators::VaultDynamicRotator.new(vault_client) + s = CRE::Domain::NewSecret.new( + ciphertext: "{}".to_slice, + metadata: {"lease_id" => "new-lease-id"}, + ) + revoked = false + WebMock.stub(:put, "http://vault.test/v1/sys/leases/revoke") + .with(body: %({"lease_id":"new-lease-id"})) + .to_return { |_| revoked = true; HTTP::Client::Response.new(200, body: "{}") } + rotator.rollback_apply(cred, s) + revoked.should be_true + end + + it "skips lease revocation when no current_lease_id" do + cred = vault_credential # no current_lease_id + WebMock.stub(:get, "http://vault.test/v1/database/creds/myrole") + .to_return(body: %({"lease_id":"new","lease_duration":3600,"data":{"username":"u","password":"p"}})) + rotator = CRE::Rotators::VaultDynamicRotator.new(vault_client) + s = rotator.generate(cred) + # commit should be a no-op (no old lease to revoke) + rotator.commit(cred, s) + # If a stub was missing webmock would have raised; absence proves no PUT happened. + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/ansi_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/ansi_spec.cr new file mode 100644 index 00000000..e63f3108 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/ansi_spec.cr @@ -0,0 +1,25 @@ +# =================== +# ©AngelaMos | 2026 +# ansi_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/tui/ansi" + +describe CRE::Tui::Ansi do + it "wraps text with color escape codes" do + out = CRE::Tui::Ansi.green("hello") + out.should contain "\e[32m" + out.should contain "hello" + out.should end_with "\e[0m" + end + + it "move produces a CSI cursor-position sequence" do + CRE::Tui::Ansi.move(5, 10).should eq "\e[5;10H" + end + + it "strip removes escape sequences" do + raw = "\e[1m\e[33mwarn\e[0m message" + CRE::Tui::Ansi.strip(raw).should eq "warn message" + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/renderer_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/renderer_spec.cr new file mode 100644 index 00000000..4e65a57c --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/renderer_spec.cr @@ -0,0 +1,52 @@ +# =================== +# ©AngelaMos | 2026 +# renderer_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/tui/renderer" +require "../../../src/cre/events/credential_events" + +describe CRE::Tui::Renderer do + it "renders the layout with header + panels" do + state = CRE::Tui::State.new(kek_version: 3) + io = IO::Memory.new + CRE::Tui::Renderer.new(state, io, use_color: false).render + + out = CRE::Tui::Ansi.strip(io.to_s) + out.should contain "Credential Rotation Enforcer" + out.should contain "STATUS" + out.should contain "Active Rotations" + out.should contain "Recent Events" + out.should contain "(no active rotations)" + out.should contain "(no events yet)" + out.should contain "v3" + end + + it "renders active rotations" do + state = CRE::Tui::State.new + cred_id = UUID.random + state.apply(CRE::Events::RotationStarted.new(cred_id, UUID.random, "aws_secretsmgr")) + state.apply(CRE::Events::RotationStepCompleted.new(cred_id, UUID.random, :generate)) + state.apply(CRE::Events::RotationStepCompleted.new(cred_id, UUID.random, :apply)) + + io = IO::Memory.new + CRE::Tui::Renderer.new(state, io, use_color: false).render + out = CRE::Tui::Ansi.strip(io.to_s) + out.should contain "aws_secretsmgr" + out.should contain "step 2/4" + end + + it "renders recent events with timestamps" do + state = CRE::Tui::State.new + cred_id = UUID.random + state.apply(CRE::Events::RotationCompleted.new(cred_id, UUID.random)) + state.apply(CRE::Events::PolicyViolation.new(cred_id, "p1", "stale")) + + io = IO::Memory.new + CRE::Tui::Renderer.new(state, io, use_color: false).render + out = CRE::Tui::Ansi.strip(io.to_s) + out.should contain "rotation completed" + out.should contain "p1" + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/state_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/state_spec.cr new file mode 100644 index 00000000..715a3545 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/tui/state_spec.cr @@ -0,0 +1,54 @@ +# =================== +# ©AngelaMos | 2026 +# state_spec.cr +# =================== + +require "../../spec_helper" +require "../../../src/cre/tui/state" +require "../../../src/cre/events/credential_events" + +describe CRE::Tui::State do + it "tracks active rotations through their step lifecycle" do + state = CRE::Tui::State.new + cred_id = UUID.random + rot_id = UUID.random + + state.apply(CRE::Events::RotationStarted.new(cred_id, rot_id, "env_file")) + state.active[cred_id]?.should_not be_nil + state.active[cred_id].step.should eq "starting" + state.active[cred_id].progress.should eq 0 + + state.apply(CRE::Events::RotationStepCompleted.new(cred_id, rot_id, :generate)) + state.active[cred_id].progress.should eq 1 + state.active[cred_id].step.should eq "generate" + + state.apply(CRE::Events::RotationStepCompleted.new(cred_id, rot_id, :apply)) + state.apply(CRE::Events::RotationStepCompleted.new(cred_id, rot_id, :verify)) + state.apply(CRE::Events::RotationStepCompleted.new(cred_id, rot_id, :commit)) + state.active[cred_id].progress.should eq 4 + + state.apply(CRE::Events::RotationCompleted.new(cred_id, rot_id)) + state.active.has_key?(cred_id).should be_false + state.completed_24h.should eq 1 + state.recent.size.should eq 1 + state.recent.first.symbol.should eq "✓" + end + + it "records failed rotations" do + state = CRE::Tui::State.new + cred_id = UUID.random + state.apply(CRE::Events::RotationFailed.new(cred_id, UUID.random, "boom")) + state.recent.first.symbol.should eq "!" + state.recent.first.summary.should contain "FAILED" + end + + it "trims recent events to MAX_RECENT_EVENTS" do + state = CRE::Tui::State.new + 25.times do |i| + state.apply(CRE::Events::AlertRaised.new(CRE::Events::Severity::Info, "msg-#{i}")) + end + state.recent.size.should eq CRE::Tui::State::MAX_RECENT_EVENTS + state.recent.first.summary.should contain "msg-5" + state.recent.last.summary.should contain "msg-24" + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/vault/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/vault/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/vault/client_spec.cr b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/vault/client_spec.cr new file mode 100644 index 00000000..0f8ae663 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/spec/unit/vault/client_spec.cr @@ -0,0 +1,57 @@ +# =================== +# ©AngelaMos | 2026 +# client_spec.cr +# =================== + +require "../../spec_helper" +require "webmock" +require "../../../src/cre/vault/client" + +WebMock.allow_net_connect = false + +private def fresh_client + CRE::Vault::Client.new(addr: "http://vault.test", token: "test-token") +end + +describe CRE::Vault::Client do + before_each { WebMock.reset } + + it "reads a dynamic secret" do + WebMock.stub(:get, "http://vault.test/v1/database/creds/myrole") + .with(headers: {"X-Vault-Token" => "test-token"}) + .to_return(body: %({ + "lease_id":"database/creds/myrole/abc", + "lease_duration":3600, + "data":{"username":"v-token-myrole-xyz","password":"hunter2"} + })) + + secret = fresh_client.read_dynamic("database/creds/myrole") + secret.lease_id.should eq "database/creds/myrole/abc" + secret.lease_duration.should eq 3600 + secret.username.should eq "v-token-myrole-xyz" + secret.password.should eq "hunter2" + end + + it "revokes a lease" do + called = false + WebMock.stub(:put, "http://vault.test/v1/sys/leases/revoke") + .with(body: %({"lease_id":"database/creds/myrole/abc"})) + .to_return { |_| called = true; HTTP::Client::Response.new(200, body: "{}") } + fresh_client.revoke_lease("database/creds/myrole/abc") + called.should be_true + end + + it "renews a lease" do + WebMock.stub(:put, "http://vault.test/v1/sys/leases/renew") + .to_return(body: %({"lease_id":"x","lease_duration":7200})) + fresh_client.renew_lease("x").should eq 7200 + end + + it "raises VaultError on non-2xx" do + WebMock.stub(:get, "http://vault.test/v1/database/creds/missing") + .to_return(status: 404, body: %({"errors":["role missing"]})) + expect_raises(CRE::Vault::VaultError) do + fresh_client.read_dynamic("database/creds/missing") + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre.cr new file mode 100644 index 00000000..a5c75450 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre.cr @@ -0,0 +1,17 @@ +# =================== +# ©AngelaMos | 2026 +# cre.cr +# =================== + +require "./cre/version" +require "./cre/cli/cli" + +module CRE + def self.main(argv : Array(String)) : Int32 + Cli.dispatch(argv) + end +end + +if PROGRAM_NAME.includes?("cre") + exit CRE.main(ARGV) +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/audit_log.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/audit_log.cr new file mode 100644 index 00000000..94103d13 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/audit_log.cr @@ -0,0 +1,142 @@ +# =================== +# ©AngelaMos | 2026 +# audit_log.cr +# =================== + +require "json" +require "uuid" +require "openssl/hmac" +require "./hash_chain" +require "./hmac_ratchet" +require "./merkle" +require "./signing" +require "../crypto/random" +require "../persistence/persistence" +require "../persistence/repos" + +module CRE::Audit + # AuditLog is the append-only, tamper-evident write API used by the + # AuditSubscriber. Verification is split across three layers, each + # callable independently: + # + # verify_hash_chain SHA-256 chain over (prev_hash || payload) + # verify_hmac_ratchet HMAC-SHA256 of every content_hash, with + # the ratcheting key replayed from the + # initial seed + # verify_batches Ed25519-signed Merkle-root batches + # + # Together they answer 'has this log been mutated since it was written': + # - hash chain catches edits to any single row (recompute everything), + # - HMAC ratchet catches edits an attacker who recomputed hashes might + # have made (they don't have the seed key), + # - Merkle batches give an external auditor an O(1) commitment to a + # range of entries that they can verify offline with a public key. + class AuditLog + @ratchet : HmacRatchet + @mutex : Mutex + @initial_hmac_key : Bytes + + def initialize(@persistence : Persistence::Persistence, initial_hmac_key : Bytes, @hmac_version : Int32, @ratchet_every : Int32) + @initial_hmac_key = initial_hmac_key.dup + @ratchet = HmacRatchet.new(initial_hmac_key, @hmac_version, @ratchet_every) + @mutex = Mutex.new + end + + def append(event_type : String, actor : String, target_id : UUID?, payload : Hash) : Persistence::AuditEntry + @mutex.synchronize do + prev = @persistence.audit.latest_hash + canonical = canonical_json(event_type, actor, target_id, payload) + content_hash = HashChain.next_hash(prev, canonical.to_slice) + hmac = @ratchet.sign(content_hash) + + entry = Persistence::AuditEntry.new( + seq: 0_i64, + event_id: UUID.random, + occurred_at: Time.utc, + event_type: event_type, + actor: actor, + target_id: target_id, + payload: canonical, + prev_hash: prev, + content_hash: content_hash, + hmac: hmac, + hmac_key_version: @ratchet.version, + ) + @persistence.audit.append(entry) + entry + end + end + + # Backwards-compatible alias: returns true iff hash chain + HMAC ratchet + # both verify against the seed key the log was constructed with. + def verify_chain : Bool + verify_hash_chain && verify_hmac_ratchet(@initial_hmac_key) + end + + # Verify only the SHA-256 chain. Catches tampering when an attacker + # didn't recompute hashes; doesn't catch tampering when they did. + def verify_hash_chain : Bool + latest = @persistence.audit.latest_seq + return true if latest == 0 + entries = @persistence.audit.range(1_i64, latest) + return false if entries.size != latest + pairs = entries.map { |e| {e.prev_hash, e.content_hash} } + payloads = entries.map(&.payload).map(&.to_slice) + HashChain.verify(pairs, payloads) + end + + # Verify the HMAC ratchet by replaying it from the seed key. An + # attacker who modified rows AND recomputed hashes still doesn't have + # the seed key, so any HMAC mismatch is dispositive evidence of + # tampering. + def verify_hmac_ratchet(seed_key : Bytes) : Bool + raise ArgumentError.new("seed key must be 32 bytes") unless seed_key.size == 32 + latest = @persistence.audit.latest_seq + return true if latest == 0 + + ratchet = HmacRatchet.new(seed_key, version: 1, ratchet_every: @ratchet_every) + entries = @persistence.audit.range(1_i64, latest) + + entries.each do |entry| + return false unless entry.hmac_key_version == ratchet.version + expected = OpenSSL::HMAC.digest(:sha256, ratchet.current_key, entry.content_hash) + return false unless CRE::Crypto::Random.constant_time_equal?(expected, entry.hmac) + ratchet.sign(entry.content_hash) # advance counter; trigger rotation at threshold + end + true + end + + # Verify all sealed Merkle batches against a public key. Each batch + # commits to a Merkle root over content_hashes from start_seq..end_seq; + # we re-derive the root from the live entries and check the signature. + def verify_batches(verifier : Signing::Ed25519Verifier) : Bool + batches = @persistence.audit.all_batches + return true if batches.empty? + + batches.each do |batch| + entries = @persistence.audit.range(batch.start_seq, batch.end_seq) + return false if entries.size != (batch.end_seq - batch.start_seq + 1) + leaves = entries.map(&.content_hash) + recomputed_root = Merkle.root(leaves) + return false unless CRE::Crypto::Random.constant_time_equal?(recomputed_root, batch.merkle_root) + + msg = BatchSealer.pack_message(batch.start_seq, batch.end_seq, batch.merkle_root) + return false unless verifier.verify(msg, batch.signature) + end + true + end + + def ratchet_version : Int32 + @ratchet.version + end + + private def canonical_json(event_type, actor, target_id, payload) : String + { + event_type: event_type, + actor: actor, + target_id: target_id.try(&.to_s), + payload: payload, + }.to_json + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/batch_sealer.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/batch_sealer.cr new file mode 100644 index 00000000..58f1ebac --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/batch_sealer.cr @@ -0,0 +1,61 @@ +# =================== +# ©AngelaMos | 2026 +# batch_sealer.cr +# =================== + +require "uuid" +require "./merkle" +require "./signing" +require "../persistence/persistence" +require "../persistence/repos" + +module CRE::Audit + class BatchSealer + def initialize( + @persistence : Persistence::Persistence, + @signer : Signing::Ed25519Signer, + ) + end + + def seal_pending : Persistence::AuditBatch? + latest = @persistence.audit.latest_seq + last_end = @persistence.audit.last_sealed_seq + return nil if latest <= last_end + + start_seq = last_end + 1 + end_seq = latest + entries = @persistence.audit.range(start_seq, end_seq) + return nil if entries.empty? + + leaves = entries.map(&.content_hash) + root = Merkle.root(leaves) + + msg = pack_message(start_seq, end_seq, root) + sig = @signer.sign(msg) + + batch = Persistence::AuditBatch.new( + id: UUID.random, + start_seq: start_seq, + end_seq: end_seq, + merkle_root: root, + signature: sig, + signing_key_version: @signer.version, + sealed_at: Time.utc, + ) + @persistence.audit.insert_batch(batch) + batch + end + + def self.pack_message(start_seq : Int64, end_seq : Int64, root : Bytes) : Bytes + io = IO::Memory.new + io.write_bytes(start_seq, IO::ByteFormat::BigEndian) + io.write_bytes(end_seq, IO::ByteFormat::BigEndian) + io.write(root) + io.to_slice + end + + private def pack_message(start_seq : Int64, end_seq : Int64, root : Bytes) : Bytes + BatchSealer.pack_message(start_seq, end_seq, root) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/batch_sealer_scheduler.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/batch_sealer_scheduler.cr new file mode 100644 index 00000000..006d4571 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/batch_sealer_scheduler.cr @@ -0,0 +1,64 @@ +# =================== +# ©AngelaMos | 2026 +# batch_sealer_scheduler.cr +# =================== + +require "log" +require "./batch_sealer" +require "../engine/event_bus" +require "../events/credential_events" +require "../events/system_events" + +module CRE::Audit + # BatchSealerScheduler runs an idle fiber that periodically calls + # BatchSealer.seal_pending. Without this fiber the audit_batches table + # never grows and 'cre audit verify --merkle' has nothing to verify. + # + # On each successful seal we publish AlertRaised(:info) with the sealed + # range; the AuditSubscriber then writes a 'audit.batch.sealed' event + # into the audit log itself, which closes the loop for compliance + # frameworks that key on that event_type. + class BatchSealerScheduler + Log = ::Log.for("cre.batch_sealer") + + @running : Bool + + def initialize(@bus : Engine::EventBus, @sealer : BatchSealer, @interval : Time::Span = 5.minutes) + @running = false + end + + def start : Nil + @running = true + spawn(name: "batch-sealer") do + seal_once + while @running + sleep @interval + break unless @running + seal_once + end + end + end + + def stop : Nil + @running = false + seal_once # final seal on shutdown + end + + def seal_once : Nil + batch = @sealer.seal_pending + return if batch.nil? + + @bus.publish Events::AuditBatchSealed.new( + start_seq: batch.start_seq, + end_seq: batch.end_seq, + signing_key_version: batch.signing_key_version, + ) + rescue ex + Log.error(exception: ex) { "batch_sealer.seal_pending failed" } + @bus.publish(Events::AlertRaised.new( + severity: Events::Severity::Critical, + message: "audit batch sealing failed: #{ex.message}", + )) rescue nil + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/hash_chain.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/hash_chain.cr new file mode 100644 index 00000000..3d8f1948 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/hash_chain.cr @@ -0,0 +1,34 @@ +# =================== +# ©AngelaMos | 2026 +# hash_chain.cr +# =================== + +require "openssl/digest" +require "../crypto/random" + +module CRE::Audit + module HashChain + GENESIS_SIZE = 32 + + def self.genesis : Bytes + Bytes.new(GENESIS_SIZE, 0_u8) + end + + def self.next_hash(prev_hash : Bytes, payload : Bytes) : Bytes + d = OpenSSL::Digest.new("SHA256") + d.update(prev_hash) + d.update(payload) + d.final + end + + def self.verify(pairs : Array({Bytes, Bytes}), payloads : Array(Bytes)) : Bool + return false unless pairs.size == payloads.size + pairs.each_with_index do |entry, i| + prev, current = entry + expected = next_hash(prev, payloads[i]) + return false unless CRE::Crypto::Random.constant_time_equal?(expected, current) + end + true + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/hmac_ratchet.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/hmac_ratchet.cr new file mode 100644 index 00000000..2dd5d0ce --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/hmac_ratchet.cr @@ -0,0 +1,52 @@ +# =================== +# ©AngelaMos | 2026 +# hmac_ratchet.cr +# =================== + +require "openssl/hmac" +require "openssl/digest" + +module CRE::Audit + class HmacRatchet + getter version : Int32 + + @key : Bytes + @counter : Int32 + + def initialize(initial_key : Bytes, @version : Int32, @ratchet_every : Int32) + raise ArgumentError.new("key must be 32 bytes") unless initial_key.size == 32 + @key = initial_key.dup + @counter = 0 + end + + def sign(payload : Bytes) : Bytes + maybe_rotate + h = OpenSSL::HMAC.digest(:sha256, @key, payload) + @counter += 1 + h + end + + def self.verify(payload : Bytes, expected : Bytes, key : Bytes) : Bool + h = OpenSSL::HMAC.digest(:sha256, key, payload) + CRE::Crypto::Random.constant_time_equal?(h, expected) + end + + def current_key : Bytes + @key.dup + end + + private def maybe_rotate : Nil + return unless @counter >= @ratchet_every + + d = OpenSSL::Digest.new("SHA256") + d.update(@key) + d.update("ratchet-v#{@version + 1}".to_slice) + new_key = d.final + + @key.size.times { |i| @key[i] = 0_u8 } + @key = new_key + @version += 1 + @counter = 0 + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/merkle.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/merkle.cr new file mode 100644 index 00000000..5b177b7d --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/merkle.cr @@ -0,0 +1,36 @@ +# =================== +# ©AngelaMos | 2026 +# merkle.cr +# =================== + +require "openssl/digest" + +module CRE::Audit + module Merkle + def self.root(leaves : Array(Bytes)) : Bytes + raise ArgumentError.new("empty merkle tree") if leaves.empty? + level = leaves.dup + while level.size > 1 + next_level = [] of Bytes + i = 0 + while i < level.size + if i + 1 < level.size + next_level << combine(level[i], level[i + 1]) + else + next_level << level[i] + end + i += 2 + end + level = next_level + end + level[0] + end + + private def self.combine(a : Bytes, b : Bytes) : Bytes + d = OpenSSL::Digest.new("SHA256") + d.update(a) + d.update(b) + d.final + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/signing.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/signing.cr new file mode 100644 index 00000000..780111eb --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/audit/signing.cr @@ -0,0 +1,116 @@ +# =================== +# ©AngelaMos | 2026 +# signing.cr +# =================== + +require "openssl" +require "openssl/lib_crypto" + +lib LibCrypto + type EVP_PKEY = Void* + + fun evp_pkey_new_raw_private_key_cre = EVP_PKEY_new_raw_private_key(type : LibC::Int, e : Void*, key : UInt8*, keylen : LibC::SizeT) : EVP_PKEY + fun evp_pkey_new_raw_public_key_cre = EVP_PKEY_new_raw_public_key(type : LibC::Int, e : Void*, key : UInt8*, keylen : LibC::SizeT) : EVP_PKEY + fun evp_pkey_get_raw_public_key_cre = EVP_PKEY_get_raw_public_key(pkey : EVP_PKEY, pub : UInt8*, len : LibC::SizeT*) : LibC::Int + fun evp_pkey_free_cre = EVP_PKEY_free(pkey : EVP_PKEY) : Void + fun evp_digestsigninit_cre = EVP_DigestSignInit(ctx : EVP_MD_CTX, pctx : Void*, type : EVP_MD, e : Void*, pkey : EVP_PKEY) : LibC::Int + fun evp_digestsign_cre = EVP_DigestSign(ctx : EVP_MD_CTX, sigret : UInt8*, siglen : LibC::SizeT*, tbs : UInt8*, tbslen : LibC::SizeT) : LibC::Int + fun evp_digestverifyinit_cre = EVP_DigestVerifyInit(ctx : EVP_MD_CTX, pctx : Void*, type : EVP_MD, e : Void*, pkey : EVP_PKEY) : LibC::Int + fun evp_digestverify_cre = EVP_DigestVerify(ctx : EVP_MD_CTX, sig : UInt8*, siglen : LibC::SizeT, tbs : UInt8*, tbslen : LibC::SizeT) : LibC::Int +end + +module CRE::Audit::Signing + NID_ED25519 = 1087 + ED25519_KEY_SIZE = 32 + ED25519_SIG_SIZE = 64 + ED25519_PUBKEY_SIZE = 32 + + class Error < OpenSSL::Error; end + + class Ed25519Keypair + getter version : Int32 + getter private_key : Bytes + getter public_key : Bytes + + def initialize(@private_key : Bytes, @public_key : Bytes, @version : Int32) + raise ArgumentError.new("private key must be 32 bytes") unless @private_key.size == ED25519_KEY_SIZE + raise ArgumentError.new("public key must be 32 bytes") unless @public_key.size == ED25519_PUBKEY_SIZE + end + + def self.generate(version : Int32 = 1) : Ed25519Keypair + private_key = ::Random::Secure.random_bytes(ED25519_KEY_SIZE) + pkey = LibCrypto.evp_pkey_new_raw_private_key_cre(NID_ED25519, Pointer(Void).null, private_key.to_unsafe, ED25519_KEY_SIZE.to_u64) + raise Error.new("EVP_PKEY_new_raw_private_key failed") if pkey.null? + begin + pubkey_buf = Bytes.new(ED25519_PUBKEY_SIZE) + len = ED25519_PUBKEY_SIZE.to_u64 + rc = LibCrypto.evp_pkey_get_raw_public_key_cre(pkey, pubkey_buf.to_unsafe, pointerof(len)) + raise Error.new("EVP_PKEY_get_raw_public_key failed (rc=#{rc})") unless rc == 1 + Ed25519Keypair.new(private_key, pubkey_buf, version) + ensure + LibCrypto.evp_pkey_free_cre(pkey) + end + end + end + + class Ed25519Signer + getter version : Int32 + + def initialize(@private_key : Bytes, @version : Int32) + raise ArgumentError.new("private key must be 32 bytes") unless @private_key.size == ED25519_KEY_SIZE + end + + def self.from_keypair(kp : Ed25519Keypair) : Ed25519Signer + Ed25519Signer.new(kp.private_key, kp.version) + end + + def sign(message : Bytes) : Bytes + pkey = LibCrypto.evp_pkey_new_raw_private_key_cre(NID_ED25519, Pointer(Void).null, @private_key.to_unsafe, ED25519_KEY_SIZE.to_u64) + raise Error.new("EVP_PKEY_new_raw_private_key failed") if pkey.null? + ctx = LibCrypto.evp_md_ctx_new + raise Error.new("EVP_MD_CTX_new failed") if ctx.null? + begin + rc = LibCrypto.evp_digestsigninit_cre(ctx, Pointer(Void).null, Pointer(Void).null.as(LibCrypto::EVP_MD), Pointer(Void).null, pkey) + raise Error.new("EVP_DigestSignInit failed (rc=#{rc})") unless rc == 1 + + siglen = ED25519_SIG_SIZE.to_u64 + sig = Bytes.new(ED25519_SIG_SIZE) + rc = LibCrypto.evp_digestsign_cre(ctx, sig.to_unsafe, pointerof(siglen), message.to_unsafe, message.size.to_u64) + raise Error.new("EVP_DigestSign failed (rc=#{rc})") unless rc == 1 + + sig + ensure + LibCrypto.evp_md_ctx_free(ctx) + LibCrypto.evp_pkey_free_cre(pkey) + end + end + end + + class Ed25519Verifier + def initialize(@public_key : Bytes) + raise ArgumentError.new("public key must be 32 bytes") unless @public_key.size == ED25519_PUBKEY_SIZE + end + + def verify(message : Bytes, signature : Bytes) : Bool + return false unless signature.size == ED25519_SIG_SIZE + + pkey = LibCrypto.evp_pkey_new_raw_public_key_cre(NID_ED25519, Pointer(Void).null, @public_key.to_unsafe, ED25519_PUBKEY_SIZE.to_u64) + return false if pkey.null? + ctx = LibCrypto.evp_md_ctx_new + if ctx.null? + LibCrypto.evp_pkey_free_cre(pkey) + return false + end + begin + rc = LibCrypto.evp_digestverifyinit_cre(ctx, Pointer(Void).null, Pointer(Void).null.as(LibCrypto::EVP_MD), Pointer(Void).null, pkey) + return false unless rc == 1 + + rc = LibCrypto.evp_digestverify_cre(ctx, signature.to_unsafe, signature.size.to_u64, message.to_unsafe, message.size.to_u64) + rc == 1 + ensure + LibCrypto.evp_md_ctx_free(ctx) + LibCrypto.evp_pkey_free_cre(pkey) + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/aws/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/aws/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/aws/secrets_client.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/aws/secrets_client.cr new file mode 100644 index 00000000..1984516d --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/aws/secrets_client.cr @@ -0,0 +1,98 @@ +# =================== +# ©AngelaMos | 2026 +# secrets_client.cr +# =================== + +require "http/client" +require "json" +require "uuid" +require "./signer" +require "../http/retry" + +module CRE::Aws + class AwsApiError < Exception + getter status : Int32 + getter aws_code : String? + + def initialize(message : String, @status : Int32, @aws_code : String? = nil) + super(message) + end + end + + class SecretsManagerClient + AWSCURRENT = "AWSCURRENT" + AWSPENDING = "AWSPENDING" + AWSPREVIOUS = "AWSPREVIOUS" + + record SecretVersion, version_id : String, secret_string : String? + + def initialize( + @access_key_id : String, + @secret_access_key : String, + @region : String, + @endpoint : String? = nil, + @session_token : String? = nil, + ) + @signer = SigV4.new(@access_key_id, @secret_access_key, @region, "secretsmanager", @session_token) + end + + # Stages a new secret version with the AWSPENDING label. + def put_secret_value(secret_id : String, secret_string : String, version_stages : Array(String) = [AWSPENDING]) : SecretVersion + payload = { + "SecretId" => secret_id, + "SecretString" => secret_string, + "ClientRequestToken" => UUID.random.to_s, + "VersionStages" => version_stages, + }.to_json + json = call("PutSecretValue", payload) + SecretVersion.new(json["VersionId"].as_s, secret_string) + end + + def get_secret_value(secret_id : String, version_id : String? = nil, version_stage : String? = nil) : SecretVersion + payload_h = {"SecretId" => secret_id} + payload_h["VersionId"] = version_id if version_id + payload_h["VersionStage"] = version_stage if version_stage + payload = payload_h.to_json + json = call("GetSecretValue", payload) + SecretVersion.new( + json["VersionId"].as_s, + json["SecretString"]?.try(&.as_s), + ) + end + + def update_secret_version_stage(secret_id : String, version_stage : String, move_to_version_id : String? = nil, remove_from_version_id : String? = nil) : Nil + payload_h = { + "SecretId" => secret_id, + "VersionStage" => version_stage, + } + payload_h["MoveToVersionId"] = move_to_version_id if move_to_version_id + payload_h["RemoveFromVersionId"] = remove_from_version_id if remove_from_version_id + call("UpdateSecretVersionStage", payload_h.to_json) + end + + private def call(action : String, body : String) : JSON::Any + uri = URI.parse(@endpoint || "https://secretsmanager.#{@region}.amazonaws.com/") + headers = HTTP::Headers{ + "Content-Type" => "application/x-amz-json-1.1", + "X-Amz-Target" => "secretsmanager.#{action}", + } + @signer.sign("POST", uri, headers, body) + + response = CRE::Http.request("POST", uri.to_s, headers, body, label: "aws.#{action}") + raise AwsApiError.new(error_message(response), response.status_code, error_code(response)) unless response.status_code < 300 + + response.body.empty? ? JSON::Any.new(Hash(String, JSON::Any).new) : JSON.parse(response.body) + end + + private def error_message(resp : HTTP::Client::Response) : String + "AWS #{resp.status_code}: #{resp.body[0, 200]?}" + end + + private def error_code(resp : HTTP::Client::Response) : String? + return nil if resp.body.empty? + JSON.parse(resp.body)["__type"]?.try(&.as_s) + rescue + nil + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/aws/signer.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/aws/signer.cr new file mode 100644 index 00000000..5e4c8bdd --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/aws/signer.cr @@ -0,0 +1,122 @@ +# =================== +# ©AngelaMos | 2026 +# signer.cr +# =================== + +require "openssl/digest" +require "openssl/hmac" +require "uri" +require "http/headers" + +module CRE::Aws + class SignerError < Exception; end + + # SigV4 signer per AWS reference: + # https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html + class SigV4 + ALGORITHM = "AWS4-HMAC-SHA256" + + def initialize( + @access_key_id : String, + @secret_access_key : String, + @region : String, + @service : String, + @session_token : String? = nil, + ) + end + + record SignedRequest, headers : HTTP::Headers, body : String + + # Returns the signed Authorization header value plus modified headers. + # Mutates the headers map in-place to add 'X-Amz-Date', 'Host', + # 'X-Amz-Content-SHA256', 'X-Amz-Security-Token' (if any), 'Authorization'. + def sign(method : String, uri : URI, headers : HTTP::Headers, body : String, now : Time = Time.utc) : Nil + amz_date = now.to_s("%Y%m%dT%H%M%SZ") + date_stamp = now.to_s("%Y%m%d") + + headers["Host"] = uri.host.not_nil! + headers["X-Amz-Date"] = amz_date + headers["X-Amz-Security-Token"] = @session_token.not_nil! if @session_token + payload_hash = sha256_hex(body) + headers["X-Amz-Content-SHA256"] = payload_hash + + canonical_uri = canonical_path(uri.path.empty? ? "/" : uri.path) + canonical_querystring = canonical_query(uri.query) + canonical_headers, signed_headers = canonical_headers_and_list(headers) + + canonical_request = String.build do |s| + s << method.upcase << '\n' + s << canonical_uri << '\n' + s << canonical_querystring << '\n' + s << canonical_headers << '\n' + s << signed_headers << '\n' + s << payload_hash + end + + credential_scope = "#{date_stamp}/#{@region}/#{@service}/aws4_request" + string_to_sign = String.build do |s| + s << ALGORITHM << '\n' + s << amz_date << '\n' + s << credential_scope << '\n' + s << sha256_hex(canonical_request) + end + + signing_key = derive_signing_key(date_stamp) + signature = OpenSSL::HMAC.hexdigest(:sha256, signing_key, string_to_sign) + + auth = String.build do |s| + s << ALGORITHM << ' ' + s << "Credential=" << @access_key_id << '/' << credential_scope << ", " + s << "SignedHeaders=" << signed_headers << ", " + s << "Signature=" << signature + end + headers["Authorization"] = auth + end + + private def canonical_path(path : String) : String + # AWS: encode each path segment per RFC 3986; '/' kept literal; double-encode for non-S3 services + path.split('/', remove_empty: false).map { |seg| URI.encode_path_segment(seg) }.join('/') + end + + private def canonical_query(query : String?) : String + return "" unless query && !query.empty? + params = [] of {String, String} + query.split('&') do |pair| + eq = pair.index('=') + if eq + k = URI.decode_www_form(pair[0, eq]) + v = URI.decode_www_form(pair[eq + 1..]) + else + k = URI.decode_www_form(pair) + v = "" + end + params << {k, v} + end + params.sort! { |a, b| a[0] <=> b[0] } + params.map { |k, v| "#{URI.encode_path_segment(k)}=#{URI.encode_path_segment(v)}" }.join('&') + end + + private def canonical_headers_and_list(headers : HTTP::Headers) : {String, String} + sorted = headers.to_a.map { |name, values| + {name.downcase, values.first.strip.gsub(/\s+/, " ")} + }.sort_by { |entry| entry[0] } + + canonical = sorted.map { |k, v| "#{k}:#{v}\n" }.join + list = sorted.map(&.[0]).join(';') + {canonical, list} + end + + private def derive_signing_key(date_stamp : String) : Bytes + k_date = OpenSSL::HMAC.digest(:sha256, "AWS4#{@secret_access_key}".to_slice, date_stamp.to_slice) + k_region = OpenSSL::HMAC.digest(:sha256, k_date, @region.to_slice) + k_service = OpenSSL::HMAC.digest(:sha256, k_region, @service.to_slice) + OpenSSL::HMAC.digest(:sha256, k_service, "aws4_request".to_slice) + end + + private def sha256_hex(data : String) : String + d = OpenSSL::Digest.new("SHA256") + d.update(data) + d.hexfinal + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/bootstrap.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/bootstrap.cr new file mode 100644 index 00000000..0bd27491 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/bootstrap.cr @@ -0,0 +1,122 @@ +# =================== +# ©AngelaMos | 2026 +# bootstrap.cr +# =================== + +require "../crypto/kek" +require "../crypto/envelope" +require "../audit/signing" +require "../persistence/persistence" +require "../persistence/sqlite/sqlite_persistence" +require "../persistence/postgres/postgres_persistence" +require "../engine/rotation_worker" +require "../rotators/env_file" +require "../rotators/aws_secrets" +require "../rotators/vault_dynamic" +require "../rotators/github_pat" +require "../aws/secrets_client" +require "../vault/client" +require "../github/client" + +module CRE::Cli::Bootstrap + HMAC_KEY_VAR = "CRE_HMAC_KEY_HEX" + KEK_HEX_VAR = "CRE_KEK_HEX" + KEK_VERSION_VAR = "CRE_KEK_VERSION" + SIGNING_KEY_VAR = "CRE_SIGNING_KEY_HEX" + SEAL_INTERVAL_VAR = "CRE_SEAL_INTERVAL_SECONDS" + + class ConfigError < Exception; end + + # Loads the 32-byte HMAC seed key from CRE_HMAC_KEY_HEX. Hard-fails when + # missing; the prior all-zero default left audit logs trivially forgeable + # by anyone with read access to the source. + def self.require_hmac_key : Bytes + hex = ENV[HMAC_KEY_VAR]? + if hex.nil? || hex.empty? + raise ConfigError.new( + "#{HMAC_KEY_VAR} is required for cre to start. Generate one with:\n openssl rand -hex 32\nThen export it before invoking cre.", + ) + end + if hex.size != 64 + raise ConfigError.new("#{HMAC_KEY_VAR} must be 64 hex chars (32 bytes); got #{hex.size}") + end + hex.hexbytes + end + + # Returns an Envelope when CRE_KEK_HEX is set; nil otherwise. nil disables + # at-rest encryption — appropriate for the demo path, but cre run/watch + # should refuse to start without it. + def self.envelope : Crypto::Envelope? + hex = ENV[KEK_HEX_VAR]? + return nil if hex.nil? || hex.empty? + raise ConfigError.new("#{KEK_HEX_VAR} must be 64 hex chars (32 bytes); got #{hex.size}") unless hex.size == 64 + version = (ENV[KEK_VERSION_VAR]? || "1").to_i + kek = Crypto::Kek::EnvKek.new(KEK_HEX_VAR, version) + Crypto::Envelope.new(kek) + end + + def self.require_envelope : Crypto::Envelope + env = envelope + return env unless env.nil? + raise ConfigError.new( + "#{KEK_HEX_VAR} is required for cre run/watch. Generate with:\n openssl rand -hex 32\nKEK rotation: bump #{KEK_VERSION_VAR}.", + ) + end + + # Returns an Ed25519 signer when CRE_SIGNING_KEY_HEX is set, nil otherwise. + # When nil, batch sealing is disabled and 'cre audit verify' will skip the + # Merkle layer. + def self.signer : Audit::Signing::Ed25519Signer? + hex = ENV[SIGNING_KEY_VAR]? + return nil if hex.nil? || hex.empty? + raise ConfigError.new("#{SIGNING_KEY_VAR} must be 64 hex chars (32 bytes); got #{hex.size}") unless hex.size == 64 + Audit::Signing::Ed25519Signer.new(hex.hexbytes, version: 1) + end + + def self.seal_interval : Time::Span + seconds = (ENV[SEAL_INTERVAL_VAR]? || "300").to_i + seconds.seconds + end + + def self.build_persistence(url : String) : Persistence::Persistence + if url.starts_with?("sqlite:") + Persistence::Sqlite::SqlitePersistence.new(url.lchop("sqlite:")) + elsif url.starts_with?("postgres://") || url.starts_with?("postgresql://") + Persistence::Postgres::PostgresPersistence.new(url) + else + raise ConfigError.new("unknown database URL: #{url} (expected sqlite:PATH or postgres://...)") + end + end + + def self.register_rotators(worker : Engine::RotationWorker, io : IO) : Nil + worker.register(:env_file, Rotators::EnvFileRotator.new) + + if (aws_id = ENV["AWS_ACCESS_KEY_ID"]?) && (aws_secret = ENV["AWS_SECRET_ACCESS_KEY"]?) + client = Aws::SecretsManagerClient.new( + access_key_id: aws_id, + secret_access_key: aws_secret, + region: ENV["AWS_REGION"]? || "us-east-1", + endpoint: ENV["AWS_ENDPOINT"]?, + session_token: ENV["AWS_SESSION_TOKEN"]?, + ) + worker.register(:aws_secretsmgr, Rotators::AwsSecretsRotator.new(client)) + end + + if (vault_addr = ENV["VAULT_ADDR"]?) && (vault_token = ENV["VAULT_TOKEN"]?) + client = Vault::Client.new(addr: vault_addr, token: vault_token) + worker.register(:vault_dynamic, Rotators::VaultDynamicRotator.new(client)) + end + + if gh_token = ENV["GITHUB_TOKEN"]? + api = ENV["GITHUB_API_BASE"]? || "https://api.github.com" + client = Github::Client.new(token: gh_token, api_base: api) + worker.register(:github_pat, Rotators::GithubPatRotator.new(client)) + end + rescue ex + io.puts "warning: rotator wiring failed: #{ex.message}" + end + + def self.redact_db_url(url : String) : String + url.gsub(/:\/\/[^:]+:[^@]+@/) { |_| "://****:****@" } + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/cli.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/cli.cr new file mode 100644 index 00000000..d2e01b9a --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/cli.cr @@ -0,0 +1,70 @@ +# =================== +# ©AngelaMos | 2026 +# cli.cr +# =================== + +require "option_parser" +require "../version" +require "./output" +require "./commands" + +module CRE::Cli + USAGE = <<-USAGE + cre - Credential Rotation Enforcer + + Usage: cre [options] + + Subcommands: + run headless daemon (production / systemd) + watch engine + live TUI in same process + check evaluate policies once, exit non-zero on violations + rotate manually rotate a single credential + policy list list compiled-in policies + policy show inspect one policy + export --framework= generate signed compliance evidence bundle + audit verify verify hash chain + HMAC ratchet + Merkle batches + verify-bundle verify a compliance evidence ZIP offline + demo tier-1 zero-deps demo (SQLite + .env rotator) + tui-demo 8-second TUI preview with synthetic events + version print version + help this message + + Common options: + --output=human|json|ndjson output format (default: human) + --config=PATH config file (default: $CRE_CONFIG or ./config.cr) + USAGE + + def self.dispatch(argv : Array(String), io : IO = STDOUT) : Int32 + if argv.empty? || %w[--help -h help].includes?(argv.first) + io.puts USAGE + return argv.empty? ? 64 : 0 # 64 = EX_USAGE + end + + subcommand = argv.shift + case subcommand + when "version" + io.puts CRE::VERSION + 0 + when "run" then Commands::Run.new.execute(argv, io) + when "watch" then Commands::Watch.new.execute(argv, io) + when "check" then Commands::Check.new.execute(argv, io) + when "rotate" then Commands::Rotate.new.execute(argv, io) + when "policy" then Commands::Policy.new.execute(argv, io) + when "export" then Commands::Export.new.execute(argv, io) + when "audit" then Commands::Audit.new.execute(argv, io) + when "verify-bundle" then Commands::VerifyBundle.new.execute(argv, io) + when "demo" then Commands::Demo.new.execute(argv, io) + when "tui-demo" then Commands::TuiDemo.new.execute(argv, io) + else + io.puts "unknown subcommand: #{subcommand}" + io.puts USAGE + 64 + end + rescue ex : OptionParser::InvalidOption | OptionParser::MissingOption + io.puts "error: #{ex.message}" + 64 + rescue ex + io.puts "error: #{ex.message}" + 1 + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands.cr new file mode 100644 index 00000000..01946114 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands.cr @@ -0,0 +1,16 @@ +# =================== +# ©AngelaMos | 2026 +# commands.cr +# =================== + +require "./commands/run" +require "./commands/watch" +require "./commands/check" +require "./commands/rotate" +require "./commands/policy" +require "./commands/export" +require "./commands/audit" +require "./commands/verify_bundle" +require "./commands/demo" +require "./commands/tui_demo" +require "./commands/version" diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/audit.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/audit.cr new file mode 100644 index 00000000..fd534da9 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/audit.cr @@ -0,0 +1,95 @@ +# =================== +# ©AngelaMos | 2026 +# audit.cr +# =================== + +require "../../audit/audit_log" +require "../../audit/signing" +require "../../persistence/sqlite/sqlite_persistence" +require "../bootstrap" + +module CRE::Cli::Commands + class Audit + def execute(argv : Array(String), io : IO) : Int32 + sub = argv.shift? + case sub + when "verify" then verify(argv, io) + when nil, "--help", "-h" + io.puts <<-USAGE + Usage: cre audit verify [--db=PATH] [--public-key=PATH] + + Verifies the local audit log in three layers: + - hash chain (always) + - HMAC ratchet (always; requires CRE_HMAC_KEY_HEX) + - Merkle batch signatures (when --public-key=PATH or + CRE_AUDIT_PUBLIC_KEY_HEX is set) + USAGE + 0 + else + io.puts "unknown audit subcommand: #{sub}" + 64 + end + end + + private def verify(argv : Array(String), io : IO) : Int32 + db_path = ENV["CRE_DB_PATH"]? || "cre.db" + public_key_hex = ENV["CRE_AUDIT_PUBLIC_KEY_HEX"]? + public_key_path = nil + + OptionParser.parse(argv) do |parser| + parser.on("--db=PATH", "") { |p| db_path = p } + parser.on("--public-key=PATH", "Ed25519 public key (32 bytes hex) for batch signature verification") { |p| public_key_path = p } + end + + hmac_key = Bootstrap.require_hmac_key + + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(db_path) + persist.migrate! + + log = CRE::Audit::AuditLog.new(persist, hmac_key, 1, 1024) + + hash_ok = log.verify_hash_chain + hmac_ok = log.verify_hmac_ratchet(hmac_key) + latest_seq = persist.audit.latest_seq + + verifier_pem_hex = if path = public_key_path + File.read(path).strip + else + public_key_hex + end + + batches_ok = true + if (hex = verifier_pem_hex) && !hex.empty? + if hex.size != 64 + io.puts "✗ public key must be 64 hex chars (32 bytes); got #{hex.size}" + persist.close + return 2 + end + verifier = CRE::Audit::Signing::Ed25519Verifier.new(hex.hexbytes) + batches_ok = log.verify_batches(verifier) + end + + persist.close + + print_result(io, "hash chain", hash_ok) + print_result(io, "HMAC ratchet", hmac_ok) + if verifier_pem_hex + print_result(io, "Merkle batches", batches_ok) + else + io.puts " - Merkle batches not checked (no public key supplied)" + end + + if hash_ok && hmac_ok && batches_ok + io.puts "✓ audit chain valid: #{latest_seq} entries" + 0 + else + io.puts "✗ audit chain BROKEN — verification failed" + 2 + end + end + + private def print_result(io : IO, label : String, ok : Bool) : Nil + io.puts " #{ok ? "✓" : "✗"} #{label}: #{ok ? "OK" : "FAILED"}" + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/check.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/check.cr new file mode 100644 index 00000000..2dc78c15 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/check.cr @@ -0,0 +1,77 @@ +# =================== +# ©AngelaMos | 2026 +# check.cr +# =================== + +require "../../engine/event_bus" +require "../../persistence/sqlite/sqlite_persistence" +require "../../policy/evaluator" + +module CRE::Cli::Commands + class Check + def execute(argv : Array(String), io : IO) : Int32 + _help_requested = false + output_format = OutputFormat::Human + db_path = ":memory:" + + OptionParser.parse(argv) do |parser| + parser.banner = "Usage: cre check [options]" + parser.on("--output=FORMAT", "human|json|ndjson") { |f| output_format = Output.parse_format(f) } + parser.on("--db=PATH", "SQLite path (default :memory:)") { |p| db_path = p } + parser.on("-h", "--help") { _help_requested = true; io.puts parser } + end + return 0 if _help_requested + + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(db_path) + persist.migrate! + + bus = CRE::Engine::EventBus.new + ch = bus.subscribe(buffer: 256) + bus.run + + CRE::Policy::Evaluator.new(bus, persist).evaluate_all + sleep 0.1.seconds + + violations = drain(ch).select(&.is_a?(CRE::Events::PolicyViolation)).map(&.as(CRE::Events::PolicyViolation)) + bus.stop + persist.close + + case output_format + in OutputFormat::Human + if violations.empty? + io.puts "OK: no policy violations" + else + io.puts "VIOLATIONS (#{violations.size}):" + violations.each do |v| + io.puts " - credential=#{v.credential_id} policy=#{v.policy_name} reason=#{v.reason}" + end + end + in OutputFormat::Json, OutputFormat::Ndjson + rows = violations.map do |v| + { + "credential_id" => v.credential_id.to_s, + "policy" => v.policy_name, + "reason" => v.reason, + "occurred_at" => v.occurred_at.to_rfc3339, + } + end + Output.print(io, output_format, rows) + end + + violations.empty? ? 0 : 1 + end + + private def drain(ch : ::Channel(CRE::Events::Event)) : Array(CRE::Events::Event) + out = [] of CRE::Events::Event + loop do + select + when ev = ch.receive + out << ev + else + break + end + end + out + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/demo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/demo.cr new file mode 100644 index 00000000..0dd8697f --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/demo.cr @@ -0,0 +1,21 @@ +# =================== +# ©AngelaMos | 2026 +# demo.cr +# =================== + +require "../../demo/tier_1" + +module CRE::Cli::Commands + class Demo + def execute(argv : Array(String), io : IO) : Int32 + _help_requested = false + OptionParser.parse(argv) do |parser| + parser.banner = "Usage: cre demo (tier-1, no external deps)" + parser.on("-h", "--help") { _help_requested = true; io.puts parser } + end + return 0 if _help_requested + + CRE::Demo::Tier1.run(io) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/export.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/export.cr new file mode 100644 index 00000000..95083f21 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/export.cr @@ -0,0 +1,40 @@ +# =================== +# ©AngelaMos | 2026 +# export.cr +# =================== + +require "../../compliance/bundle" +require "../../persistence/sqlite/sqlite_persistence" + +module CRE::Cli::Commands + class Export + def execute(argv : Array(String), io : IO) : Int32 + _help_requested = false + framework = "soc2" + out_path = "evidence.zip" + db_path = ENV["CRE_DB_PATH"]? || "cre.db" + + OptionParser.parse(argv) do |parser| + parser.banner = "Usage: cre export --framework= --out=" + parser.on("--framework=NAME", "soc2|pci_dss|iso27001|hipaa") { |f| framework = f } + parser.on("--out=PATH", "output zip path") { |p| out_path = p } + parser.on("--db=PATH", "") { |p| db_path = p } + parser.on("-h", "--help") { _help_requested = true; io.puts parser } + end + return 0 if _help_requested + + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(db_path) + persist.migrate! + + bundle = CRE::Compliance::Bundle.new(persist, framework) + bundle.write(out_path) + persist.close + + io.puts "evidence bundle written to #{out_path}" + 0 + rescue ex + io.puts "export failed: #{ex.message}" + 1 + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/policy.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/policy.cr new file mode 100644 index 00000000..ec9a8228 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/policy.cr @@ -0,0 +1,75 @@ +# =================== +# ©AngelaMos | 2026 +# policy.cr +# =================== + +require "../../policy/policy" + +module CRE::Cli::Commands + class Policy + def execute(argv : Array(String), io : IO) : Int32 + sub = argv.shift? + case sub + when "list" then list(argv, io) + when "show" then show(argv, io) + when nil, "--help", "-h" + io.puts "Usage: cre policy >" + 0 + else + io.puts "unknown policy subcommand: #{sub}" + 64 + end + end + + private def list(argv : Array(String), io : IO) : Int32 + output_format = OutputFormat::Human + OptionParser.parse(argv) do |parser| + parser.on("--output=FORMAT", "human|json") { |f| output_format = Output.parse_format(f) } + end + + policies = CRE::Policy.registry + case output_format + in OutputFormat::Human + if policies.empty? + io.puts "(no policies compiled in)" + else + io.puts "Compiled policies:" + policies.each { |p| io.puts " - #{p.name} (max_age=#{p.max_age}, enforce=#{p.enforce_action.to_s.downcase})" } + end + in OutputFormat::Json, OutputFormat::Ndjson + rows = policies.map do |p| + { + "name" => p.name, + "max_age" => p.max_age.to_s, + "enforce" => p.enforce_action.to_s.downcase, + "warn_at" => p.warn_at.try(&.to_s), + } + end + Output.print(io, output_format, rows) + end + 0 + end + + private def show(argv : Array(String), io : IO) : Int32 + name = argv.shift? + if name.nil? + io.puts "usage: cre policy show " + return 64 + end + policy = CRE::Policy.registry.find { |p| p.name == name } + if policy.nil? + io.puts "policy not found: #{name}" + return 1 + end + io.puts "name: #{policy.name}" + io.puts "desc: #{policy.description || "(none)"}" + io.puts "max_age: #{policy.max_age}" + io.puts "warn_at: #{policy.warn_at || "(none)"}" + io.puts "enforce: #{policy.enforce_action.to_s.downcase}" + io.puts "channels: #{policy.notify_channels.map(&.to_s.downcase).join(", ")}" + io.puts "triggers:" + policy.triggers.each { |k, v| io.puts " #{k.to_s.downcase}: #{v.to_s.downcase}" } + 0 + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/rotate.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/rotate.cr new file mode 100644 index 00000000..d57ae558 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/rotate.cr @@ -0,0 +1,80 @@ +# =================== +# ©AngelaMos | 2026 +# rotate.cr +# =================== + +require "../bootstrap" +require "../../engine/event_bus" +require "../../engine/rotation_orchestrator" +require "../../engine/rotation_worker" + +module CRE::Cli::Commands + class Rotate + def execute(argv : Array(String), io : IO) : Int32 + _help_requested = false + db_url = ENV["DATABASE_URL"]? || "sqlite:cre.db" + cred_id_str = nil + + OptionParser.parse(argv) do |parser| + parser.banner = "Usage: cre rotate [options]" + parser.on("--db=URL", "database URL (sqlite:path or postgres://...)") { |u| db_url = u } + parser.on("-h", "--help") { _help_requested = true; io.puts parser } + parser.unknown_args { |args| cred_id_str = args.first? } + end + return 0 if _help_requested + + if cred_id_str.nil? + io.puts "usage: cre rotate " + return 64 + end + + cred_id = UUID.new(cred_id_str.not_nil!) rescue nil + if cred_id.nil? + io.puts "invalid credential id" + return 64 + end + + envelope = CRE::Cli::Bootstrap.envelope + + persist = CRE::Cli::Bootstrap.build_persistence(db_url) + persist.migrate! + + cred = persist.credentials.find(cred_id) + if cred.nil? + io.puts "credential not found: #{cred_id}" + persist.close + return 1 + end + + bus = CRE::Engine::EventBus.new + bus.run + orchestrator = CRE::Engine::RotationOrchestrator.new(bus, persist, envelope) + worker = CRE::Engine::RotationWorker.new(bus, orchestrator, persist) + CRE::Cli::Bootstrap.register_rotators(worker, io) + + rotator = worker.rotator_for_kind(cred.kind) + if rotator.nil? + io.puts "no rotator registered for #{cred.kind} (set the matching env vars; see README)" + bus.stop + persist.close + return 1 + end + + io.puts "Rotating #{cred.name} (#{cred.id}) via #{rotator.kind}..." + state = orchestrator.run(cred, rotator) + sleep 0.1.seconds + bus.stop + persist.close + + case state + when CRE::Persistence::RotationState::Completed then io.puts "✓ rotation completed"; 0 + when CRE::Persistence::RotationState::Failed then io.puts "✗ rotation failed"; 1 + when CRE::Persistence::RotationState::Inconsistent then io.puts "✗ rotation INCONSISTENT — manual intervention required"; 2 + else io.puts "rotation ended in unexpected state #{state}"; 2 + end + rescue ex : CRE::Cli::Bootstrap::ConfigError + io.puts "configuration error: #{ex.message}" + 78 + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/run.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/run.cr new file mode 100644 index 00000000..62e4ca7a --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/run.cr @@ -0,0 +1,137 @@ +# =================== +# ©AngelaMos | 2026 +# run.cr +# =================== + +require "../bootstrap" +require "../../engine/engine" +require "../../engine/scheduler" +require "../../engine/rotation_orchestrator" +require "../../engine/rotation_worker" +require "../../audit/batch_sealer" +require "../../audit/batch_sealer_scheduler" +require "../../policy/evaluator" +require "../../notifiers/log_notifier" +require "../../notifiers/telegram" +require "../../notifiers/telegram_subscriber" +require "../../notifiers/telegram_bot" + +module CRE::Cli::Commands + class Run + class StartStop + def initialize(@start_proc : Proc(Nil), @stop_proc : Proc(Nil)) + end + + def start : Nil + @start_proc.call + end + + def stop : Nil + @stop_proc.call + end + end + + def execute(argv : Array(String), io : IO) : Int32 + _help_requested = false + db_url = ENV["DATABASE_URL"]? || "sqlite:cre.db" + interval = (ENV["CRE_TICK_SECONDS"]? || "60").to_i + + OptionParser.parse(argv) do |parser| + parser.banner = "Usage: cre run [options]" + parser.on("--db=URL", "database URL (sqlite:path or postgres://...)") { |u| db_url = u } + parser.on("--interval=SECONDS", "scheduler tick interval") { |i| interval = i.to_i } + parser.on("-h", "--help") { _help_requested = true; io.puts parser } + end + return 0 if _help_requested + + hmac_key = Bootstrap.require_hmac_key + envelope = Bootstrap.require_envelope + signer = Bootstrap.signer + + persist = Bootstrap.build_persistence(db_url) + persist.migrate! + + engine = CRE::Engine::Engine.new(persist, hmac_key) + log_notifier = CRE::Notifiers::LogNotifier.new(engine.bus) + evaluator = CRE::Policy::Evaluator.new(engine.bus, persist) + scheduler = CRE::Engine::Scheduler.new(engine.bus, interval.seconds) + + orchestrator = CRE::Engine::RotationOrchestrator.new(engine.bus, persist, envelope) + worker = CRE::Engine::RotationWorker.new(engine.bus, orchestrator, persist) + Bootstrap.register_rotators(worker, io) + + sealer_scheduler = if signer_obj = signer + sealer = CRE::Audit::BatchSealer.new(persist, signer_obj) + CRE::Audit::BatchSealerScheduler.new(engine.bus, sealer, Bootstrap.seal_interval) + end + + telegram_pieces = wire_telegram(engine.bus, persist, io) + + engine.start + log_notifier.start + worker.start + evaluator.start + scheduler.start + sealer_scheduler.try(&.start) + telegram_pieces.each(&.start) + + io.puts "cre running. PID #{Process.pid}, tick #{interval}s, db #{Bootstrap.redact_db_url(db_url)}" + io.puts "rotators: #{worker.kinds.map(&.to_s).join(", ")}" + io.puts "envelope: AES-256-GCM (KEK v#{ENV[Bootstrap::KEK_VERSION_VAR]? || "1"})" + io.puts "audit batches: #{sealer_scheduler.nil? ? "(disabled — set #{Bootstrap::SIGNING_KEY_VAR})" : "every #{Bootstrap.seal_interval.total_seconds.to_i}s"}" + io.puts "telegram: #{telegram_pieces.empty? ? "(disabled)" : "enabled"}" + + stop_signal = Channel(Nil).new + Signal::INT.trap do + io.puts "\nshutting down..." + scheduler.stop + evaluator.stop + worker.stop + sealer_scheduler.try(&.stop) + log_notifier.stop + telegram_pieces.each(&.stop) + engine.stop + persist.close + stop_signal.send(nil) rescue nil + end + + stop_signal.receive + 0 + rescue ex : CRE::Cli::Bootstrap::ConfigError + io.puts "configuration error: #{ex.message}" + 78 # EX_CONFIG + end + + private def wire_telegram(bus : CRE::Engine::EventBus, persist : CRE::Persistence::Persistence, io : IO) : Array(StartStop) + pieces = [] of StartStop + + token = ENV["TELEGRAM_TOKEN"]? + return pieces if token.nil? || token.empty? + + viewer_chats = parse_chat_ids(ENV["TELEGRAM_VIEWER_CHATS"]?) + operator_chats = parse_chat_ids(ENV["TELEGRAM_OPERATOR_CHATS"]?) + all_chats = (viewer_chats + operator_chats).uniq + + if all_chats.empty? + io.puts "warning: TELEGRAM_TOKEN set but no TELEGRAM_VIEWER_CHATS / TELEGRAM_OPERATOR_CHATS; skipping bot" + return pieces + end + + telegram = CRE::Notifiers::Telegram.new(token) + sub = CRE::Notifiers::TelegramSubscriber.new(bus, telegram, all_chats) + bot = CRE::Notifiers::TelegramBot.new( + bus: bus, telegram: telegram, persistence: persist, + viewer_chats: viewer_chats, operator_chats: operator_chats, + ) + + pieces << StartStop.new(start_proc: -> { sub.start }, stop_proc: -> { sub.stop }) + pieces << StartStop.new(start_proc: -> { bot.start }, stop_proc: -> { bot.stop }) + pieces + end + + private def parse_chat_ids(raw : String?) : Array(Int64) + return [] of Int64 if raw.nil? || raw.empty? + raw.split(',').map(&.strip).reject(&.empty?).map(&.to_i64) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/tui_demo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/tui_demo.cr new file mode 100644 index 00000000..704026fd --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/tui_demo.cr @@ -0,0 +1,23 @@ +# =================== +# ©AngelaMos | 2026 +# tui_demo.cr +# =================== + +require "../../demo/tui_demo" + +module CRE::Cli::Commands + class TuiDemo + def execute(argv : Array(String), io : IO) : Int32 + _help_requested = false + seconds = 8 + OptionParser.parse(argv) do |parser| + parser.banner = "Usage: cre tui-demo [--seconds=N]" + parser.on("--seconds=N", "duration in seconds (default 8)") { |s| seconds = s.to_i } + parser.on("-h", "--help") { _help_requested = true; io.puts parser } + end + return 0 if _help_requested + + CRE::Demo::TuiDemo.run(io, seconds) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/verify_bundle.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/verify_bundle.cr new file mode 100644 index 00000000..1642fa4e --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/verify_bundle.cr @@ -0,0 +1,218 @@ +# =================== +# ©AngelaMos | 2026 +# verify_bundle.cr +# =================== + +require "compress/zip" +require "json" +require "openssl/digest" +require "../../audit/hash_chain" +require "../../audit/signing" +require "../../audit/merkle" + +module CRE::Cli::Commands + # VerifyBundle reads a compliance evidence ZIP produced by 'cre export' + # and re-runs every check the bundle's README documents: + # + # 1. Per-file SHA-256 vs manifest.json + # 2. Manifest Ed25519 signature vs public_key.pem (if both present) + # 3. Audit log hash chain reconstruction + # 4. Audit batch Merkle-root + signature reconstruction + # + # Exit codes: + # 0 - all checks passed + # 2 - one or more checks failed + # 64 - usage error + class VerifyBundle + def execute(argv : Array(String), io : IO) : Int32 + _help_requested = false + bundle_path = nil + + OptionParser.parse(argv) do |parser| + parser.banner = "Usage: cre verify-bundle " + parser.on("-h", "--help") { _help_requested = true; io.puts parser } + parser.unknown_args { |args| bundle_path = args.first? } + end + return 0 if _help_requested + + if bundle_path.nil? + io.puts "usage: cre verify-bundle " + return 64 + end + bundle = bundle_path.not_nil! + + unless File.exists?(bundle) + io.puts "bundle not found: #{bundle}" + return 2 + end + + contents = read_zip(bundle) + manifest_text = contents["manifest.json"]? + if manifest_text.nil? + io.puts "✗ bundle is missing manifest.json" + return 2 + end + manifest = JSON.parse(manifest_text) + + checks_passed = true + checks_passed &= verify_checksums(io, contents, manifest) + checks_passed &= verify_manifest_signature(io, contents, manifest_text) + checks_passed &= verify_hash_chain(io, contents) + checks_passed &= verify_batches(io, contents) + + if checks_passed + io.puts "✓ bundle valid" + 0 + else + io.puts "✗ bundle FAILED verification" + 2 + end + end + + private def read_zip(path : String) : Hash(String, String) + out = {} of String => String + Compress::Zip::File.open(path) do |zip| + zip.entries.each do |entry| + out[entry.filename] = entry.open(&.gets_to_end) + end + end + out + end + + private def verify_checksums(io : IO, contents : Hash(String, String), manifest : JSON::Any) : Bool + ok = true + manifest["files"].as_a.each do |entry| + name = entry["name"].as_s + expected = entry["sha256"].as_s + body = contents[name]? + if body.nil? + io.puts " ✗ checksum: missing #{name}" + ok = false + next + end + actual = sha256_hex(body) + if actual != expected + io.puts " ✗ checksum mismatch on #{name}: expected #{expected}, got #{actual}" + ok = false + end + end + io.puts " ✓ #{manifest["files"].as_a.size} file checksums match" if ok + ok + end + + private def verify_manifest_signature(io : IO, contents : Hash(String, String), manifest_text : String) : Bool + sig_b64 = contents["manifest.sig"]? + pubkey_hex = contents["public_key.pem"]? + if sig_b64.nil? || pubkey_hex.nil? + io.puts " - manifest.sig / public_key.pem absent — signature step skipped" + return true + end + + sig = Base64.decode(sig_b64.strip) + key_bytes = pubkey_hex.strip.hexbytes + verifier = CRE::Audit::Signing::Ed25519Verifier.new(key_bytes) + if verifier.verify(manifest_text.to_slice, sig) + io.puts " ✓ manifest signature valid" + true + else + io.puts " ✗ manifest signature INVALID" + false + end + rescue ex + io.puts " ✗ manifest signature verification error: #{ex.message}" + false + end + + private def verify_hash_chain(io : IO, contents : Hash(String, String)) : Bool + ndjson = contents["audit_log.ndjson"]? + if ndjson.nil? || ndjson.empty? + io.puts " - audit_log.ndjson empty — hash chain step skipped" + return true + end + + prev = Bytes.new(32, 0_u8) + lineno = 0 + ndjson.each_line do |line| + lineno += 1 + next if line.empty? + row = JSON.parse(line) + # The exporter writes 'payload' as the canonical JSON the log used + # when computing content_hash, so we hash that string verbatim. + canonical = row["payload"].as_s + expected = CRE::Audit::HashChain.next_hash(prev, canonical.to_slice) + actual = row["content_hash_hex"].as_s.hexbytes + unless expected == actual + io.puts " ✗ hash chain broken at seq=#{row["seq"]?} (line #{lineno})" + return false + end + prev = actual + end + io.puts " ✓ hash chain valid (#{lineno} entries)" + true + end + + private def verify_batches(io : IO, contents : Hash(String, String)) : Bool + batches_json = contents["audit_batches.json"]? + pubkey_hex = contents["public_key.pem"]? + if batches_json.nil? || batches_json == "[]" + io.puts " - audit_batches.json empty — batch verify skipped" + return true + end + if pubkey_hex.nil? + io.puts " ✗ batches present but public_key.pem absent — cannot verify" + return false + end + + verifier = CRE::Audit::Signing::Ed25519Verifier.new(pubkey_hex.strip.hexbytes) + ndjson = contents["audit_log.ndjson"]? || "" + content_hashes_by_seq = {} of Int64 => Bytes + ndjson.each_line do |line| + next if line.empty? + row = JSON.parse(line) + content_hashes_by_seq[row["seq"].as_i64] = row["content_hash_hex"].as_s.hexbytes + end + + batches = JSON.parse(batches_json).as_a + batches.each do |b| + start_seq = b["start_seq"].as_i64 + end_seq = b["end_seq"].as_i64 + leaves = (start_seq..end_seq).map do |seq| + h = content_hashes_by_seq[seq]? + if h.nil? + io.puts " ✗ batch covers seq=#{seq} but ndjson is missing it" + return false + end + h + end + recomputed = CRE::Audit::Merkle.root(leaves) + stored = b["merkle_root_hex"].as_s.hexbytes + unless recomputed == stored + io.puts " ✗ Merkle root mismatch on batch [#{start_seq}..#{end_seq}]" + return false + end + msg = pack_batch_message(start_seq, end_seq, stored) + sig = b["signature_hex"].as_s.hexbytes + unless verifier.verify(msg, sig) + io.puts " ✗ batch signature invalid for [#{start_seq}..#{end_seq}]" + return false + end + end + io.puts " ✓ #{batches.size} audit batches verified" + true + end + + private def pack_batch_message(start_seq : Int64, end_seq : Int64, root : Bytes) : Bytes + io = IO::Memory.new + io.write_bytes(start_seq, IO::ByteFormat::BigEndian) + io.write_bytes(end_seq, IO::ByteFormat::BigEndian) + io.write(root) + io.to_slice + end + + private def sha256_hex(content : String) : String + d = OpenSSL::Digest.new("SHA256") + d.update(content) + d.hexfinal + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/version.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/version.cr new file mode 100644 index 00000000..142315ca --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/version.cr @@ -0,0 +1,14 @@ +# =================== +# ©AngelaMos | 2026 +# version.cr +# =================== + +require "../../version" + +module CRE::Cli::Commands + module Version + def self.print(io : IO) : Nil + io.puts "cre v#{CRE::VERSION}" + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/watch.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/watch.cr new file mode 100644 index 00000000..e35e41f7 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/commands/watch.cr @@ -0,0 +1,82 @@ +# =================== +# ©AngelaMos | 2026 +# watch.cr +# =================== + +require "../bootstrap" +require "../../engine/engine" +require "../../engine/scheduler" +require "../../engine/rotation_orchestrator" +require "../../engine/rotation_worker" +require "../../audit/batch_sealer" +require "../../audit/batch_sealer_scheduler" +require "../../policy/evaluator" +require "../../tui/tui" + +module CRE::Cli::Commands + class Watch + def execute(argv : Array(String), io : IO) : Int32 + _help_requested = false + db_url = ENV["DATABASE_URL"]? || "sqlite:cre.db" + interval = (ENV["CRE_TICK_SECONDS"]? || "60").to_i + + OptionParser.parse(argv) do |parser| + parser.banner = "Usage: cre watch [options]" + parser.on("--db=URL", "database URL (sqlite:path or postgres://...)") { |u| db_url = u } + parser.on("--interval=SECONDS", "scheduler tick interval") { |i| interval = i.to_i } + parser.on("-h", "--help") { _help_requested = true; io.puts parser } + end + return 0 if _help_requested + + hmac_key = Bootstrap.require_hmac_key + envelope = Bootstrap.require_envelope + signer = Bootstrap.signer + + persist = Bootstrap.build_persistence(db_url) + persist.migrate! + + engine = CRE::Engine::Engine.new(persist, hmac_key) + evaluator = CRE::Policy::Evaluator.new(engine.bus, persist) + scheduler = CRE::Engine::Scheduler.new(engine.bus, interval.seconds) + orchestrator = CRE::Engine::RotationOrchestrator.new(engine.bus, persist, envelope) + worker = CRE::Engine::RotationWorker.new(engine.bus, orchestrator, persist) + Bootstrap.register_rotators(worker, io) + + sealer_scheduler = if signer_obj = signer + sealer = CRE::Audit::BatchSealer.new(persist, signer_obj) + CRE::Audit::BatchSealerScheduler.new(engine.bus, sealer, Bootstrap.seal_interval) + end + + kek_version = (ENV[Bootstrap::KEK_VERSION_VAR]? || "1").to_i + tui_state = CRE::Tui::State.new(kek_version: kek_version) + tui_snapshotter = CRE::Tui::Snapshotter.new(tui_state, persist) + tui = CRE::Tui::Tui.new(engine.bus, tui_state) + + engine.start + worker.start + evaluator.start + scheduler.start + sealer_scheduler.try(&.start) + tui_snapshotter.start + tui.start + + Signal::INT.trap do + tui.stop + tui_snapshotter.stop + scheduler.stop + evaluator.stop + worker.stop + sealer_scheduler.try(&.stop) + engine.stop + persist.close + exit 0 + end + + sleep + 0 + rescue ex : CRE::Cli::Bootstrap::ConfigError + io.puts "configuration error: #{ex.message}" + 78 + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/output.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/output.cr new file mode 100644 index 00000000..aee755e4 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/cli/output.cr @@ -0,0 +1,41 @@ +# =================== +# ©AngelaMos | 2026 +# output.cr +# =================== + +require "json" + +module CRE::Cli + enum OutputFormat + Human + Json + Ndjson + end + + module Output + def self.parse_format(s : String) : OutputFormat + case s.downcase + when "human" then OutputFormat::Human + when "json" then OutputFormat::Json + when "ndjson" then OutputFormat::Ndjson + else + raise "unknown output format: #{s} (valid: human, json, ndjson)" + end + end + + def self.print(io : IO, format : OutputFormat, data) : Nil + case format + in OutputFormat::Human + io.puts data.to_s + in OutputFormat::Json + io.puts data.to_json + in OutputFormat::Ndjson + if data.is_a?(Array) + data.each { |row| io.puts row.to_json } + else + io.puts data.to_json + end + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/compliance/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/compliance/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/compliance/bundle.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/compliance/bundle.cr new file mode 100644 index 00000000..39df8aca --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/compliance/bundle.cr @@ -0,0 +1,172 @@ +# =================== +# ©AngelaMos | 2026 +# bundle.cr +# =================== + +require "compress/zip" +require "json" +require "openssl/digest" +require "../persistence/persistence" +require "../persistence/repos" +require "../audit/signing" +require "./control_mapping" + +module CRE::Compliance + # Bundle assembles a self-verifying evidence ZIP for a compliance auditor. + # Layout: + # evidence.zip/ + # README.md - what's in here, how to verify + # manifest.json - file checksums + signature + # audit_log.ndjson - raw audit events with hash-chain fields + # audit_batches.json - signed Merkle batch roots over the period + # public_key.pem - Ed25519 public key (32 hex bytes; SHA-256 + # covered by manifest so substitution shows + # up as a manifest checksum mismatch) + # control_mapping.json - event_type -> framework controls + class Bundle + record FileEntry, name : String, sha256_hex : String, size : Int32 + + def initialize( + @persistence : Persistence::Persistence, + @framework : String, + @signer : Audit::Signing::Ed25519Signer? = nil, + @public_key_hex : String? = nil, + ) + end + + def write(path : String) : Nil + File.open(path, "w") do |fp| + Compress::Zip::Writer.open(fp) do |zip| + # 1) build raw bytes for every file we plan to ship + payload_files = [] of {String, String} + payload_files << {"audit_log.ndjson", build_audit_log_ndjson} + payload_files << {"audit_batches.json", build_audit_batches_json} + payload_files << {"control_mapping.json", build_control_mapping_json} + if pem = @public_key_hex + payload_files << {"public_key.pem", pem} + end + + # 2) compute checksums and build manifest covering ALL payload files + # (including public_key.pem so substitution invalidates the manifest sig) + payload_entries = payload_files.map do |(name, content)| + FileEntry.new(name: name, sha256_hex: sha256_hex(content), size: content.bytesize) + end + readme = build_readme(payload_entries) + payload_files << {"README.md", readme} + payload_entries << FileEntry.new(name: "README.md", sha256_hex: sha256_hex(readme), size: readme.bytesize) + + manifest = build_manifest(payload_entries) + + # 3) emit zip in dependency order + payload_files.each { |(name, content)| add_file(zip, name, content) } + add_file(zip, "manifest.json", manifest) + if signer = @signer + sig = signer.sign(manifest.to_slice) + add_file(zip, "manifest.sig", Base64.encode(sig)) + end + end + end + end + + private def add_file(zip, name : String, content : String) : Nil + zip.add(name) { |io| io << content } + end + + private def build_audit_log_ndjson : String + latest = @persistence.audit.latest_seq + return "" if latest == 0 + io = IO::Memory.new + @persistence.audit.each_in_range(1_i64, latest) do |entry| + row = { + "seq" => entry.seq, + "event_id" => entry.event_id.to_s, + "occurred_at" => entry.occurred_at.to_rfc3339, + "event_type" => entry.event_type, + "actor" => entry.actor, + "target_id" => entry.target_id.try(&.to_s), + "payload" => entry.payload, + "prev_hash_hex" => entry.prev_hash.hexstring, + "content_hash_hex" => entry.content_hash.hexstring, + "hmac_hex" => entry.hmac.hexstring, + "hmac_key_version" => entry.hmac_key_version, + } + row.to_json(io) + io << '\n' + end + io.to_s + end + + private def build_audit_batches_json : String + batches = @persistence.audit.all_batches + return "[]" if batches.empty? + rows = batches.map do |b| + { + "id" => b.id.to_s, + "start_seq" => b.start_seq, + "end_seq" => b.end_seq, + "merkle_root_hex" => b.merkle_root.hexstring, + "signature_hex" => b.signature.hexstring, + "signing_key_version" => b.signing_key_version, + "sealed_at" => b.sealed_at.to_rfc3339, + } + end + rows.to_json + end + + private def build_control_mapping_json : String + ControlMapping.for(@framework).to_json + end + + private def build_manifest(entries : Array(FileEntry)) : String + { + "framework" => @framework, + "generated" => Time.utc.to_rfc3339, + "files" => entries.map { |e| + {"name" => e.name, "sha256" => e.sha256_hex, "size" => e.size} + }, + }.to_json + end + + private def build_readme(_entries : Array(FileEntry)) : String + <<-MD + Credential Rotation Enforcer - Compliance Evidence Bundle + + Framework: #{@framework} + Generated: #{Time.utc.to_rfc3339} + + Contents: + - audit_log.ndjson raw audit events with hash-chain fields + - audit_batches.json signed Merkle batches over the period + - control_mapping.json event_type -> framework controls + - public_key.pem Ed25519 public key (32 hex bytes) + - manifest.json per-file SHA-256 checksums (covers public_key.pem) + - manifest.sig Ed25519 signature of manifest.json (if signed) + + Verification: + cre verify-bundle + + Manual verification: + 1. Recompute SHA-256 of every file listed in manifest.json and compare. + 2. Verify manifest.sig over manifest.json using public_key.pem. + 3. Walk audit_log.ndjson and recompute the hash chain - each row's + content_hash should equal SHA256(prev_hash || canonical(payload)). + 4. For each row in audit_batches.json, recompute the Merkle root over + content_hashes in [start_seq, end_seq] and verify signature_hex + with public_key.pem. + + Note on public_key.pem trust: + The bundled public key is fingerprint-protected by manifest.json's + SHA-256 entry. The manifest itself is Ed25519-signed; if an adversary + substitutes the key+sig pair, manifest.json's checksum no longer + matches the bundled file. Auditors should still verify the in-bundle + public key's SHA-256 against an out-of-band fingerprint they trust. + MD + end + + private def sha256_hex(content : String) : String + d = OpenSSL::Digest.new("SHA256") + d.update(content) + d.hexfinal + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/compliance/control_mapping.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/compliance/control_mapping.cr new file mode 100644 index 00000000..9cef80f6 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/compliance/control_mapping.cr @@ -0,0 +1,66 @@ +# =================== +# ©AngelaMos | 2026 +# control_mapping.cr +# =================== + +module CRE::Compliance + # ControlMapping is the lookup that turns audit event_types into the specific + # framework controls they satisfy. The mapping is intentionally opinionated - + # each event maps only to controls where it provides direct evidence, not + # speculative coverage. + module ControlMapping + SOC2 = { + "rotation.completed" => ["CC6.1", "CC6.6"], + "rotation.failed" => ["CC6.6", "CC7.2"], + "rotation.step.completed" => ["CC6.1"], + "rotation.step.failed" => ["CC6.6", "CC7.2"], + "policy.violation" => ["CC6.7", "CC7.2"], + "drift.detected" => ["CC6.6", "CC7.2"], + "audit.batch.sealed" => ["CC4.1", "CC7.1"], + "key.rotation.kek" => ["CC6.1"], + "credential.discovered" => ["CC6.1"], + "alert.raised" => ["CC7.2"], + } + + PCI_DSS = { + "rotation.completed" => ["8.3.9", "8.6.3"], + "rotation.failed" => ["8.3.9", "10.2.1"], + "policy.violation" => ["8.6.3", "10.2.1"], + "drift.detected" => ["10.2.1", "11.5.2"], + "audit.batch.sealed" => ["10.5.2", "10.5.3"], + "key.rotation.kek" => ["3.7.4"], + } + + ISO27001 = { + "rotation.completed" => ["A.5.16", "A.5.17"], + "rotation.failed" => ["A.5.17", "A.8.5"], + "policy.violation" => ["A.5.18"], + "drift.detected" => ["A.8.16"], + "audit.batch.sealed" => ["A.8.15"], + "key.rotation.kek" => ["A.8.24"], + } + + HIPAA = { + "rotation.completed" => ["164.308(a)(5)(ii)(D)"], + "rotation.failed" => ["164.308(a)(5)(ii)(D)", "164.308(a)(6)(ii)"], + "policy.violation" => ["164.308(a)(5)(ii)(D)"], + "drift.detected" => ["164.308(a)(6)(ii)"], + "audit.batch.sealed" => ["164.312(b)"], + } + + def self.for(framework : String) : Hash(String, Array(String)) + case framework.downcase + when "soc2" then SOC2 + when "pci_dss" then PCI_DSS + when "iso27001" then ISO27001 + when "hipaa" then HIPAA + else + raise ArgumentError.new("unknown framework: #{framework} (valid: soc2, pci_dss, iso27001, hipaa)") + end + end + + def self.frameworks : Array(String) + %w[soc2 pci_dss iso27001 hipaa] + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/config/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/config/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/aead.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/aead.cr new file mode 100644 index 00000000..797b1383 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/aead.cr @@ -0,0 +1,100 @@ +# =================== +# ©AngelaMos | 2026 +# aead.cr +# =================== + +require "openssl" +require "openssl/lib_crypto" + +lib LibCrypto + fun evp_cipher_ctx_ctrl_cre = EVP_CIPHER_CTX_ctrl(ctx : EVP_CIPHER_CTX, type : LibC::Int, arg : LibC::Int, ptr : Void*) : LibC::Int + fun evp_aes_256_gcm_cre = EVP_aes_256_gcm : EVP_CIPHER +end + +module CRE::Crypto + module Aead + NONCE_SIZE = 12 + TAG_SIZE = 16 + + EVP_CTRL_GCM_SET_IVLEN = 0x9 + EVP_CTRL_GCM_GET_TAG = 0x10 + EVP_CTRL_GCM_SET_TAG = 0x11 + + class Error < OpenSSL::Error; end + + def self.encrypt(plaintext : Bytes, key : Bytes, aad : Bytes) : {Bytes, Bytes, Bytes} + raise ArgumentError.new("key must be 32 bytes (AES-256)") unless key.size == 32 + ctx = LibCrypto.evp_cipher_ctx_new + raise Error.new("EVP_CIPHER_CTX_new") if ctx.null? + begin + nonce = ::Random::Secure.random_bytes(NONCE_SIZE) + cipher = LibCrypto.evp_aes_256_gcm_cre + + check(LibCrypto.evp_cipherinit_ex(ctx, cipher, Pointer(Void).null, Pointer(UInt8).null, Pointer(UInt8).null, 1), "EncryptInit (cipher)") + check(LibCrypto.evp_cipher_ctx_ctrl_cre(ctx, EVP_CTRL_GCM_SET_IVLEN, NONCE_SIZE, Pointer(Void).null), "set IV len") + check(LibCrypto.evp_cipherinit_ex(ctx, Pointer(Void).null.as(LibCrypto::EVP_CIPHER), Pointer(Void).null, key.to_unsafe, nonce.to_unsafe, 1), "EncryptInit (key/iv)") + + unless aad.empty? + aad_outl = 0 + check(LibCrypto.evp_cipherupdate(ctx, Pointer(UInt8).null, pointerof(aad_outl), aad.to_unsafe, aad.size), "EncryptUpdate (AAD)") + end + + ct_buf = Bytes.new(plaintext.size + 16) + outl = 0 + check(LibCrypto.evp_cipherupdate(ctx, ct_buf.to_unsafe, pointerof(outl), plaintext.to_unsafe, plaintext.size), "EncryptUpdate (data)") + ct_size = outl + + final_outl = 0 + check(LibCrypto.evp_cipherfinal_ex(ctx, ct_buf.to_unsafe + ct_size, pointerof(final_outl)), "EncryptFinal_ex") + ct_size += final_outl + + tag = Bytes.new(TAG_SIZE) + check(LibCrypto.evp_cipher_ctx_ctrl_cre(ctx, EVP_CTRL_GCM_GET_TAG, TAG_SIZE, tag.to_unsafe.as(Void*)), "get tag") + + {ct_buf[0, ct_size], nonce, tag} + ensure + LibCrypto.evp_cipher_ctx_free(ctx) + end + end + + def self.decrypt(ciphertext : Bytes, key : Bytes, aad : Bytes, nonce : Bytes, tag : Bytes) : Bytes + raise ArgumentError.new("key must be 32 bytes") unless key.size == 32 + ctx = LibCrypto.evp_cipher_ctx_new + raise Error.new("EVP_CIPHER_CTX_new") if ctx.null? + begin + cipher = LibCrypto.evp_aes_256_gcm_cre + + check(LibCrypto.evp_cipherinit_ex(ctx, cipher, Pointer(Void).null, Pointer(UInt8).null, Pointer(UInt8).null, 0), "DecryptInit (cipher)") + check(LibCrypto.evp_cipher_ctx_ctrl_cre(ctx, EVP_CTRL_GCM_SET_IVLEN, NONCE_SIZE, Pointer(Void).null), "set IV len") + check(LibCrypto.evp_cipherinit_ex(ctx, Pointer(Void).null.as(LibCrypto::EVP_CIPHER), Pointer(Void).null, key.to_unsafe, nonce.to_unsafe, 0), "DecryptInit (key/iv)") + + unless aad.empty? + aad_outl = 0 + check(LibCrypto.evp_cipherupdate(ctx, Pointer(UInt8).null, pointerof(aad_outl), aad.to_unsafe, aad.size), "DecryptUpdate (AAD)") + end + + pt_buf = Bytes.new(ciphertext.size + 16) + outl = 0 + check(LibCrypto.evp_cipherupdate(ctx, pt_buf.to_unsafe, pointerof(outl), ciphertext.to_unsafe, ciphertext.size), "DecryptUpdate (data)") + pt_size = outl + + check(LibCrypto.evp_cipher_ctx_ctrl_cre(ctx, EVP_CTRL_GCM_SET_TAG, TAG_SIZE, tag.to_unsafe.as(Void*)), "set tag") + + final_outl = 0 + result = LibCrypto.evp_cipherfinal_ex(ctx, pt_buf.to_unsafe + pt_size, pointerof(final_outl)) + if result <= 0 + raise Error.new("AEAD authentication failed (tag mismatch / tampered ciphertext)") + end + pt_size += final_outl + + pt_buf[0, pt_size] + ensure + LibCrypto.evp_cipher_ctx_free(ctx) + end + end + + private def self.check(rc : LibC::Int, what : String) : Nil + raise Error.new("#{what} failed (rc=#{rc})") unless rc == 1 + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/envelope.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/envelope.cr new file mode 100644 index 00000000..7e9b911a --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/envelope.cr @@ -0,0 +1,72 @@ +# =================== +# ©AngelaMos | 2026 +# envelope.cr +# =================== + +require "./aead" +require "./kek" +require "./random" + +module CRE::Crypto + ALGORITHM_AES_256_GCM = 1_i16 + + struct SealedSecret + getter ciphertext : Bytes + getter dek_wrapped : Bytes + getter kek_version : Int32 + getter algorithm_id : Int16 + + def initialize(@ciphertext, @dek_wrapped, @kek_version, @algorithm_id) + end + end + + class Envelope + def initialize(@kek : Kek::Kek) + end + + def seal(plaintext : Bytes, aad : Bytes) : SealedSecret + dek = Random.bytes(32) + ct, nonce, tag = Aead.encrypt(plaintext, dek, aad) + packed_ct = pack(nonce, tag, ct) + + wrap_aad = "kek-wrap|v#{@kek.version}".to_slice + wrapped_ct, wrap_nonce, wrap_tag = Aead.encrypt(dek, @kek.bytes, wrap_aad) + packed_wrap = pack(wrap_nonce, wrap_tag, wrapped_ct) + + SealedSecret.new( + ciphertext: packed_ct, + dek_wrapped: packed_wrap, + kek_version: @kek.version, + algorithm_id: ALGORITHM_AES_256_GCM, + ) + end + + def open(sealed : SealedSecret, aad : Bytes) : Bytes + raise "unsupported algorithm_id #{sealed.algorithm_id}" unless sealed.algorithm_id == ALGORITHM_AES_256_GCM + raise "kek version mismatch (sealed=#{sealed.kek_version}, kek=#{@kek.version})" unless sealed.kek_version == @kek.version + + wrap_nonce, wrap_tag, wrapped = unpack(sealed.dek_wrapped) + wrap_aad = "kek-wrap|v#{@kek.version}".to_slice + dek = Aead.decrypt(wrapped, @kek.bytes, wrap_aad, wrap_nonce, wrap_tag) + + nonce, tag, ct = unpack(sealed.ciphertext) + Aead.decrypt(ct, dek, aad, nonce, tag) + end + + private def pack(nonce : Bytes, tag : Bytes, body : Bytes) : Bytes + io = IO::Memory.new(nonce.size + tag.size + body.size) + io.write(nonce); io.write(tag); io.write(body) + io.to_slice + end + + private def unpack(packed : Bytes) : {Bytes, Bytes, Bytes} + n = Aead::NONCE_SIZE + t = Aead::TAG_SIZE + raise "packed too small" if packed.size < n + t + nonce = packed[0, n] + tag = packed[n, t] + body = packed[n + t, packed.size - n - t] + {nonce, tag, body} + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/kek.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/kek.cr new file mode 100644 index 00000000..54bb6f80 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/kek.cr @@ -0,0 +1,33 @@ +# =================== +# ©AngelaMos | 2026 +# kek.cr +# =================== + +module CRE::Crypto + module Kek + class InvalidKekError < Exception; end + + abstract class Kek + abstract def bytes : Bytes + abstract def version : Int32 + abstract def source : String + end + + class EnvKek < Kek + getter bytes : Bytes + getter version : Int32 + getter source : String + + def initialize(env_var : String, @version : Int32) + @source = "env:#{env_var}" + hex = ENV[env_var]? || raise InvalidKekError.new("ENV[#{env_var}] not set") + raise InvalidKekError.new("expected 64-char hex (32 bytes), got #{hex.size}") unless hex.size == 64 + @bytes = hex.hexbytes + end + + protected def bytes_writer=(b : Bytes) : Nil + @bytes = b + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/random.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/random.cr new file mode 100644 index 00000000..c7b0f3d8 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/crypto/random.cr @@ -0,0 +1,25 @@ +# =================== +# ©AngelaMos | 2026 +# random.cr +# =================== + +require "random/secure" + +module CRE::Crypto + module Random + def self.bytes(n : Int32) : Bytes + ::Random::Secure.random_bytes(n) + end + + def self.hex(n : Int32) : String + bytes(n).hexstring + end + + def self.constant_time_equal?(a : Bytes, b : Bytes) : Bool + return false unless a.size == b.size + diff = 0_u8 + a.size.times { |i| diff |= a[i] ^ b[i] } + diff == 0_u8 + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/demo/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/demo/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/demo/tier_1.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/demo/tier_1.cr new file mode 100644 index 00000000..3f384aa1 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/demo/tier_1.cr @@ -0,0 +1,121 @@ +# =================== +# ©AngelaMos | 2026 +# tier_1.cr +# =================== + +require "../engine/event_bus" +require "../engine/rotation_orchestrator" +require "../engine/subscribers/audit_subscriber" +require "../persistence/sqlite/sqlite_persistence" +require "../rotators/env_file" +require "../audit/audit_log" +require "../tui/ansi" + +module CRE::Demo + module Tier1 + def self.run(io : IO) : Int32 + tmp_env = File.tempname("cre-demo-", ".env") + File.write(tmp_env, "API_KEY=oldvalue-aaa\nOTHER=keep\n") + + io.puts CRE::Tui::Ansi.cyan("Credential Rotation Enforcer - Tier 1 demo") + io.puts " (in-memory SQLite + ephemeral .env file rotator, zero external deps)" + io.puts "" + + persist = CRE::Persistence::Sqlite::SqlitePersistence.new(":memory:") + persist.migrate! + log = CRE::Audit::AuditLog.new(persist, Bytes.new(32, 0_u8), 1, 1024) + + cred_id = UUID.random + cred = CRE::Domain::Credential.new( + id: cred_id, + external_id: "demo-#{tmp_env}", + kind: CRE::Domain::CredentialKind::EnvFile, + name: "API_KEY", + tags: { + "path" => tmp_env, + "key" => "API_KEY", + "bytes" => "16", + } of String => String, + updated_at: Time.utc - 60.days, + ) + persist.credentials.insert(cred) + + io.puts CRE::Tui::Ansi.bold("Step 1 - Inventory:") + io.puts " - #{cred.kind} '#{cred.name}' (id=#{short(cred.id)})" + io.puts " last updated #{cred.updated_at.to_rfc3339} (60 days ago - overdue)" + io.puts "" + + io.puts CRE::Tui::Ansi.bold("Step 2 - File contents BEFORE:") + File.read(tmp_env).each_line { |line| io.puts " #{line}" } + io.puts "" + + io.puts CRE::Tui::Ansi.bold("Step 3 - Rotating (4-step contract):") + bus = CRE::Engine::EventBus.new + ch = bus.subscribe(buffer: 256) + audit_sub = CRE::Engine::Subscribers::AuditSubscriber.new(bus, log) + audit_sub.start + bus.run + + rotator = CRE::Rotators::EnvFileRotator.new + orchestrator = CRE::Engine::RotationOrchestrator.new(bus, persist) + state = orchestrator.run(cred, rotator) + + sleep 0.15.seconds + drain_steps(ch, io) + + audit_sub.stop + bus.stop + + io.puts "" + io.puts CRE::Tui::Ansi.bold("Step 4 - File contents AFTER:") + File.read(tmp_env).each_line { |line| io.puts " #{line}" } + io.puts "" + + io.puts CRE::Tui::Ansi.bold("Step 5 - Audit chain verification:") + ok = log.verify_chain + latest_seq = persist.audit.latest_seq + if ok + io.puts " #{CRE::Tui::Ansi.green("✓")} #{latest_seq} audit events, hash chain valid" + else + io.puts " #{CRE::Tui::Ansi.red("✗")} audit chain BROKEN" + end + + persist.close + File.delete(tmp_env) if File.exists?(tmp_env) + + io.puts "" + io.puts CRE::Tui::Ansi.dim("Demo complete. State #{state}. Try 'cre run --db=sqlite:cre.db' for the daemon.") + state == CRE::Persistence::RotationState::Completed ? 0 : 1 + end + + private def self.drain_steps(ch : ::Channel(CRE::Events::Event), io : IO) : Nil + loop do + select + when ev = ch.receive + narrate(ev, io) + else + break + end + end + end + + private def self.narrate(ev : CRE::Events::Event, io : IO) : Nil + case ev + when CRE::Events::RotationStepStarted + io.puts " - step started: #{ev.step}" + when CRE::Events::RotationStepCompleted + io.puts " #{CRE::Tui::Ansi.green("✓")} step completed: #{ev.step}" + when CRE::Events::RotationStepFailed + io.puts " #{CRE::Tui::Ansi.red("✗")} step failed: #{ev.step} (#{ev.error})" + when CRE::Events::RotationCompleted + io.puts " #{CRE::Tui::Ansi.green("✓")} rotation completed" + when CRE::Events::RotationFailed + io.puts " #{CRE::Tui::Ansi.red("✗")} rotation failed: #{ev.reason}" + end + end + + private def self.short(uuid : UUID) : String + uuid.to_s[0, 8] + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/demo/tui_demo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/demo/tui_demo.cr new file mode 100644 index 00000000..dc0d0212 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/demo/tui_demo.cr @@ -0,0 +1,116 @@ +# =================== +# ©AngelaMos | 2026 +# tui_demo.cr +# =================== + +require "../engine/event_bus" +require "../tui/tui" +require "../events/credential_events" +require "../events/system_events" + +module CRE::Demo + # TuiDemo synthesizes a stream of fake events so you can SEE what the + # live TUI looks like without running the full daemon. Eight seconds of + # narrated activity, then it shuts down cleanly. + module TuiDemo + def self.run(io : IO = STDOUT, seconds : Int32 = 8) : Int32 + bus = CRE::Engine::EventBus.new + tui = CRE::Tui::Tui.new(bus, io: io, refresh_interval: 150.milliseconds) + bus.run + tui.start + + script_fiber = spawn do + run_script(bus, seconds) + end + + sleep seconds.seconds + 0.5.seconds + tui.stop + bus.stop + 0 + end + + private def self.run_script(bus : CRE::Engine::EventBus, seconds : Int32) : Nil + cred_a = UUID.random + cred_b = UUID.random + cred_c = UUID.random + cred_d = UUID.random + + # 0.5s: a policy violation arrives + sleep 0.5.seconds + bus.publish CRE::Events::PolicyViolation.new(cred_a, "production-databases", "credential exceeded max_age=30.days (last rotated 47 days ago)") + + # 1.0s: rotation A starts + sleep 0.5.seconds + rot_a = UUID.random + bus.publish CRE::Events::RotationStarted.new(cred_a, rot_a, "aws_secretsmgr") + bus.publish CRE::Events::RotationStepStarted.new(cred_a, rot_a, :generate) + + # 1.5s: drift detected on B + sleep 0.5.seconds + bus.publish CRE::Events::DriftDetected.new(cred_b, "abc123def456", "ffe098cba321") + + # 2.0s: rotation A finishes generate, starts apply + sleep 0.5.seconds + bus.publish CRE::Events::RotationStepCompleted.new(cred_a, rot_a, :generate) + bus.publish CRE::Events::RotationStepStarted.new(cred_a, rot_a, :apply) + + # 2.5s: rotation A finishes apply, starts verify + sleep 0.5.seconds + bus.publish CRE::Events::RotationStepCompleted.new(cred_a, rot_a, :apply) + bus.publish CRE::Events::RotationStepStarted.new(cred_a, rot_a, :verify) + + # 3.0s: rotation C starts (parallel) + sleep 0.5.seconds + rot_c = UUID.random + bus.publish CRE::Events::RotationStarted.new(cred_c, rot_c, "github_pat") + bus.publish CRE::Events::RotationStepStarted.new(cred_c, rot_c, :generate) + + # 3.5s: rotation A finishes verify, starts commit + sleep 0.5.seconds + bus.publish CRE::Events::RotationStepCompleted.new(cred_a, rot_a, :verify) + bus.publish CRE::Events::RotationStepStarted.new(cred_a, rot_a, :commit) + + # 4.0s: rotation A complete! + sleep 0.5.seconds + bus.publish CRE::Events::RotationStepCompleted.new(cred_a, rot_a, :commit) + bus.publish CRE::Events::RotationCompleted.new(cred_a, rot_a) + + # 4.5s: alert + a fourth rotation (vault) starts + sleep 0.5.seconds + bus.publish CRE::Events::AlertRaised.new(CRE::Events::Severity::Warn, "5 credentials approaching expiry within 7 days") + rot_d = UUID.random + bus.publish CRE::Events::RotationStarted.new(cred_d, rot_d, "vault_dynamic") + bus.publish CRE::Events::RotationStepStarted.new(cred_d, rot_d, :generate) + + # 5.0s: rotation C finishes generate, then fails on apply + sleep 0.5.seconds + bus.publish CRE::Events::RotationStepCompleted.new(cred_c, rot_c, :generate) + bus.publish CRE::Events::RotationStepStarted.new(cred_c, rot_c, :apply) + + # 5.5s: rotation C apply fails! + sleep 0.5.seconds + bus.publish CRE::Events::RotationStepFailed.new(cred_c, rot_c, :apply, "GitHub API 403 - PAT lacks admin:org scope") + bus.publish CRE::Events::RotationFailed.new(cred_c, rot_c, "GitHub API 403 - PAT lacks admin:org scope") + + # 6.0s: rotation D progresses + sleep 0.5.seconds + bus.publish CRE::Events::RotationStepCompleted.new(cred_d, rot_d, :generate) + bus.publish CRE::Events::RotationStepStarted.new(cred_d, rot_d, :apply) + bus.publish CRE::Events::RotationStepCompleted.new(cred_d, rot_d, :apply) + bus.publish CRE::Events::RotationStepStarted.new(cred_d, rot_d, :verify) + + # 6.5s: critical alert + sleep 0.5.seconds + bus.publish CRE::Events::AlertRaised.new(CRE::Events::Severity::Critical, "1 critical: rotation_failure github_pat/deploy-bot needs manual intervention") + + # 7.0s: rotation D finishes + sleep 0.5.seconds + bus.publish CRE::Events::RotationStepCompleted.new(cred_d, rot_d, :verify) + bus.publish CRE::Events::RotationStepStarted.new(cred_d, rot_d, :commit) + bus.publish CRE::Events::RotationStepCompleted.new(cred_d, rot_d, :commit) + bus.publish CRE::Events::RotationCompleted.new(cred_d, rot_d) + rescue ex + # silence: we may be torn down mid-script + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/credential.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/credential.cr new file mode 100644 index 00000000..f2d76eb2 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/credential.cr @@ -0,0 +1,52 @@ +# =================== +# ©AngelaMos | 2026 +# credential.cr +# =================== + +require "uuid" + +module CRE::Domain + enum CredentialKind + AwsSecretsmgr + VaultDynamic + GithubPat + EnvFile + end + + struct Credential + getter id : UUID + getter external_id : String + getter kind : CredentialKind + getter name : String + getter tags : Hash(String, String) + getter current_version_id : UUID? + getter pending_version_id : UUID? + getter previous_version_id : UUID? + getter created_at : Time + getter updated_at : Time + getter last_rotated_at : Time? + + def initialize( + @id : UUID, + @external_id : String, + @kind : CredentialKind, + @name : String, + @tags : Hash(String, String), + @current_version_id : UUID? = nil, + @pending_version_id : UUID? = nil, + @previous_version_id : UUID? = nil, + @created_at : Time = Time.utc, + @updated_at : Time = Time.utc, + @last_rotated_at : Time? = nil, + ) + end + + def tag(key : String | Symbol) : String? + @tags[key.to_s]? + end + + def rotation_anchor : Time + @last_rotated_at || @created_at + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/credential_version.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/credential_version.cr new file mode 100644 index 00000000..3c256c2b --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/credential_version.cr @@ -0,0 +1,37 @@ +# =================== +# ©AngelaMos | 2026 +# credential_version.cr +# =================== + +require "uuid" + +module CRE::Domain + struct CredentialVersion + getter id : UUID + getter credential_id : UUID + getter ciphertext : Bytes + getter dek_wrapped : Bytes + getter kek_version : Int32 + getter algorithm_id : Int16 + getter metadata : Hash(String, String) + getter generated_at : Time + getter revoked_at : Time? + + def initialize( + @id : UUID, + @credential_id : UUID, + @ciphertext : Bytes, + @dek_wrapped : Bytes, + @kek_version : Int32, + @algorithm_id : Int16, + @metadata : Hash(String, String) = {} of String => String, + @generated_at : Time = Time.utc, + @revoked_at : Time? = nil, + ) + end + + def revoked? : Bool + !@revoked_at.nil? + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/new_secret.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/new_secret.cr new file mode 100644 index 00000000..dd06c2b4 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/domain/new_secret.cr @@ -0,0 +1,19 @@ +# =================== +# ©AngelaMos | 2026 +# new_secret.cr +# =================== + +module CRE::Domain + struct NewSecret + getter ciphertext : Bytes + getter metadata : Hash(String, String) + getter generated_at : Time + + def initialize( + @ciphertext : Bytes, + @metadata : Hash(String, String) = {} of String => String, + @generated_at : Time = Time.utc, + ) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/engine.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/engine.cr new file mode 100644 index 00000000..0f8cf39f --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/engine.cr @@ -0,0 +1,55 @@ +# =================== +# ©AngelaMos | 2026 +# engine.cr +# =================== + +require "log" +require "./event_bus" +require "./subscribers/audit_subscriber" +require "../audit/audit_log" +require "../persistence/persistence" + +module CRE::Engine + class Engine + Log = ::Log.for("cre.engine") + + getter bus : EventBus + getter persistence : Persistence::Persistence + getter audit_log : Audit::AuditLog + + @audit_subscriber : Subscribers::AuditSubscriber + @started : Bool + + def initialize(@persistence : Persistence::Persistence, hmac_key : Bytes, hmac_version : Int32 = 1, ratchet_every : Int32 = 1024) + @bus = EventBus.new + @audit_log = Audit::AuditLog.new(@persistence, hmac_key, hmac_version, ratchet_every) + @audit_subscriber = Subscribers::AuditSubscriber.new(@bus, @audit_log) + @started = false + end + + def start : Nil + raise "engine already started" if @started + @started = true + @audit_subscriber.start + @bus.run + Log.info { "engine started" } + end + + def stop : Nil + return unless @started + Log.info { "engine stopping" } + @bus.publish(Events::ShutdownRequested.new) rescue nil + + # Wait until the audit subscriber has drained everything queued + # before ShutdownRequested. Bounded so a stuck subscriber can't + # hang shutdown forever. + drained = @audit_subscriber.await_drain(2.seconds) + Log.warn { "audit subscriber did not drain in time during shutdown" } unless drained + + @audit_subscriber.stop + @bus.stop + @started = false + Log.info { "engine stopped" } + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/event_bus.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/event_bus.cr new file mode 100644 index 00000000..e3627e88 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/event_bus.cr @@ -0,0 +1,94 @@ +# =================== +# ©AngelaMos | 2026 +# event_bus.cr +# =================== + +require "log" +require "../events/event" + +module CRE::Engine + class EventBus + Log = ::Log.for("cre.event_bus") + + enum Overflow + Block + Drop + end + + record Subscription, channel : Channel(Events::Event), overflow : Overflow + + @inbox : Channel(Events::Event) + @subs : Array(Subscription) + @subs_mutex : Mutex + @running : Bool + + def initialize(inbox_capacity : Int32 = 1024, @block_send_timeout : Time::Span = 5.seconds) + @inbox = Channel(Events::Event).new(capacity: inbox_capacity) + @subs = [] of Subscription + @subs_mutex = Mutex.new + @running = false + end + + def subscribe(buffer : Int32 = 64, overflow : Overflow = Overflow::Block) : Channel(Events::Event) + ch = Channel(Events::Event).new(capacity: buffer) + @subs_mutex.synchronize { @subs << Subscription.new(ch, overflow) } + ch + end + + def publish(event : Events::Event) : Nil + @inbox.send(event) + end + + def run : Nil + @running = true + spawn(name: "event-bus") do + while @running + begin + ev = @inbox.receive + rescue Channel::ClosedError + break + end + @subs_mutex.synchronize { @subs.dup }.each { |s| dispatch(s, ev) } + end + end + end + + def stop : Nil + @running = false + @inbox.close + @subs_mutex.synchronize do + @subs.each(&.channel.close) + end + end + + # Dispatch isolates each subscriber so a slow one cannot block the bus + # for everyone else (head-of-line blocking). + # + # Drop overflow uses a non-blocking select+default; rejections are + # logged. Block overflow uses a select with a timeout; if the + # subscriber's buffer stays full beyond the timeout, the event is + # logged as dropped and the bus moves on rather than freezing the + # entire pipeline. Operators tune the timeout up for slow downstreams + # they trust (DB writes) and down for unreliable ones (Telegram). + private def dispatch(sub : Subscription, ev : Events::Event) : Nil + case sub.overflow + in Overflow::Block + select + when sub.channel.send(ev) + # delivered + when timeout(@block_send_timeout) + Log.warn { "subscriber stalled past #{@block_send_timeout.total_seconds}s; dropped: #{ev.class.name}" } + end + in Overflow::Drop + select + when sub.channel.send(ev) + # delivered + else + Log.warn { "subscriber drop: #{ev.class.name}" } + end + end + rescue Channel::ClosedError + # subscriber gone; remove from list lazily on next dispatch + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/rotation_orchestrator.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/rotation_orchestrator.cr new file mode 100644 index 00000000..9fa682d9 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/rotation_orchestrator.cr @@ -0,0 +1,172 @@ +# =================== +# ©AngelaMos | 2026 +# rotation_orchestrator.cr +# =================== + +require "log" +require "uuid" +require "./event_bus" +require "../events/credential_events" +require "../rotators/rotator" +require "../crypto/envelope" +require "../persistence/persistence" +require "../persistence/repos" + +module CRE::Engine + class VerifyFailed < Exception; end + + # The orchestrator drives a credential through the four-step rotation + # contract (generate -> apply -> verify -> commit). On success it + # 1. seals the new secret with the optional Envelope and writes a + # credential_versions row, + # 2. bumps the credential's last_rotated_at and current/previous + # version pointers so the policy evaluator no longer sees it as + # overdue. + # + # Failures roll the credential back to its previous state. Failures in + # apply or verify call rotator.rollback_apply; commit failures additionally + # mark the rotation as Inconsistent because partial cloud-side stage + # transitions cannot always be undone client-side. + class RotationOrchestrator + Log = ::Log.for("cre.rotator") + + def initialize( + @bus : EventBus, + @persistence : Persistence::Persistence, + @envelope : Crypto::Envelope? = nil, + ) + end + + def run(c : Domain::Credential, rotator : Rotators::Rotator) : Persistence::RotationState + rotation_id = UUID.random + record = Persistence::RotationRecord.new( + id: rotation_id, + credential_id: c.id, + rotator_kind: kind_to_enum(rotator.kind), + state: Persistence::RotationState::Generating, + started_at: Time.utc, + completed_at: nil, + failure_reason: nil, + ) + @persistence.rotations.insert(record) + @bus.publish Events::RotationStarted.new(c.id, rotation_id, rotator.kind.to_s) + + new_secret = nil + current_step = :generate + begin + @bus.publish Events::RotationStepStarted.new(c.id, rotation_id, :generate) + new_secret = rotator.generate(c) + @persistence.rotations.update_state(rotation_id, Persistence::RotationState::Applying) + @bus.publish Events::RotationStepCompleted.new(c.id, rotation_id, :generate) + + current_step = :apply + @bus.publish Events::RotationStepStarted.new(c.id, rotation_id, :apply) + rotator.apply(c, new_secret) + @persistence.rotations.update_state(rotation_id, Persistence::RotationState::Verifying) + @bus.publish Events::RotationStepCompleted.new(c.id, rotation_id, :apply) + + current_step = :verify + @bus.publish Events::RotationStepStarted.new(c.id, rotation_id, :verify) + ok = rotator.verify(c, new_secret) + raise VerifyFailed.new("verify returned false") unless ok + @persistence.rotations.update_state(rotation_id, Persistence::RotationState::Committing) + @bus.publish Events::RotationStepCompleted.new(c.id, rotation_id, :verify) + + current_step = :commit + @bus.publish Events::RotationStepStarted.new(c.id, rotation_id, :commit) + rotator.commit(c, new_secret) + @bus.publish Events::RotationStepCompleted.new(c.id, rotation_id, :commit) + + finalize_success(c, new_secret, rotation_id) + Persistence::RotationState::Completed + rescue ex + if (ns = new_secret) && (current_step == :apply || current_step == :verify) + begin + rotator.rollback_apply(c, ns) + rescue rb + Log.error(exception: rb) { "rollback_apply failed for credential #{c.id}" } + end + end + finalize_failure(c, rotation_id, current_step, ex) + end + end + + private def finalize_success(c : Domain::Credential, secret : Domain::NewSecret, rotation_id : UUID) : Nil + version_id = persist_credential_version(c, secret) + bump_credential(c, version_id) + @persistence.rotations.update_state(rotation_id, Persistence::RotationState::Completed) + @bus.publish Events::RotationCompleted.new(c.id, rotation_id) + end + + private def finalize_failure( + c : Domain::Credential, + rotation_id : UUID, + current_step : Symbol, + ex : Exception, + ) : Persistence::RotationState + reason = ex.message || ex.class.name + terminal_state = current_step == :commit ? Persistence::RotationState::Inconsistent : Persistence::RotationState::Failed + + @persistence.rotations.update_state(rotation_id, terminal_state, reason) + @bus.publish Events::RotationStepFailed.new(c.id, rotation_id, current_step, reason) + @bus.publish Events::RotationFailed.new(c.id, rotation_id, reason) + + if terminal_state == Persistence::RotationState::Inconsistent + @bus.publish Events::AlertRaised.new( + severity: Events::Severity::Critical, + message: "rotation #{rotation_id} for credential #{c.id} left in inconsistent state at commit step: #{reason}", + ) + end + + terminal_state + end + + private def persist_credential_version(c : Domain::Credential, secret : Domain::NewSecret) : UUID? + env = @envelope + return nil if env.nil? + + aad = "cred=#{c.id}|kind=#{c.kind}".to_slice + sealed = env.seal(secret.ciphertext, aad) + version = Domain::CredentialVersion.new( + id: UUID.random, + credential_id: c.id, + ciphertext: sealed.ciphertext, + dek_wrapped: sealed.dek_wrapped, + kek_version: sealed.kek_version, + algorithm_id: sealed.algorithm_id, + metadata: secret.metadata, + generated_at: secret.generated_at, + ) + @persistence.versions.insert(version) + version.id + end + + private def bump_credential(c : Domain::Credential, new_version_id : UUID?) : Nil + now = Time.utc + updated = Domain::Credential.new( + id: c.id, + external_id: c.external_id, + kind: c.kind, + name: c.name, + tags: c.tags, + current_version_id: new_version_id || c.current_version_id, + pending_version_id: nil, + previous_version_id: new_version_id ? c.current_version_id : c.previous_version_id, + created_at: c.created_at, + updated_at: now, + last_rotated_at: now, + ) + @persistence.credentials.update(updated) + end + + private def kind_to_enum(kind : Symbol) : Persistence::RotatorKind + case kind + when :aws_secretsmgr then Persistence::RotatorKind::AwsSecretsmgr + when :vault_dynamic then Persistence::RotatorKind::VaultDynamic + when :github_pat then Persistence::RotatorKind::GithubPat + when :env_file then Persistence::RotatorKind::EnvFile + else raise "unknown rotator kind #{kind}" + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/rotation_worker.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/rotation_worker.cr new file mode 100644 index 00000000..5c202fb5 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/rotation_worker.cr @@ -0,0 +1,105 @@ +# =================== +# ©AngelaMos | 2026 +# rotation_worker.cr +# =================== + +require "log" +require "./event_bus" +require "./rotation_orchestrator" +require "../events/credential_events" +require "../rotators/rotator" +require "../persistence/persistence" + +module CRE::Engine + # RotationWorker is the subscriber that turns RotationScheduled events into + # actual 4-step rotations. It owns a kind -> Rotator dispatch table populated + # at boot from env-var configuration (see cre run). + # + # The worker uses Block overflow so a slow rotator can't drop scheduled + # rotations on the floor. + class RotationWorker + Log = ::Log.for("cre.rotation_worker") + + @ch : ::Channel(Events::Event)? + @running : Bool + @rotators : Hash(Symbol, Rotators::Rotator) + + def initialize(@bus : EventBus, @orchestrator : RotationOrchestrator, @persistence : Persistence::Persistence) + @rotators = {} of Symbol => Rotators::Rotator + @running = false + end + + def register(kind : Symbol, rotator : Rotators::Rotator) : Nil + @rotators[kind] = rotator + Log.info { "registered rotator: #{kind}" } + end + + def kinds : Array(Symbol) + @rotators.keys + end + + def rotator_for_kind(kind : Domain::CredentialKind) : Rotators::Rotator? + @rotators[symbol_for_kind(kind)]? + end + + def start : Nil + @running = true + ch = @bus.subscribe(buffer: 32, overflow: EventBus::Overflow::Block) + @ch = ch + spawn(name: "rotation-worker") do + while @running + begin + ev = ch.receive + rescue ::Channel::ClosedError + break + end + handle(ev) + end + end + end + + def stop : Nil + @running = false + @ch.try(&.close) + end + + private def handle(ev : Events::Event) : Nil + return unless ev.is_a?(Events::RotationScheduled) + cred = @persistence.credentials.find(ev.credential_id) + if cred.nil? + Log.warn { "RotationScheduled for missing credential #{ev.credential_id}" } + return + end + + rotator_kind = symbol_for_kind(cred.kind) + rotator = @rotators[rotator_kind]? + if rotator.nil? + Log.warn { "no rotator registered for #{rotator_kind} (credential #{cred.id}); skipping" } + return + end + + unless rotator.can_rotate?(cred) + Log.warn { "rotator #{rotator_kind} declined credential #{cred.id} (missing required tags?)" } + return + end + + if @persistence.rotations.in_flight.any? { |r| r.credential_id == cred.id } + Log.info { "rotation already in flight for credential #{cred.id}; skipping duplicate schedule" } + return + end + + @orchestrator.run(cred, rotator) + rescue ex + Log.error(exception: ex) { "rotation_worker.handle failed for event #{ev.class.name}" } + end + + private def symbol_for_kind(k : Domain::CredentialKind) : Symbol + case k + in .aws_secretsmgr? then :aws_secretsmgr + in .vault_dynamic? then :vault_dynamic + in .github_pat? then :github_pat + in .env_file? then :env_file + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/scheduler.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/scheduler.cr new file mode 100644 index 00000000..3b232b2b --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/scheduler.cr @@ -0,0 +1,52 @@ +# =================== +# ©AngelaMos | 2026 +# scheduler.cr +# =================== + +require "log" +require "./event_bus" +require "../events/system_events" + +module CRE::Engine + # Scheduler is a fiber that publishes SchedulerTick events at a fixed interval. + # The PolicyEvaluator subscriber listens for these and runs evaluate_all, + # which discovers overdue credentials and publishes RotationScheduled etc. + # + # The fiber owns its own lifecycle: start() spawns it; stop() flips a flag and + # the next tick's check exits cleanly. + class Scheduler + Log = ::Log.for("cre.scheduler") + + @running : Bool + + def initialize(@bus : EventBus, @interval : Time::Span = 60.seconds) + @running = false + end + + def start : Nil + @running = true + spawn(name: "scheduler") do + # Fire one tick immediately so the first evaluation doesn't wait + # for the full interval on boot. + @bus.publish Events::SchedulerTick.new + while @running + sleep @interval + break unless @running + begin + @bus.publish Events::SchedulerTick.new + rescue ex + Log.error(exception: ex) { "scheduler tick publish failed" } + end + end + end + end + + def stop : Nil + @running = false + end + + def running? : Bool + @running + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/subscribers/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/subscribers/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/subscribers/audit_subscriber.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/subscribers/audit_subscriber.cr new file mode 100644 index 00000000..77d14af0 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/engine/subscribers/audit_subscriber.cr @@ -0,0 +1,119 @@ +# =================== +# ©AngelaMos | 2026 +# audit_subscriber.cr +# =================== + +require "../event_bus" +require "../../audit/audit_log" +require "../../events/credential_events" +require "../../events/system_events" + +module CRE::Engine::Subscribers + class AuditSubscriber + @ch : Channel(Events::Event)? + @running : Bool + @drain_ready : ::Channel(Nil) + + def initialize(@bus : EventBus, @log : Audit::AuditLog, @actor : String = "system") + @running = false + @drain_ready = ::Channel(Nil).new(1) + end + + def start : Nil + @running = true + ch = @bus.subscribe(buffer: 256, overflow: EventBus::Overflow::Block) + @ch = ch + spawn(name: "audit-sub") do + while @running + begin + ev = ch.receive + rescue Channel::ClosedError + break + end + handle(ev) + end + end + end + + def stop : Nil + @running = false + @ch.try(&.close) + end + + # Block until either the subscriber receives ShutdownRequested (i.e. + # has drained everything published before the shutdown signal) or the + # timeout elapses. Lets engine.stop deterministically wait instead of + # sleeping for a magic 50ms. + def await_drain(timeout_span : Time::Span = 2.seconds) : Bool + select + when @drain_ready.receive + true + when timeout(timeout_span) + false + end + end + + private def handle(ev : Events::Event) : Nil + case ev + when Events::ShutdownRequested + @drain_ready.send(nil) rescue nil + return + when Events::RotationCompleted + @log.append("rotation.completed", @actor, ev.credential_id, { + "rotation_id" => ev.rotation_id.to_s, + }) + when Events::RotationFailed + @log.append("rotation.failed", @actor, ev.credential_id, { + "rotation_id" => ev.rotation_id.to_s, + "reason" => ev.reason, + }) + when Events::RotationStepCompleted + @log.append("rotation.step.completed", @actor, ev.credential_id, { + "rotation_id" => ev.rotation_id.to_s, + "step" => ev.step.to_s, + }) + when Events::RotationStepFailed + @log.append("rotation.step.failed", @actor, ev.credential_id, { + "rotation_id" => ev.rotation_id.to_s, + "step" => ev.step.to_s, + "error" => ev.error, + }) + when Events::PolicyViolation + @log.append("policy.violation", @actor, ev.credential_id, { + "policy_name" => ev.policy_name, + "reason" => ev.reason, + }) + when Events::DriftDetected + @log.append("drift.detected", @actor, ev.credential_id, { + "expected_hash" => ev.expected_hash, + "actual_hash" => ev.actual_hash, + }) + when Events::CredentialDiscovered + @log.append("credential.discovered", @actor, ev.credential_id, {} of String => String) + when Events::AlertRaised + @log.append("alert.raised", @actor, nil, { + "severity" => ev.severity.to_s, + "message" => ev.message, + }) + when Events::AuditBatchSealed + @log.append("audit.batch.sealed", @actor, nil, { + "start_seq" => ev.start_seq.to_s, + "end_seq" => ev.end_seq.to_s, + "signing_key_version" => ev.signing_key_version.to_s, + }) + end + rescue ex + EventBus::Log.error(exception: ex) { "audit subscriber failed to write" } + @bus.publish(Events::AlertRaised.new( + severity: Events::Severity::Critical, + message: "audit log write failed: #{ex.message} (event=#{ev.class.name})", + )) rescue nil + + mode = ENV["CRE_AUDIT_FAILURE_MODE"]? || "panic" + if mode == "panic" + STDERR.puts "FATAL: audit log write failed in panic mode: #{ex.message} (event=#{ev.class.name})" + Process.exit(2) + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/credential_events.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/credential_events.cr new file mode 100644 index 00000000..0ac959de --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/credential_events.cr @@ -0,0 +1,100 @@ +# =================== +# ©AngelaMos | 2026 +# credential_events.cr +# =================== + +require "uuid" +require "./event" + +module CRE::Events + abstract class CredentialEvent < Event + getter credential_id : UUID + + def initialize(@credential_id : UUID) + super() + end + end + + class CredentialDiscovered < CredentialEvent + end + + class PolicyViolation < CredentialEvent + getter policy_name : String + getter reason : String + + def initialize(credential_id : UUID, @policy_name : String, @reason : String) + super(credential_id) + end + end + + class RotationScheduled < CredentialEvent + getter rotator_kind : String + + def initialize(credential_id : UUID, @rotator_kind : String) + super(credential_id) + end + end + + class RotationStarted < CredentialEvent + getter rotation_id : UUID + getter rotator_kind : String + + def initialize(credential_id : UUID, @rotation_id : UUID, @rotator_kind : String) + super(credential_id) + end + end + + class RotationStepStarted < CredentialEvent + getter rotation_id : UUID + getter step : Symbol + + def initialize(credential_id : UUID, @rotation_id : UUID, @step : Symbol) + super(credential_id) + end + end + + class RotationStepCompleted < CredentialEvent + getter rotation_id : UUID + getter step : Symbol + + def initialize(credential_id : UUID, @rotation_id : UUID, @step : Symbol) + super(credential_id) + end + end + + class RotationStepFailed < CredentialEvent + getter rotation_id : UUID + getter step : Symbol + getter error : String + + def initialize(credential_id : UUID, @rotation_id : UUID, @step : Symbol, @error : String) + super(credential_id) + end + end + + class RotationCompleted < CredentialEvent + getter rotation_id : UUID + + def initialize(credential_id : UUID, @rotation_id : UUID) + super(credential_id) + end + end + + class RotationFailed < CredentialEvent + getter rotation_id : UUID + getter reason : String + + def initialize(credential_id : UUID, @rotation_id : UUID, @reason : String) + super(credential_id) + end + end + + class DriftDetected < CredentialEvent + getter expected_hash : String + getter actual_hash : String + + def initialize(credential_id : UUID, @expected_hash : String, @actual_hash : String) + super(credential_id) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/event.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/event.cr new file mode 100644 index 00000000..53b3ca6c --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/event.cr @@ -0,0 +1,13 @@ +# =================== +# ©AngelaMos | 2026 +# event.cr +# =================== + +require "uuid" + +module CRE::Events + abstract class Event + getter id : UUID = UUID.random + getter occurred_at : Time = Time.utc + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/system_events.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/system_events.cr new file mode 100644 index 00000000..61d10dbd --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/events/system_events.cr @@ -0,0 +1,39 @@ +# =================== +# ©AngelaMos | 2026 +# system_events.cr +# =================== + +require "./event" + +module CRE::Events + enum Severity + Info + Warn + Critical + end + + class AlertRaised < Event + getter severity : Severity + getter message : String + + def initialize(@severity : Severity, @message : String) + super() + end + end + + class SchedulerTick < Event + end + + class ShutdownRequested < Event + end + + class AuditBatchSealed < Event + getter start_seq : Int64 + getter end_seq : Int64 + getter signing_key_version : Int32 + + def initialize(@start_seq : Int64, @end_seq : Int64, @signing_key_version : Int32) + super() + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/github/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/github/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/github/client.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/github/client.cr new file mode 100644 index 00000000..534c2549 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/github/client.cr @@ -0,0 +1,84 @@ +# =================== +# ©AngelaMos | 2026 +# client.cr +# =================== + +require "http/client" +require "json" +require "../http/retry" + +module CRE::Github + class GithubError < Exception + getter status : Int32 + + def initialize(message : String, @status : Int32) + super(message) + end + end + + # Thin GitHub REST client. We target fine-grained PATs for rotation since + # the /user/personal-access-tokens endpoint accepts programmatic creation + # and deletion when the bearer has the appropriate Apps-managed + # permission. For the test/portfolio path we mock these endpoints + # directly. + class Client + record Token, id : Int64, token_value : String, expires_at : String? + + DEFAULT_API = "https://api.github.com" + + def initialize(@token : String, @api_base : String = DEFAULT_API) + end + + def me : JSON::Any + get("/user") + end + + def create_pat(name : String, scopes : Array(String), expires_in_days : Int32 = 90) : Token + payload = { + "name" => name, + "expires_in_days" => expires_in_days, + "scopes" => scopes, + }.to_json + json = post("/user/personal-access-tokens", payload) + Token.new( + id: json["id"].as_i64, + token_value: json["token"].as_s, + expires_at: json["expires_at"]?.try(&.as_s), + ) + end + + def delete_pat(token_id : Int64) : Nil + delete("/user/personal-access-tokens/#{token_id}") + end + + private def get(path : String) : JSON::Any + response = CRE::Http.request("GET", url(path), headers, label: "github.GET#{path}") + raise GithubError.new("GET #{path}: #{response.body[0, 200]?}", response.status_code) unless response.status_code < 300 + JSON.parse(response.body) + end + + private def post(path : String, body : String) : JSON::Any + response = CRE::Http.request("POST", url(path), headers, body, label: "github.POST#{path}") + raise GithubError.new("POST #{path}: #{response.body[0, 200]?}", response.status_code) unless response.status_code < 300 + JSON.parse(response.body) + end + + private def delete(path : String) : Nil + response = CRE::Http.request("DELETE", url(path), headers, label: "github.DELETE#{path}") + raise GithubError.new("DELETE #{path}: #{response.body[0, 200]?}", response.status_code) unless response.status_code < 300 + end + + private def headers : HTTP::Headers + HTTP::Headers{ + "Authorization" => "Bearer #{@token}", + "Accept" => "application/vnd.github+json", + "X-GitHub-Api-Version" => "2022-11-28", + "Content-Type" => "application/json", + } + end + + private def url(path : String) : String + "#{@api_base}#{path}" + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/http/retry.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/http/retry.cr new file mode 100644 index 00000000..baf79dbe --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/http/retry.cr @@ -0,0 +1,90 @@ +# =================== +# ©AngelaMos | 2026 +# retry.cr +# =================== + +require "http/client" +require "log" + +module CRE::Http + # Transient HTTP statuses where retrying makes sense. We do NOT retry + # on 401/403/404 — those mean the request is bad, not flaky. + RETRY_STATUSES = {408, 425, 429, 500, 502, 503, 504}.to_set + + # Retry wraps a Proc with bounded retry-with-jitter. Default policy: + # 3 attempts (initial + 2 retries), 200ms..2s exponential backoff with + # full jitter, retries network errors and the canonical transient + # statuses listed above. + module Retry + Log = ::Log.for("cre.http.retry") + + def self.with( + *, + attempts : Int32 = 3, + base_delay : Time::Span = 200.milliseconds, + max_delay : Time::Span = 2.seconds, + retry_statuses : Set(Int32) = RETRY_STATUSES, + label : String = "http", + &block : -> HTTP::Client::Response + ) : HTTP::Client::Response + attempt = 0 + loop do + attempt += 1 + begin + response = block.call + if retry_statuses.includes?(response.status_code) && attempt < attempts + Log.warn { "#{label}: HTTP #{response.status_code} on attempt #{attempt}; retrying" } + sleep_with_jitter(base_delay, max_delay, attempt) + next + end + return response + rescue ex : IO::TimeoutError | Socket::ConnectError | IO::Error + if attempt < attempts + Log.warn(exception: ex) { "#{label}: transient error on attempt #{attempt}; retrying" } + sleep_with_jitter(base_delay, max_delay, attempt) + next + end + raise ex + end + end + end + + private def self.sleep_with_jitter(base : Time::Span, ceiling : Time::Span, attempt : Int32) : Nil + backoff_ms = base.total_milliseconds * (1 << (attempt - 1)) + capped_ms = Math.min(backoff_ms, ceiling.total_milliseconds) + jittered = (capped_ms * Random.rand).to_i + sleep jittered.milliseconds + end + end + + # Connect/read timeouts come from env so operators can tune per + # environment without recompiling. Defaults are conservative for cloud + # APIs where 5xx blips are normal. + CONNECT_TIMEOUT = ((ENV["CRE_HTTP_CONNECT_TIMEOUT_S"]? || "5").to_f).seconds + READ_TIMEOUT = ((ENV["CRE_HTTP_READ_TIMEOUT_S"]? || "30").to_f).seconds + + # Single-shot HTTP request with timeouts + retry. Returns the + # HTTP::Client::Response. The HTTP::Client instance is created per + # call and closed in an ensure block so a hung peer can't pin + # resources past the timeout. Webmock intercepts via instance method + # override so test stubs continue to apply unchanged. + def self.request(method : String, url : String, headers : HTTP::Headers, body : String = "", label : String = "http") : HTTP::Client::Response + uri = URI.parse(url) + request_target = String.build do |s| + s << (uri.path.empty? ? "/" : uri.path) + if (q = uri.query) && !q.empty? + s << "?" << q + end + end + Retry.with(label: label) do + client = HTTP::Client.new(uri) + client.connect_timeout = CONNECT_TIMEOUT + client.read_timeout = READ_TIMEOUT + begin + client.exec(method, request_target, headers: headers, body: body) + ensure + client.close + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/log_notifier.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/log_notifier.cr new file mode 100644 index 00000000..e41a3c1d --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/log_notifier.cr @@ -0,0 +1,65 @@ +# =================== +# ©AngelaMos | 2026 +# log_notifier.cr +# =================== + +require "log" +require "../engine/event_bus" +require "../events/credential_events" +require "../events/system_events" + +module CRE::Notifiers + # LogNotifier subscribes to all events and emits structured stdlib Log lines. + # Suitable for shipping to journald, vector, or fluentd; downstream tooling + # can ingest the structured fields directly. + class LogNotifier + Log = ::Log.for("cre.notifier") + + @ch : ::Channel(Events::Event)? + @running : Bool + + def initialize(@bus : Engine::EventBus) + @running = false + end + + def start : Nil + @running = true + ch = @bus.subscribe(buffer: 64, overflow: Engine::EventBus::Overflow::Drop) + @ch = ch + spawn(name: "log-notifier") do + while @running + begin + ev = ch.receive + rescue ::Channel::ClosedError + break + end + emit(ev) + end + end + end + + def stop : Nil + @running = false + @ch.try(&.close) + end + + private def emit(ev : Events::Event) : Nil + case ev + when Events::RotationCompleted + Log.info &.emit("rotation completed", credential_id: ev.credential_id.to_s, rotation_id: ev.rotation_id.to_s) + when Events::RotationFailed + Log.error &.emit("rotation failed", credential_id: ev.credential_id.to_s, rotation_id: ev.rotation_id.to_s, reason: ev.reason) + when Events::PolicyViolation + Log.warn &.emit("policy violation", credential_id: ev.credential_id.to_s, policy: ev.policy_name, reason: ev.reason) + when Events::DriftDetected + Log.warn &.emit("drift detected", credential_id: ev.credential_id.to_s, expected: ev.expected_hash, actual: ev.actual_hash) + when Events::AlertRaised + case ev.severity + in Events::Severity::Critical then Log.error &.emit("alert", text: ev.message) + in Events::Severity::Warn then Log.warn &.emit("alert", text: ev.message) + in Events::Severity::Info then Log.info &.emit("alert", text: ev.message) + end + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/telegram.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/telegram.cr new file mode 100644 index 00000000..66d7804f --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/telegram.cr @@ -0,0 +1,79 @@ +# =================== +# ©AngelaMos | 2026 +# telegram.cr +# =================== + +require "http/client" +require "json" +require "log" +require "../http/retry" + +module CRE::Notifiers + # Thin Telegram Bot API client. We hit api.telegram.org/bot/ + # directly with HTTP::Client; no tourmaline dependency for the + # notification path keeps the footprint small. + # + # Telegram requires the bot token to live in the URL path. To prevent + # leaks, error messages substitute the token with '****' before + # surfacing any URL fragment. The token is still in the underlying + # request's URI; operators wiring a logging proxy in front of cre + # should redact at the proxy layer too. + class Telegram + Log = ::Log.for("cre.telegram") + DEFAULT_API = "https://api.telegram.org" + + class TelegramError < Exception + getter status : Int32 + + def initialize(message : String, @status : Int32) + super(message) + end + end + + record Update, + update_id : Int64, + message_id : Int64?, + chat_id : Int64?, + text : String? + + def initialize(@token : String, @api_base : String = DEFAULT_API) + end + + def send_message(chat_id : Int64, text : String, parse_mode : String? = nil) : Nil + payload = {"chat_id" => chat_id, "text" => text} of String => String | Int64 + payload["parse_mode"] = parse_mode if parse_mode + call("sendMessage", payload.to_json) + end + + def get_updates(offset : Int64? = nil, timeout : Int32 = 30) : Array(Update) + h = {"timeout" => timeout} of String => String | Int64 | Int32 + h["offset"] = offset if offset + json = call("getUpdates", h.to_json) + results = json["result"].as_a + results.map do |entry| + msg = entry["message"]? + Update.new( + update_id: entry["update_id"].as_i64, + message_id: msg.try(&.["message_id"]?.try(&.as_i64)), + chat_id: msg.try(&.["chat"]?.try(&.["id"]?.try(&.as_i64))), + text: msg.try(&.["text"]?.try(&.as_s)), + ) + end + end + + private def call(method : String, body : String) : JSON::Any + url = "#{@api_base}/bot#{@token}/#{method}" + headers = HTTP::Headers{"Content-Type" => "application/json"} + response = CRE::Http.request("POST", url, headers, body, label: "telegram.#{method}") + unless response.status_code < 300 + raise TelegramError.new("telegram #{method} #{response.status_code}: #{redact(response.body[0, 200]?)}", response.status_code) + end + JSON.parse(response.body) + end + + private def redact(text : String?) : String? + return nil if text.nil? + text.gsub(@token, "****") + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/telegram_bot.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/telegram_bot.cr new file mode 100644 index 00000000..18d424f5 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/telegram_bot.cr @@ -0,0 +1,142 @@ +# =================== +# ©AngelaMos | 2026 +# telegram_bot.cr +# =================== + +require "log" +require "./telegram" +require "../engine/event_bus" +require "../persistence/persistence" + +module CRE::Notifiers + # TelegramBot does long-polling getUpdates and dispatches commands to + # operator handlers. Two ACL tiers: + # - viewer : read-only commands (/status, /queue, /history, /alerts, /help) + # - operator: viewer + mutating commands (/rotate, /snooze) + # + # Authorization is by chat_id; not strictly authentication but adequate for a + # single-tenant deployment where the bot token + chat IDs live in env vars. + class TelegramBot + Log = ::Log.for("cre.telegram_bot") + + @running : Bool + @last_offset : Int64 + + def initialize( + @bus : Engine::EventBus, + @telegram : Telegram, + @persistence : Persistence::Persistence, + @viewer_chats : Array(Int64), + @operator_chats : Array(Int64), + ) + @running = false + @last_offset = 0_i64 + end + + def start : Nil + @running = true + spawn(name: "telegram-bot") do + while @running + begin + poll_once + rescue ex + Log.error(exception: ex) { "telegram bot poll failed" } + sleep 1.second + end + end + end + end + + def stop : Nil + @running = false + end + + def authorized_viewer?(chat_id : Int64) : Bool + @viewer_chats.includes?(chat_id) || @operator_chats.includes?(chat_id) + end + + def authorized_operator?(chat_id : Int64) : Bool + @operator_chats.includes?(chat_id) + end + + def handle_command(chat_id : Int64, text : String) : String + return "unauthorized" unless authorized_viewer?(chat_id) + cmd, _, rest = text.strip.lstrip('/').partition(' ') + case cmd + when "status" then status_message + when "queue" then queue_message + when "alerts" then alerts_message + when "help", "" then help_message + when "rotate" then handle_rotate(chat_id, rest) + when "history" then history_message(rest) + else + "unknown command: /#{cmd} (try /help)" + end + end + + def poll_once : Nil + updates = @telegram.get_updates(offset: @last_offset == 0 ? nil : @last_offset, timeout: 5) + updates.each do |u| + @last_offset = u.update_id + 1 + chat_id = u.chat_id + text = u.text + next if chat_id.nil? || text.nil? || !text.starts_with?('/') + reply = handle_command(chat_id, text) + @telegram.send_message(chat_id, reply) rescue nil + end + end + + private def status_message : String + total = @persistence.credentials.all.size + in_flight = @persistence.rotations.in_flight.size + "● live\nCredentials: #{total}\nIn-flight rotations: #{in_flight}" + end + + private def queue_message : String + in_flight = @persistence.rotations.in_flight + return "queue empty" if in_flight.empty? + lines = in_flight.first(10).map { |r| "- #{r.rotator_kind} #{r.credential_id} [#{r.state}]" } + "Active queue (#{in_flight.size}):\n#{lines.join('\n')}" + end + + private def alerts_message : String + "Alerts inspection is exposed via the audit log; use 'cre audit verify --since=...' from the CLI." + end + + private def help_message : String + <<-MD + Available commands: + /status - quick health summary + /queue - active rotations + /history - last events for a credential + /alerts - critical alerts pointer + /rotate - force rotation (operator) + MD + end + + private def handle_rotate(chat_id : Int64, rest : String) : String + return "operator-only command" unless authorized_operator?(chat_id) + id_str = rest.strip + return "usage: /rotate " if id_str.empty? + uuid = UUID.new(id_str) rescue nil + return "invalid credential id" if uuid.nil? + @bus.publish Events::RotationScheduled.new(uuid, "manual") + "rotation scheduled for #{uuid}" + end + + private def history_message(rest : String) : String + id_str = rest.strip + return "usage: /history " if id_str.empty? + uuid = UUID.new(id_str) rescue nil + return "invalid credential id" if uuid.nil? + cred = @persistence.credentials.find(uuid) + return "credential not found" if cred.nil? + latest = @persistence.audit.latest_seq + entries = latest > 10 ? @persistence.audit.range(latest - 9, latest) : @persistence.audit.range(1_i64, latest) + filtered = entries.select { |e| e.target_id == uuid } + return "no audit entries for #{uuid}" if filtered.empty? + lines = filtered.last(10).map { |e| "- #{e.occurred_at.to_rfc3339}: #{e.event_type}" } + "Last events for #{cred.name}:\n#{lines.join('\n')}" + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/telegram_subscriber.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/telegram_subscriber.cr new file mode 100644 index 00000000..1faabeb9 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/notifiers/telegram_subscriber.cr @@ -0,0 +1,80 @@ +# =================== +# ©AngelaMos | 2026 +# telegram_subscriber.cr +# =================== + +require "log" +require "./telegram" +require "../engine/event_bus" +require "../events/credential_events" +require "../events/system_events" + +module CRE::Notifiers + # TelegramSubscriber sends emoji-prefixed messages to allowlisted chats on + # significant events. Best-effort delivery (Drop overflow); transient + # Telegram errors are logged and swallowed so a network blip never blocks + # the engine. + class TelegramSubscriber + Log = ::Log.for("cre.telegram_subscriber") + + @ch : ::Channel(Events::Event)? + @running : Bool + + def initialize(@bus : Engine::EventBus, @telegram : Telegram, @viewer_chats : Array(Int64), @notify_on_success : Bool = false) + @running = false + end + + def start : Nil + @running = true + ch = @bus.subscribe(buffer: 128, overflow: Engine::EventBus::Overflow::Drop) + @ch = ch + spawn(name: "telegram-sub") do + while @running + begin + ev = ch.receive + rescue ::Channel::ClosedError + break + end + dispatch(ev) + end + end + end + + def stop : Nil + @running = false + @ch.try(&.close) + end + + private def dispatch(ev : Events::Event) : Nil + msg = format(ev) + return if msg.nil? + @viewer_chats.each do |chat| + @telegram.send_message(chat, msg) + rescue ex + Log.warn(exception: ex) { "telegram send failed for chat=#{chat}" } + end + end + + private def format(ev : Events::Event) : String? + case ev + when Events::RotationFailed + "! Rotation FAILED for credential #{ev.credential_id} (rotation #{ev.rotation_id}): #{ev.reason}" + when Events::DriftDetected + "⚠ Drift detected on credential #{ev.credential_id}: hash mismatch (expected=#{ev.expected_hash[0, 12]}..., actual=#{ev.actual_hash[0, 12]}...)" + when Events::PolicyViolation + "⚠ Policy violation: '#{ev.policy_name}' on #{ev.credential_id} (#{ev.reason})" + when Events::AlertRaised + sev = case ev.severity + in Events::Severity::Critical then "!" + in Events::Severity::Warn then "⚠" + in Events::Severity::Info then "ℹ" + end + "#{sev} #{ev.message}" + when Events::RotationCompleted + @notify_on_success ? "✓ Rotation completed for credential #{ev.credential_id}" : nil + else + nil + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/persistence.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/persistence.cr new file mode 100644 index 00000000..862bf62e --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/persistence.cr @@ -0,0 +1,20 @@ +# =================== +# ©AngelaMos | 2026 +# persistence.cr +# =================== + +require "./repos" + +module CRE::Persistence + abstract class Persistence + abstract def credentials : CredentialsRepo + abstract def versions : VersionsRepo + abstract def rotations : RotationsRepo + abstract def audit : AuditRepo + + abstract def transaction(&block : ->) + abstract def with_advisory_lock(key : Int64, &block : ->) + abstract def migrate! : Nil + abstract def close : Nil + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/audit_repo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/audit_repo.cr new file mode 100644 index 00000000..72c24711 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/audit_repo.cr @@ -0,0 +1,132 @@ +# =================== +# ©AngelaMos | 2026 +# audit_repo.cr +# =================== + +require "db" +require "uuid" +require "../repos" + +module CRE::Persistence::Postgres + class AuditRepo < CRE::Persistence::AuditRepo + GENESIS_HASH = Bytes.new(32, 0_u8) + + SELECT_ENTRY_COLS = "seq, event_id::text, occurred_at, event_type, actor, target_id::text, payload::text, prev_hash, content_hash, hmac, hmac_key_version" + SELECT_BATCH_COLS = "id::text, start_seq, end_seq, merkle_root, signature, signing_key_version, sealed_at" + + def initialize(@db : DB::Database) + end + + def append(entry : AuditEntry) : Nil + @db.exec( + "INSERT INTO audit_events (event_id, occurred_at, event_type, actor, target_id, payload, prev_hash, content_hash, hmac, hmac_key_version) VALUES ($1::uuid, $2, $3, $4, $5::uuid, $6::jsonb, $7, $8, $9, $10)", + entry.event_id.to_s, entry.occurred_at, + entry.event_type, entry.actor, + entry.target_id.try(&.to_s), + entry.payload, + entry.prev_hash, entry.content_hash, entry.hmac, + entry.hmac_key_version, + ) + end + + def latest_hash : Bytes + result = @db.query_one?( + "SELECT content_hash FROM audit_events ORDER BY seq DESC LIMIT 1", + as: Bytes, + ) + result || GENESIS_HASH + end + + def latest_seq : Int64 + result = @db.query_one?( + "SELECT seq FROM audit_events ORDER BY seq DESC LIMIT 1", + as: Int64, + ) + result || 0_i64 + end + + def range(start_seq : Int64, end_seq : Int64) : Array(AuditEntry) + @db.query_all( + "SELECT #{SELECT_ENTRY_COLS} FROM audit_events WHERE seq >= $1 AND seq <= $2 ORDER BY seq ASC", + start_seq, end_seq, + as: {Int64, String, Time, String, String, String?, String, Bytes, Bytes, Bytes, Int32}, + ).map { |row| row_to_entry(row) } + end + + def each_in_range(start_seq : Int64, end_seq : Int64, &block : AuditEntry ->) : Nil + @db.query( + "SELECT #{SELECT_ENTRY_COLS} FROM audit_events WHERE seq >= $1 AND seq <= $2 ORDER BY seq ASC", + start_seq, end_seq, + ) do |rs| + rs.each do + entry = AuditEntry.new( + seq: rs.read(Int64), + event_id: UUID.new(rs.read(String)), + occurred_at: rs.read(Time), + event_type: rs.read(String), + actor: rs.read(String), + target_id: rs.read(String?).try { |s| UUID.new(s) }, + payload: rs.read(String), + prev_hash: rs.read(Bytes), + content_hash: rs.read(Bytes), + hmac: rs.read(Bytes), + hmac_key_version: rs.read(Int32), + ) + block.call(entry) + end + end + end + + def insert_batch(batch : AuditBatch) : Nil + @db.exec( + "INSERT INTO audit_batches (id, start_seq, end_seq, merkle_root, signature, signing_key_version, sealed_at) VALUES ($1::uuid, $2, $3, $4, $5, $6, $7)", + batch.id.to_s, batch.start_seq, batch.end_seq, + batch.merkle_root, batch.signature, + batch.signing_key_version, batch.sealed_at, + ) + end + + def last_sealed_seq : Int64 + result = @db.query_one?( + "SELECT MAX(end_seq) FROM audit_batches", + as: Int64?, + ) + result || 0_i64 + end + + def all_batches : Array(AuditBatch) + @db.query_all( + "SELECT #{SELECT_BATCH_COLS} FROM audit_batches ORDER BY start_seq ASC", + as: {String, Int64, Int64, Bytes, Bytes, Int32, Time}, + ).map { |row| row_to_batch(row) } + end + + private def row_to_entry(row) : AuditEntry + AuditEntry.new( + seq: row[0], + event_id: UUID.new(row[1]), + occurred_at: row[2], + event_type: row[3], + actor: row[4], + target_id: row[5].try { |s| UUID.new(s) }, + payload: row[6], + prev_hash: row[7], + content_hash: row[8], + hmac: row[9], + hmac_key_version: row[10], + ) + end + + private def row_to_batch(row) : AuditBatch + AuditBatch.new( + id: UUID.new(row[0]), + start_seq: row[1], + end_seq: row[2], + merkle_root: row[3], + signature: row[4], + signing_key_version: row[5], + sealed_at: row[6], + ) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/credentials_repo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/credentials_repo.cr new file mode 100644 index 00000000..2e4186ab --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/credentials_repo.cr @@ -0,0 +1,91 @@ +# =================== +# ©AngelaMos | 2026 +# credentials_repo.cr +# =================== + +require "db" +require "json" +require "uuid" +require "../repos" +require "../../domain/credential" + +module CRE::Persistence::Postgres + class CredentialsRepo < CRE::Persistence::CredentialsRepo + SELECT_COLS = "id::text, external_id, kind, name, tags::text, current_version_id::text, pending_version_id::text, previous_version_id::text, created_at, updated_at, last_rotated_at" + + def initialize(@db : DB::Database) + end + + def insert(c : Domain::Credential) : Nil + @db.exec( + "INSERT INTO credentials (id, external_id, kind, name, tags, current_version_id, pending_version_id, previous_version_id, created_at, updated_at, last_rotated_at) VALUES ($1::uuid, $2, $3, $4, $5::jsonb, $6::uuid, $7::uuid, $8::uuid, $9, $10, $11)", + c.id.to_s, c.external_id, c.kind.to_s, c.name, + c.tags.to_json, + c.current_version_id.try(&.to_s), + c.pending_version_id.try(&.to_s), + c.previous_version_id.try(&.to_s), + c.created_at, c.updated_at, c.last_rotated_at, + ) + end + + def update(c : Domain::Credential) : Nil + @db.exec( + "UPDATE credentials SET name = $1, tags = $2::jsonb, current_version_id = $3::uuid, pending_version_id = $4::uuid, previous_version_id = $5::uuid, updated_at = $6, last_rotated_at = $7 WHERE id = $8::uuid", + c.name, c.tags.to_json, + c.current_version_id.try(&.to_s), + c.pending_version_id.try(&.to_s), + c.previous_version_id.try(&.to_s), + Time.utc, c.last_rotated_at, c.id.to_s, + ) + end + + def find(id : UUID) : Domain::Credential? + @db.query_one?( + "SELECT #{SELECT_COLS} FROM credentials WHERE id = $1::uuid", + id.to_s, + as: {String, String, String, String, String, String?, String?, String?, Time, Time, Time?}, + ).try { |row| row_to_credential(row) } + end + + def find_by_external(kind : Domain::CredentialKind, external_id : String) : Domain::Credential? + @db.query_one?( + "SELECT #{SELECT_COLS} FROM credentials WHERE kind = $1 AND external_id = $2", + kind.to_s, external_id, + as: {String, String, String, String, String, String?, String?, String?, Time, Time, Time?}, + ).try { |row| row_to_credential(row) } + end + + def all : Array(Domain::Credential) + @db.query_all( + "SELECT #{SELECT_COLS} FROM credentials", + as: {String, String, String, String, String, String?, String?, String?, Time, Time, Time?}, + ).map { |row| row_to_credential(row) } + end + + def overdue(now : Time, max_age : Time::Span) : Array(Domain::Credential) + cutoff = now - max_age + @db.query_all( + "SELECT #{SELECT_COLS} FROM credentials WHERE COALESCE(last_rotated_at, created_at) < $1", + cutoff, + as: {String, String, String, String, String, String?, String?, String?, Time, Time, Time?}, + ).map { |row| row_to_credential(row) } + end + + private def row_to_credential(row) : Domain::Credential + tags = Hash(String, String).from_json(row[4]) + Domain::Credential.new( + id: UUID.new(row[0]), + external_id: row[1], + kind: Domain::CredentialKind.parse(row[2]), + name: row[3], + tags: tags, + current_version_id: row[5].try { |s| UUID.new(s) }, + pending_version_id: row[6].try { |s| UUID.new(s) }, + previous_version_id: row[7].try { |s| UUID.new(s) }, + created_at: row[8], + updated_at: row[9], + last_rotated_at: row[10], + ) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/migrations.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/migrations.cr new file mode 100644 index 00000000..12fcd683 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/migrations.cr @@ -0,0 +1,140 @@ +# =================== +# ©AngelaMos | 2026 +# migrations.cr +# =================== + +require "db" + +module CRE::Persistence::Postgres + module Migrations + record Step, version : Int32, statements : Array(String) + + MIGRATIONS = [ + Step.new(1, [ + <<-SQL, + CREATE TABLE IF NOT EXISTS credentials ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + external_id TEXT NOT NULL, + kind TEXT NOT NULL, + name TEXT NOT NULL, + tags JSONB NOT NULL DEFAULT '{}'::jsonb, + current_version_id UUID, + pending_version_id UUID, + previous_version_id UUID, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (kind, external_id) + ) + SQL + "CREATE INDEX IF NOT EXISTS credentials_tags_gin ON credentials USING gin (tags jsonb_path_ops)", + <<-SQL, + CREATE TABLE IF NOT EXISTS credential_versions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + credential_id UUID NOT NULL REFERENCES credentials(id), + ciphertext BYTEA NOT NULL, + dek_wrapped BYTEA NOT NULL, + kek_version INT NOT NULL, + algorithm_id SMALLINT NOT NULL, + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + generated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + revoked_at TIMESTAMPTZ + ) + SQL + <<-SQL, + CREATE TABLE IF NOT EXISTS rotations ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + credential_id UUID NOT NULL REFERENCES credentials(id), + rotator_kind TEXT NOT NULL, + state TEXT NOT NULL, + started_at TIMESTAMPTZ NOT NULL DEFAULT now(), + completed_at TIMESTAMPTZ, + step_outcomes JSONB NOT NULL DEFAULT '{}'::jsonb, + failure_reason TEXT + ) + SQL + <<-SQL, + CREATE INDEX IF NOT EXISTS rotations_in_flight + ON rotations(state) + WHERE state NOT IN ('completed','failed','aborted','inconsistent') + SQL + <<-SQL, + CREATE TABLE IF NOT EXISTS audit_events ( + seq BIGSERIAL PRIMARY KEY, + event_id UUID UNIQUE NOT NULL DEFAULT gen_random_uuid(), + occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(), + event_type TEXT NOT NULL, + actor TEXT NOT NULL, + target_id UUID, + payload JSONB NOT NULL, + prev_hash BYTEA NOT NULL, + content_hash BYTEA NOT NULL, + hmac BYTEA NOT NULL, + hmac_key_version INT NOT NULL + ) + SQL + <<-SQL, + CREATE TABLE IF NOT EXISTS audit_batches ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + start_seq BIGINT NOT NULL, + end_seq BIGINT NOT NULL, + merkle_root BYTEA NOT NULL, + signature BYTEA NOT NULL, + signing_key_version INT NOT NULL, + sealed_at TIMESTAMPTZ NOT NULL DEFAULT now() + ) + SQL + <<-SQL, + CREATE TABLE IF NOT EXISTS kek_versions ( + version INT PRIMARY KEY, + source TEXT NOT NULL, + source_ref TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + retired_at TIMESTAMPTZ + ) + SQL + <<-SQL, + CREATE OR REPLACE FUNCTION audit_no_modify() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'audit_events is append-only'; END $$ + SQL + "DROP TRIGGER IF EXISTS audit_events_no_update ON audit_events", + <<-SQL, + CREATE TRIGGER audit_events_no_update + BEFORE UPDATE OR DELETE OR TRUNCATE + ON audit_events + EXECUTE FUNCTION audit_no_modify() + SQL + ]), + Step.new(2, [ + "ALTER TABLE credentials ADD COLUMN IF NOT EXISTS last_rotated_at TIMESTAMPTZ", + "UPDATE credentials SET last_rotated_at = updated_at WHERE last_rotated_at IS NULL", + ]), + Step.new(3, [ + "CREATE INDEX IF NOT EXISTS credentials_last_rotated_at ON credentials(last_rotated_at)", + "CREATE INDEX IF NOT EXISTS credential_versions_credential_id ON credential_versions(credential_id)", + <<-SQL, + CREATE UNIQUE INDEX IF NOT EXISTS rotations_one_in_flight_per_cred + ON rotations(credential_id) + WHERE state NOT IN ('completed','failed','aborted','inconsistent') + SQL + ]), + ] + + def self.run(db : DB::Database) : Nil + db.exec("CREATE TABLE IF NOT EXISTS schema_migrations (version INT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())") + applied = applied_versions(db) + MIGRATIONS.each do |step| + next if applied.includes?(step.version) + step.statements.each { |stmt| db.exec(stmt) } + db.exec("INSERT INTO schema_migrations (version) VALUES ($1)", step.version) + end + end + + private def self.applied_versions(db : DB::Database) : Set(Int32) + versions = Set(Int32).new + db.query("SELECT version FROM schema_migrations") do |rs| + rs.each { versions << rs.read(Int32) } + end + versions + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/postgres_persistence.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/postgres_persistence.cr new file mode 100644 index 00000000..661dc7a9 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/postgres_persistence.cr @@ -0,0 +1,66 @@ +# =================== +# ©AngelaMos | 2026 +# postgres_persistence.cr +# =================== + +require "db" +require "pg" +require "../persistence" +require "./migrations" +require "./credentials_repo" +require "./versions_repo" +require "./rotations_repo" +require "./audit_repo" + +module CRE::Persistence::Postgres + class PostgresPersistence < CRE::Persistence::Persistence + @db : DB::Database + @credentials : CredentialsRepo? + @versions : VersionsRepo? + @rotations : RotationsRepo? + @audit : AuditRepo? + + def initialize(database_url : String) + @db = DB.open(database_url) + end + + def credentials : CredentialsRepo + @credentials ||= CredentialsRepo.new(@db) + end + + def versions : VersionsRepo + @versions ||= VersionsRepo.new(@db) + end + + def rotations : RotationsRepo + @rotations ||= RotationsRepo.new(@db) + end + + def audit : AuditRepo + @audit ||= AuditRepo.new(@db) + end + + def transaction(&block : ->) : Nil + @db.transaction { yield } + end + + def with_advisory_lock(key : Int64, &block : ->) : Nil + @db.transaction do |tx| + tx.connection.exec("SELECT pg_advisory_xact_lock($1)", key) + yield + end + end + + def migrate! : Nil + Migrations.run(@db) + end + + def close : Nil + @db.close + end + + def db : DB::Database + @db + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/rotations_repo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/rotations_repo.cr new file mode 100644 index 00000000..8380e503 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/rotations_repo.cr @@ -0,0 +1,53 @@ +# =================== +# ©AngelaMos | 2026 +# rotations_repo.cr +# =================== + +require "db" +require "uuid" +require "../repos" + +module CRE::Persistence::Postgres + class RotationsRepo < CRE::Persistence::RotationsRepo + SELECT_COLS = "id::text, credential_id::text, rotator_kind, state, started_at, completed_at, failure_reason" + + def initialize(@db : DB::Database) + end + + def insert(rotation : RotationRecord) : Nil + @db.exec( + "INSERT INTO rotations (id, credential_id, rotator_kind, state, started_at, completed_at, failure_reason) VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, $7)", + rotation.id.to_s, rotation.credential_id.to_s, + rotation.rotator_kind.to_s, rotation.state.to_s, + rotation.started_at, rotation.completed_at, rotation.failure_reason, + ) + end + + def update_state(id : UUID, state : RotationState, error : String? = nil) : Nil + completed_at = TERMINAL_STATES.includes?(state) ? Time.utc : nil + @db.exec( + "UPDATE rotations SET state = $1, completed_at = $2, failure_reason = COALESCE($3, failure_reason) WHERE id = $4::uuid", + state.to_s, completed_at, error, id.to_s, + ) + end + + def in_flight : Array(RotationRecord) + @db.query_all( + "SELECT #{SELECT_COLS} FROM rotations WHERE state NOT IN ('completed','failed','aborted','inconsistent')", + as: {String, String, String, String, Time, Time?, String?}, + ).map { |row| row_to_record(row) } + end + + private def row_to_record(row) : RotationRecord + RotationRecord.new( + id: UUID.new(row[0]), + credential_id: UUID.new(row[1]), + rotator_kind: RotatorKind.parse(row[2]), + state: RotationState.parse(row[3]), + started_at: row[4], + completed_at: row[5], + failure_reason: row[6], + ) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/versions_repo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/versions_repo.cr new file mode 100644 index 00000000..a4d1b74b --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/postgres/versions_repo.cr @@ -0,0 +1,67 @@ +# =================== +# ©AngelaMos | 2026 +# versions_repo.cr +# =================== + +require "db" +require "json" +require "uuid" +require "../repos" +require "../../domain/credential_version" + +module CRE::Persistence::Postgres + class VersionsRepo < CRE::Persistence::VersionsRepo + SELECT_COLS = "id::text, credential_id::text, ciphertext, dek_wrapped, kek_version, algorithm_id, metadata::text, generated_at, revoked_at" + + def initialize(@db : DB::Database) + end + + def insert(v : Domain::CredentialVersion) : Nil + @db.exec( + "INSERT INTO credential_versions (id, credential_id, ciphertext, dek_wrapped, kek_version, algorithm_id, metadata, generated_at, revoked_at) VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, $7::jsonb, $8, $9)", + v.id.to_s, v.credential_id.to_s, + v.ciphertext, v.dek_wrapped, + v.kek_version, v.algorithm_id.to_i32, + v.metadata.to_json, v.generated_at, + v.revoked_at, + ) + end + + def find(id : UUID) : Domain::CredentialVersion? + @db.query_one?( + "SELECT #{SELECT_COLS} FROM credential_versions WHERE id = $1::uuid", + id.to_s, + as: {String, String, Bytes, Bytes, Int32, Int16, String, Time, Time?}, + ).try { |row| row_to_version(row) } + end + + def for_credential(credential_id : UUID) : Array(Domain::CredentialVersion) + @db.query_all( + "SELECT #{SELECT_COLS} FROM credential_versions WHERE credential_id = $1::uuid ORDER BY generated_at DESC", + credential_id.to_s, + as: {String, String, Bytes, Bytes, Int32, Int16, String, Time, Time?}, + ).map { |row| row_to_version(row) } + end + + def revoke(id : UUID, at : Time = Time.utc) : Nil + @db.exec( + "UPDATE credential_versions SET revoked_at = $1 WHERE id = $2::uuid", + at, id.to_s, + ) + end + + private def row_to_version(row) : Domain::CredentialVersion + Domain::CredentialVersion.new( + id: UUID.new(row[0]), + credential_id: UUID.new(row[1]), + ciphertext: row[2], + dek_wrapped: row[3], + kek_version: row[4], + algorithm_id: row[5], + metadata: Hash(String, String).from_json(row[6]), + generated_at: row[7], + revoked_at: row[8], + ) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/repos.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/repos.cr new file mode 100644 index 00000000..ea0bfaa9 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/repos.cr @@ -0,0 +1,95 @@ +# =================== +# ©AngelaMos | 2026 +# repos.cr +# =================== + +require "uuid" +require "../domain/credential" +require "../domain/credential_version" + +module CRE::Persistence + enum RotatorKind + AwsSecretsmgr + VaultDynamic + GithubPat + EnvFile + end + + enum RotationState + Pending + Generating + Applying + Verifying + Committing + Completed + Failed + Aborted + Inconsistent + end + + TERMINAL_STATES = [RotationState::Completed, RotationState::Failed, RotationState::Aborted, RotationState::Inconsistent] + + record RotationRecord, + id : UUID, + credential_id : UUID, + rotator_kind : RotatorKind, + state : RotationState, + started_at : Time, + completed_at : Time?, + failure_reason : String? + + record AuditEntry, + seq : Int64, + event_id : UUID, + occurred_at : Time, + event_type : String, + actor : String, + target_id : UUID?, + payload : String, + prev_hash : Bytes, + content_hash : Bytes, + hmac : Bytes, + hmac_key_version : Int32 + + record AuditBatch, + id : UUID, + start_seq : Int64, + end_seq : Int64, + merkle_root : Bytes, + signature : Bytes, + signing_key_version : Int32, + sealed_at : Time + + abstract class CredentialsRepo + abstract def insert(c : Domain::Credential) : Nil + abstract def update(c : Domain::Credential) : Nil + abstract def find(id : UUID) : Domain::Credential? + abstract def find_by_external(kind : Domain::CredentialKind, external_id : String) : Domain::Credential? + abstract def all : Array(Domain::Credential) + abstract def overdue(now : Time, max_age : Time::Span) : Array(Domain::Credential) + end + + abstract class VersionsRepo + abstract def insert(v : Domain::CredentialVersion) : Nil + abstract def find(id : UUID) : Domain::CredentialVersion? + abstract def for_credential(credential_id : UUID) : Array(Domain::CredentialVersion) + abstract def revoke(id : UUID, at : Time = Time.utc) : Nil + end + + abstract class RotationsRepo + abstract def insert(rotation : RotationRecord) : Nil + abstract def update_state(id : UUID, state : RotationState, error : String? = nil) : Nil + abstract def in_flight : Array(RotationRecord) + end + + abstract class AuditRepo + abstract def append(entry : AuditEntry) : Nil + abstract def latest_hash : Bytes + abstract def latest_seq : Int64 + abstract def range(start_seq : Int64, end_seq : Int64) : Array(AuditEntry) + abstract def each_in_range(start_seq : Int64, end_seq : Int64, &block : AuditEntry ->) : Nil + abstract def insert_batch(batch : AuditBatch) : Nil + abstract def last_sealed_seq : Int64 + abstract def all_batches : Array(AuditBatch) + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/audit_repo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/audit_repo.cr new file mode 100644 index 00000000..a470e9f7 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/audit_repo.cr @@ -0,0 +1,132 @@ +# =================== +# ©AngelaMos | 2026 +# audit_repo.cr +# =================== + +require "db" +require "uuid" +require "../repos" + +module CRE::Persistence::Sqlite + class AuditRepo < CRE::Persistence::AuditRepo + GENESIS_HASH = Bytes.new(32, 0_u8) + + SELECT_ENTRY_COLS = "seq, event_id, occurred_at, event_type, actor, target_id, payload, prev_hash, content_hash, hmac, hmac_key_version" + SELECT_BATCH_COLS = "id, start_seq, end_seq, merkle_root, signature, signing_key_version, sealed_at" + + def initialize(@db : DB::Database) + end + + def append(entry : AuditEntry) : Nil + @db.exec( + "INSERT INTO audit_events (event_id, occurred_at, event_type, actor, target_id, payload, prev_hash, content_hash, hmac, hmac_key_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + entry.event_id.to_s, entry.occurred_at.to_rfc3339, + entry.event_type, entry.actor, + entry.target_id.try(&.to_s), + entry.payload, + entry.prev_hash, entry.content_hash, entry.hmac, + entry.hmac_key_version, + ) + end + + def latest_hash : Bytes + result = @db.query_one?( + "SELECT content_hash FROM audit_events ORDER BY seq DESC LIMIT 1", + as: Bytes, + ) + result || GENESIS_HASH + end + + def latest_seq : Int64 + result = @db.query_one?( + "SELECT seq FROM audit_events ORDER BY seq DESC LIMIT 1", + as: Int64, + ) + result || 0_i64 + end + + def range(start_seq : Int64, end_seq : Int64) : Array(AuditEntry) + @db.query_all( + "SELECT #{SELECT_ENTRY_COLS} FROM audit_events WHERE seq >= ? AND seq <= ? ORDER BY seq ASC", + start_seq, end_seq, + as: {Int64, String, String, String, String, String?, String, Bytes, Bytes, Bytes, Int32}, + ).map { |row| row_to_entry(row) } + end + + def each_in_range(start_seq : Int64, end_seq : Int64, &block : AuditEntry ->) : Nil + @db.query( + "SELECT #{SELECT_ENTRY_COLS} FROM audit_events WHERE seq >= ? AND seq <= ? ORDER BY seq ASC", + start_seq, end_seq, + ) do |rs| + rs.each do + entry = AuditEntry.new( + seq: rs.read(Int64), + event_id: UUID.new(rs.read(String)), + occurred_at: Time.parse_rfc3339(rs.read(String)), + event_type: rs.read(String), + actor: rs.read(String), + target_id: rs.read(String?).try { |s| UUID.new(s) }, + payload: rs.read(String), + prev_hash: rs.read(Bytes), + content_hash: rs.read(Bytes), + hmac: rs.read(Bytes), + hmac_key_version: rs.read(Int32), + ) + block.call(entry) + end + end + end + + def insert_batch(batch : AuditBatch) : Nil + @db.exec( + "INSERT INTO audit_batches (id, start_seq, end_seq, merkle_root, signature, signing_key_version, sealed_at) VALUES (?, ?, ?, ?, ?, ?, ?)", + batch.id.to_s, batch.start_seq, batch.end_seq, + batch.merkle_root, batch.signature, + batch.signing_key_version, batch.sealed_at.to_rfc3339, + ) + end + + def last_sealed_seq : Int64 + result = @db.query_one?( + "SELECT MAX(end_seq) FROM audit_batches", + as: Int64?, + ) + result || 0_i64 + end + + def all_batches : Array(AuditBatch) + @db.query_all( + "SELECT #{SELECT_BATCH_COLS} FROM audit_batches ORDER BY start_seq ASC", + as: {String, Int64, Int64, Bytes, Bytes, Int32, String}, + ).map { |row| row_to_batch(row) } + end + + private def row_to_entry(row) : AuditEntry + AuditEntry.new( + seq: row[0], + event_id: UUID.new(row[1]), + occurred_at: Time.parse_rfc3339(row[2]), + event_type: row[3], + actor: row[4], + target_id: row[5].try { |s| UUID.new(s) }, + payload: row[6], + prev_hash: row[7], + content_hash: row[8], + hmac: row[9], + hmac_key_version: row[10], + ) + end + + private def row_to_batch(row) : AuditBatch + AuditBatch.new( + id: UUID.new(row[0]), + start_seq: row[1], + end_seq: row[2], + merkle_root: row[3], + signature: row[4], + signing_key_version: row[5], + sealed_at: Time.parse_rfc3339(row[6]), + ) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/credentials_repo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/credentials_repo.cr new file mode 100644 index 00000000..96f1aa4c --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/credentials_repo.cr @@ -0,0 +1,94 @@ +# =================== +# ©AngelaMos | 2026 +# credentials_repo.cr +# =================== + +require "db" +require "json" +require "uuid" +require "../repos" +require "../../domain/credential" + +module CRE::Persistence::Sqlite + class CredentialsRepo < CRE::Persistence::CredentialsRepo + SELECT_COLS = "id, external_id, kind, name, tags, current_version_id, pending_version_id, previous_version_id, created_at, updated_at, last_rotated_at" + + def initialize(@db : DB::Database) + end + + def insert(c : Domain::Credential) : Nil + @db.exec( + "INSERT INTO credentials (id, external_id, kind, name, tags, current_version_id, pending_version_id, previous_version_id, created_at, updated_at, last_rotated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + c.id.to_s, c.external_id, c.kind.to_s, c.name, + c.tags.to_json, + c.current_version_id.try(&.to_s), + c.pending_version_id.try(&.to_s), + c.previous_version_id.try(&.to_s), + c.created_at.to_rfc3339, c.updated_at.to_rfc3339, + c.last_rotated_at.try(&.to_rfc3339), + ) + end + + def update(c : Domain::Credential) : Nil + @db.exec( + "UPDATE credentials SET name = ?, tags = ?, current_version_id = ?, pending_version_id = ?, previous_version_id = ?, updated_at = ?, last_rotated_at = ? WHERE id = ?", + c.name, c.tags.to_json, + c.current_version_id.try(&.to_s), + c.pending_version_id.try(&.to_s), + c.previous_version_id.try(&.to_s), + Time.utc.to_rfc3339, + c.last_rotated_at.try(&.to_rfc3339), + c.id.to_s, + ) + end + + def find(id : UUID) : Domain::Credential? + @db.query_one?( + "SELECT #{SELECT_COLS} FROM credentials WHERE id = ?", + id.to_s, + as: {String, String, String, String, String, String?, String?, String?, String, String, String?}, + ).try { |row| row_to_credential(row) } + end + + def find_by_external(kind : Domain::CredentialKind, external_id : String) : Domain::Credential? + @db.query_one?( + "SELECT #{SELECT_COLS} FROM credentials WHERE kind = ? AND external_id = ?", + kind.to_s, external_id, + as: {String, String, String, String, String, String?, String?, String?, String, String, String?}, + ).try { |row| row_to_credential(row) } + end + + def all : Array(Domain::Credential) + @db.query_all( + "SELECT #{SELECT_COLS} FROM credentials", + as: {String, String, String, String, String, String?, String?, String?, String, String, String?}, + ).map { |row| row_to_credential(row) } + end + + def overdue(now : Time, max_age : Time::Span) : Array(Domain::Credential) + cutoff = (now - max_age).to_rfc3339 + @db.query_all( + "SELECT #{SELECT_COLS} FROM credentials WHERE COALESCE(last_rotated_at, created_at) < ?", + cutoff, + as: {String, String, String, String, String, String?, String?, String?, String, String, String?}, + ).map { |row| row_to_credential(row) } + end + + private def row_to_credential(row) : Domain::Credential + tags = Hash(String, String).from_json(row[4]) + Domain::Credential.new( + id: UUID.new(row[0]), + external_id: row[1], + kind: Domain::CredentialKind.parse(row[2]), + name: row[3], + tags: tags, + current_version_id: row[5].try { |s| UUID.new(s) }, + pending_version_id: row[6].try { |s| UUID.new(s) }, + previous_version_id: row[7].try { |s| UUID.new(s) }, + created_at: Time.parse_rfc3339(row[8]), + updated_at: Time.parse_rfc3339(row[9]), + last_rotated_at: row[10].try { |s| Time.parse_rfc3339(s) }, + ) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/migrations.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/migrations.cr new file mode 100644 index 00000000..84d25aac --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/migrations.cr @@ -0,0 +1,130 @@ +# =================== +# ©AngelaMos | 2026 +# migrations.cr +# =================== + +require "db" + +module CRE::Persistence::Sqlite + module Migrations + record Step, version : Int32, statements : Array(String) + + MIGRATIONS = [ + Step.new(1, [ + <<-SQL, + CREATE TABLE IF NOT EXISTS credentials ( + id TEXT PRIMARY KEY, + external_id TEXT NOT NULL, + kind TEXT NOT NULL, + name TEXT NOT NULL, + tags TEXT NOT NULL DEFAULT '{}', + current_version_id TEXT, + pending_version_id TEXT, + previous_version_id TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE (kind, external_id) + ) + SQL + <<-SQL, + CREATE TABLE IF NOT EXISTS credential_versions ( + id TEXT PRIMARY KEY, + credential_id TEXT NOT NULL REFERENCES credentials(id), + ciphertext BLOB NOT NULL, + dek_wrapped BLOB NOT NULL, + kek_version INTEGER NOT NULL, + algorithm_id INTEGER NOT NULL, + metadata TEXT NOT NULL DEFAULT '{}', + generated_at TEXT NOT NULL, + revoked_at TEXT + ) + SQL + <<-SQL, + CREATE TABLE IF NOT EXISTS rotations ( + id TEXT PRIMARY KEY, + credential_id TEXT NOT NULL, + rotator_kind TEXT NOT NULL, + state TEXT NOT NULL, + started_at TEXT NOT NULL, + completed_at TEXT, + step_outcomes TEXT NOT NULL DEFAULT '{}', + failure_reason TEXT + ) + SQL + <<-SQL, + CREATE TABLE IF NOT EXISTS audit_events ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + event_id TEXT UNIQUE NOT NULL, + occurred_at TEXT NOT NULL, + event_type TEXT NOT NULL, + actor TEXT NOT NULL, + target_id TEXT, + payload TEXT NOT NULL, + prev_hash BLOB NOT NULL, + content_hash BLOB NOT NULL, + hmac BLOB NOT NULL, + hmac_key_version INTEGER NOT NULL + ) + SQL + <<-SQL, + CREATE TABLE IF NOT EXISTS audit_batches ( + id TEXT PRIMARY KEY, + start_seq INTEGER NOT NULL, + end_seq INTEGER NOT NULL, + merkle_root BLOB NOT NULL, + signature BLOB NOT NULL, + signing_key_version INTEGER NOT NULL, + sealed_at TEXT NOT NULL + ) + SQL + <<-SQL, + CREATE TABLE IF NOT EXISTS kek_versions ( + version INTEGER PRIMARY KEY, + source TEXT NOT NULL, + source_ref TEXT, + created_at TEXT NOT NULL, + retired_at TEXT + ) + SQL + ]), + Step.new(2, [ + <<-SQL, + CREATE TRIGGER IF NOT EXISTS audit_events_no_update + BEFORE UPDATE ON audit_events + BEGIN SELECT RAISE(ABORT, 'audit_events is append-only'); END + SQL + <<-SQL, + CREATE TRIGGER IF NOT EXISTS audit_events_no_delete + BEFORE DELETE ON audit_events + BEGIN SELECT RAISE(ABORT, 'audit_events is append-only'); END + SQL + ]), + Step.new(3, [ + "ALTER TABLE credentials ADD COLUMN last_rotated_at TEXT", + "UPDATE credentials SET last_rotated_at = updated_at WHERE last_rotated_at IS NULL", + ]), + Step.new(4, [ + "CREATE INDEX IF NOT EXISTS credentials_last_rotated_at ON credentials(last_rotated_at)", + "CREATE INDEX IF NOT EXISTS credential_versions_credential_id ON credential_versions(credential_id)", + ]), + ] + + def self.run(db : DB::Database) : Nil + db.exec("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)") + applied = applied_versions(db) + MIGRATIONS.each do |step| + next if applied.includes?(step.version) + step.statements.each { |stmt| db.exec(stmt) } + db.exec("INSERT INTO schema_migrations (version) VALUES (?)", step.version) + end + end + + private def self.applied_versions(db : DB::Database) : Set(Int32) + versions = Set(Int32).new + db.query("SELECT version FROM schema_migrations") do |rs| + rs.each { versions << rs.read(Int32) } + end + versions + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/rotations_repo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/rotations_repo.cr new file mode 100644 index 00000000..df72595f --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/rotations_repo.cr @@ -0,0 +1,56 @@ +# =================== +# ©AngelaMos | 2026 +# rotations_repo.cr +# =================== + +require "db" +require "uuid" +require "../repos" + +module CRE::Persistence::Sqlite + class RotationsRepo < CRE::Persistence::RotationsRepo + SELECT_COLS = "id, credential_id, rotator_kind, state, started_at, completed_at, failure_reason" + + def initialize(@db : DB::Database) + end + + def insert(rotation : RotationRecord) : Nil + @db.exec( + "INSERT INTO rotations (id, credential_id, rotator_kind, state, started_at, completed_at, failure_reason) VALUES (?, ?, ?, ?, ?, ?, ?)", + rotation.id.to_s, rotation.credential_id.to_s, + rotation.rotator_kind.to_s, rotation.state.to_s, + rotation.started_at.to_rfc3339, + rotation.completed_at.try(&.to_rfc3339), + rotation.failure_reason, + ) + end + + def update_state(id : UUID, state : RotationState, error : String? = nil) : Nil + completed_at = TERMINAL_STATES.includes?(state) ? Time.utc.to_rfc3339 : nil + @db.exec( + "UPDATE rotations SET state = ?, completed_at = ?, failure_reason = COALESCE(?, failure_reason) WHERE id = ?", + state.to_s, completed_at, error, id.to_s, + ) + end + + def in_flight : Array(RotationRecord) + placeholders = TERMINAL_STATES.map { "?" }.join(",") + args = TERMINAL_STATES.map { |s| s.to_s.as(DB::Any) } + sql = "SELECT #{SELECT_COLS} FROM rotations WHERE state NOT IN (#{placeholders})" + @db.query_all(sql, args: args, as: {String, String, String, String, String, String?, String?}) + .map { |row| row_to_record(row) } + end + + private def row_to_record(row) : RotationRecord + RotationRecord.new( + id: UUID.new(row[0]), + credential_id: UUID.new(row[1]), + rotator_kind: RotatorKind.parse(row[2]), + state: RotationState.parse(row[3]), + started_at: Time.parse_rfc3339(row[4]), + completed_at: row[5].try { |s| Time.parse_rfc3339(s) }, + failure_reason: row[6], + ) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/sqlite_persistence.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/sqlite_persistence.cr new file mode 100644 index 00000000..58c61c69 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/sqlite_persistence.cr @@ -0,0 +1,77 @@ +# =================== +# ©AngelaMos | 2026 +# sqlite_persistence.cr +# =================== + +require "db" +require "sqlite3" +require "../persistence" +require "./migrations" +require "./credentials_repo" +require "./versions_repo" +require "./rotations_repo" +require "./audit_repo" + +module CRE::Persistence::Sqlite + class SqlitePersistence < CRE::Persistence::Persistence + @db : DB::Database + @mutex : Mutex + @credentials : CredentialsRepo? + @versions : VersionsRepo? + @rotations : RotationsRepo? + @audit : AuditRepo? + + def initialize(path : String) + uri = if path == ":memory:" + "sqlite3:%3Amemory%3A?max_pool_size=1" + else + "sqlite3:#{path}?max_pool_size=1" + end + @db = DB.open(uri) + @mutex = Mutex.new + setup_pragmas + end + + def credentials : CredentialsRepo + @credentials ||= CredentialsRepo.new(@db) + end + + def versions : VersionsRepo + @versions ||= VersionsRepo.new(@db) + end + + def rotations : RotationsRepo + @rotations ||= RotationsRepo.new(@db) + end + + def audit : AuditRepo + @audit ||= AuditRepo.new(@db) + end + + def transaction(&block : ->) : Nil + @db.transaction { yield } + end + + def with_advisory_lock(key : Int64, &block : ->) : Nil + _ = key # SQLite is single-process; the mutex is sufficient + @mutex.synchronize { yield } + end + + def migrate! : Nil + Migrations.run(@db) + end + + def close : Nil + @db.close + end + + def db : DB::Database + @db + end + + private def setup_pragmas + @db.exec("PRAGMA foreign_keys = ON") + @db.exec("PRAGMA synchronous = NORMAL") + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/versions_repo.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/versions_repo.cr new file mode 100644 index 00000000..0688af6e --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/persistence/sqlite/versions_repo.cr @@ -0,0 +1,67 @@ +# =================== +# ©AngelaMos | 2026 +# versions_repo.cr +# =================== + +require "db" +require "json" +require "uuid" +require "../repos" +require "../../domain/credential_version" + +module CRE::Persistence::Sqlite + class VersionsRepo < CRE::Persistence::VersionsRepo + SELECT_COLS = "id, credential_id, ciphertext, dek_wrapped, kek_version, algorithm_id, metadata, generated_at, revoked_at" + + def initialize(@db : DB::Database) + end + + def insert(v : Domain::CredentialVersion) : Nil + @db.exec( + "INSERT INTO credential_versions (id, credential_id, ciphertext, dek_wrapped, kek_version, algorithm_id, metadata, generated_at, revoked_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + v.id.to_s, v.credential_id.to_s, + v.ciphertext, v.dek_wrapped, + v.kek_version, v.algorithm_id.to_i32, + v.metadata.to_json, v.generated_at.to_rfc3339, + v.revoked_at.try(&.to_rfc3339), + ) + end + + def find(id : UUID) : Domain::CredentialVersion? + @db.query_one?( + "SELECT #{SELECT_COLS} FROM credential_versions WHERE id = ?", + id.to_s, + as: {String, String, Bytes, Bytes, Int32, Int32, String, String, String?}, + ).try { |row| row_to_version(row) } + end + + def for_credential(credential_id : UUID) : Array(Domain::CredentialVersion) + @db.query_all( + "SELECT #{SELECT_COLS} FROM credential_versions WHERE credential_id = ? ORDER BY generated_at DESC", + credential_id.to_s, + as: {String, String, Bytes, Bytes, Int32, Int32, String, String, String?}, + ).map { |row| row_to_version(row) } + end + + def revoke(id : UUID, at : Time = Time.utc) : Nil + @db.exec( + "UPDATE credential_versions SET revoked_at = ? WHERE id = ?", + at.to_rfc3339, id.to_s, + ) + end + + private def row_to_version(row) : Domain::CredentialVersion + Domain::CredentialVersion.new( + id: UUID.new(row[0]), + credential_id: UUID.new(row[1]), + ciphertext: row[2], + dek_wrapped: row[3], + kek_version: row[4], + algorithm_id: row[5].to_i16, + metadata: Hash(String, String).from_json(row[6]), + generated_at: Time.parse_rfc3339(row[7]), + revoked_at: row[8].try { |s| Time.parse_rfc3339(s) }, + ) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/builder.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/builder.cr new file mode 100644 index 00000000..39d6b700 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/builder.cr @@ -0,0 +1,87 @@ +# =================== +# ©AngelaMos | 2026 +# builder.cr +# =================== + +require "./policy" + +module CRE::Policy + class BuilderError < Exception; end + + class Builder + @name : String + @description : String? + @matcher : Matcher? + @max_age : Time::Span? + @warn_at : Time::Span? + @enforce_action : Action? + @notify_channels : Array(Channel) + @triggers : Hash(Trigger, Action) + + def initialize(@name : String) + @notify_channels = [] of Channel + @triggers = {} of Trigger => Action + end + + def description(text : String) : Nil + @description = text + end + + def match(&block : Domain::Credential -> Bool) : Nil + @matcher = block + end + + def max_age(span : Time::Span) : Nil + @max_age = span + end + + def warn_at(span : Time::Span) : Nil + @warn_at = span + end + + def enforce(action : Action) : Nil + @enforce_action = action + end + + def notify_via(*ch : Channel) : Nil + ch.each { |c| @notify_channels << c } + end + + def notify_via(*ch : Symbol) : Nil + ch.each do |s| + parsed = Channel.parse?(s.to_s) + raise BuilderError.new("unknown channel '#{s}' in policy '#{@name}' (valid: #{Channel.values.map(&.to_s).join(", ")})") if parsed.nil? + @notify_channels << parsed + end + end + + def on_rotation_failure(action : Action) : Nil + @triggers[Trigger::OnRotationFailure] = action + end + + def on_drift_detected(action : Action) : Nil + @triggers[Trigger::OnDriftDetected] = action + end + + def on_policy_violation(action : Action) : Nil + @triggers[Trigger::OnPolicyViolation] = action + end + + def build : Policy + matcher = @matcher || raise BuilderError.new("policy '#{@name}' is missing match{} block") + max_age = @max_age || raise BuilderError.new("policy '#{@name}' is missing max_age") + enforce_action = @enforce_action || raise BuilderError.new("policy '#{@name}' is missing enforce") + + Policy.new( + name: @name, + description: @description, + matcher: matcher, + max_age: max_age, + warn_at: @warn_at, + enforce_action: enforce_action, + notify_channels: @notify_channels, + triggers: @triggers, + ) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/dsl.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/dsl.cr new file mode 100644 index 00000000..ff7c4b71 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/dsl.cr @@ -0,0 +1,33 @@ +# =================== +# ©AngelaMos | 2026 +# dsl.cr +# =================== + +require "./builder" +require "./policy" + +module CRE::Policy::Dsl + # Top-level-feeling DSL for declaring policies. Users opt in: + # + # require "cre/policy/dsl" + # include CRE::Policy::Dsl + # + # policy "production-aws-secrets" do + # description "All prod AWS secrets rotate every 30 days" + # match { |c| c.kind.aws_secretsmgr? && c.tag(:env) == "prod" } + # max_age 30.days + # enforce :rotate_immediately + # notify_via :telegram, :structured_log + # end + # + # Single-symbol args (`enforce :rotate_immediately`) autocast to enum + # values via Crystal's parameter typing — typos like + # `enforce :rotate_immediatly` fail at compile time. Splat-symbol args + # (`notify_via :telegram, :structured_log`) are validated at policy + # registration time and raise `BuilderError` on typos. + def policy(name : String, &block) + builder = CRE::Policy::Builder.new(name) + with builder yield + CRE::Policy::REGISTRY << builder.build + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/evaluator.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/evaluator.cr new file mode 100644 index 00000000..11cc25cc --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/evaluator.cr @@ -0,0 +1,127 @@ +# =================== +# ©AngelaMos | 2026 +# evaluator.cr +# =================== + +require "log" +require "./policy" +require "../engine/event_bus" +require "../events/credential_events" +require "../events/system_events" +require "../persistence/persistence" + +module CRE::Policy + class PolicyConflictError < Exception; end + + class Evaluator + Log = ::Log.for("cre.policy.evaluator") + + @ch : ::Channel(Events::Event)? + @running : Bool + + def initialize( + @bus : Engine::EventBus, + @persistence : Persistence::Persistence, + @policies : Array(Policy) = REGISTRY.dup, + ) + @running = false + end + + def start : Nil + @running = true + ch = @bus.subscribe(buffer: 64, overflow: Engine::EventBus::Overflow::Block) + @ch = ch + spawn(name: "policy-evaluator") do + while @running + begin + ev = ch.receive + rescue ::Channel::ClosedError + break + end + handle(ev) + end + end + end + + def stop : Nil + @running = false + @ch.try(&.close) + end + + # evaluate_all groups policies by max_age and uses the persistence layer's + # 'overdue' query so we don't pull every credential into memory each tick. + def evaluate_all(now : Time = Time.utc) : Nil + return if @policies.empty? + + seen = Set(UUID).new + @policies.group_by(&.max_age).each do |max_age, policies_with_age| + @persistence.credentials.overdue(now, max_age).each do |c| + next if seen.includes?(c.id) + seen << c.id + evaluate(c, now) + end + end + end + + # Evaluates a single credential. When more than one policy matches + # we raise PolicyConflictError instead of silently picking by + # registration order; conflicting policies are an operator bug, not + # a runtime decision. + def evaluate(c : Domain::Credential, now : Time = Time.utc) : Nil + matching = @policies.select(&.matches?(c)) + return if matching.empty? + + if matching.size > 1 + names = matching.map(&.name).join(", ") + @bus.publish Events::AlertRaised.new( + severity: Events::Severity::Critical, + message: "credential #{c.id} matches #{matching.size} policies (#{names}); refusing to act until ambiguity is resolved", + ) + raise PolicyConflictError.new("credential #{c.id} matches #{matching.size} policies: #{names}") + end + + policy = matching.first + return unless policy.overdue?(c, now) + + @bus.publish Events::PolicyViolation.new( + c.id, + policy.name, + "credential exceeded max_age=#{policy.max_age} (rotation_anchor #{c.rotation_anchor.to_rfc3339})", + ) + + case policy.enforce_action + in Action::RotateImmediately + @bus.publish Events::RotationScheduled.new(c.id, c.kind.to_s) + in Action::NotifyOnly + @bus.publish Events::AlertRaised.new( + severity: Events::Severity::Warn, + message: "policy '#{policy.name}' violated by credential '#{c.name}' (#{c.id})", + ) + in Action::Quarantine + @bus.publish Events::AlertRaised.new( + severity: Events::Severity::Critical, + message: "policy '#{policy.name}' triggered quarantine on credential '#{c.id}'", + ) + end + rescue ex : PolicyConflictError + Log.error(exception: ex) { "policy conflict for #{c.id}" } + rescue ex + Log.error(exception: ex) { "policy evaluation failed for #{c.id}" } + end + + private def handle(ev : Events::Event) : Nil + case ev + when Events::SchedulerTick + evaluate_all + when Events::CredentialDiscovered + if c = @persistence.credentials.find(ev.credential_id) + evaluate(c) + end + when Events::RotationCompleted + if c = @persistence.credentials.find(ev.credential_id) + evaluate(c) + end + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/policy.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/policy.cr new file mode 100644 index 00000000..a8e75e6d --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/policy/policy.cr @@ -0,0 +1,80 @@ +# =================== +# ©AngelaMos | 2026 +# policy.cr +# =================== + +require "../domain/credential" + +module CRE::Policy + enum Action + RotateImmediately + NotifyOnly + Quarantine + end + + enum Channel + Telegram + Email + StructuredLog + PagerDuty + end + + enum Trigger + OnRotationFailure + OnDriftDetected + OnPolicyViolation + end + + alias Matcher = Domain::Credential -> Bool + + class Policy + getter name : String + getter description : String? + getter matcher : Matcher + getter max_age : Time::Span + getter warn_at : Time::Span? + getter enforce_action : Action + getter notify_channels : Array(Channel) + getter triggers : Hash(Trigger, Action) + + def initialize( + @name : String, + @description : String?, + @matcher : Matcher, + @max_age : Time::Span, + @warn_at : Time::Span?, + @enforce_action : Action, + @notify_channels : Array(Channel), + @triggers : Hash(Trigger, Action), + ) + end + + def matches?(c : Domain::Credential) : Bool + @matcher.call(c) + end + + def overdue?(c : Domain::Credential, now : Time = Time.utc) : Bool + (now - c.rotation_anchor) > @max_age + end + + def in_warning_window?(c : Domain::Credential, now : Time = Time.utc) : Bool + return false unless w = @warn_at + age = now - c.rotation_anchor + age > w && age <= @max_age + end + + def trigger_action_for(trigger : Trigger) : Action? + @triggers[trigger]? + end + end + + REGISTRY = [] of Policy + + def self.registry : Array(Policy) + REGISTRY + end + + def self.clear_registry! : Nil + REGISTRY.clear + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/aws_secrets.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/aws_secrets.cr new file mode 100644 index 00000000..cf2fc273 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/aws_secrets.cr @@ -0,0 +1,107 @@ +# =================== +# ©AngelaMos | 2026 +# aws_secrets.cr +# =================== + +require "../aws/secrets_client" +require "../crypto/random" +require "./rotator" + +module CRE::Rotators + # AwsSecretsRotator implements the 4-step rotation contract against AWS Secrets + # Manager, mirroring the standard Rotation Lambda template: + # + # 1. generate -> PutSecretValue with AWSPENDING label, returns version_id + # 2. apply -> no-op (PutSecretValue exposed it; AWSPENDING already attached) + # 3. verify -> GetSecretValue by version_id, confirm decoded value matches + # 4. commit -> UpdateSecretVersionStage move AWSCURRENT to new, AWSPREVIOUS to old + # rollback_apply -> remove AWSPENDING stage from the new version + # + # Required Credential.tags: + # "secret_arn" - the AWS Secrets Manager ARN or name + # "value_length" - optional, bytes of random payload (default 32) + class AwsSecretsRotator < Rotator + register_as :aws_secretsmgr + + DEFAULT_BYTES = 32 + + def initialize(@client : Aws::SecretsManagerClient) + end + + def kind : Symbol + :aws_secretsmgr + end + + def can_rotate?(c : Domain::Credential) : Bool + c.kind.aws_secretsmgr? && !c.tag("secret_arn").nil? + end + + def generate(c : Domain::Credential) : Domain::NewSecret + raise RotatorError.new("missing 'secret_arn' tag") unless can_rotate?(c) + bytes = (c.tag("value_length") || DEFAULT_BYTES.to_s).to_i + raw = CRE::Crypto::Random.bytes(bytes) + new_value = Base64.urlsafe_encode(raw, padding: false) + + version = @client.put_secret_value(c.tag("secret_arn").not_nil!, new_value) + Domain::NewSecret.new( + ciphertext: new_value.to_slice, + metadata: { + "version_id" => version.version_id, + "secret_arn" => c.tag("secret_arn").not_nil!, + }, + ) + end + + def apply(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = {c, s} + # No-op: PutSecretValue with AWSPENDING already made the new version available. + end + + def verify(c : Domain::Credential, s : Domain::NewSecret) : Bool + version_id = s.metadata["version_id"] + secret_arn = s.metadata["secret_arn"] + retrieved = @client.get_secret_value(secret_arn, version_id: version_id) + expected = String.new(s.ciphertext) + retrieved.secret_string == expected + rescue + false + end + + def commit(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = c + version_id = s.metadata["version_id"] + secret_arn = s.metadata["secret_arn"] + + # Find the current version_id + current = @client.get_secret_value(secret_arn, version_stage: Aws::SecretsManagerClient::AWSCURRENT) + old_version_id = current.version_id + + # Move AWSCURRENT to new, removing it from old (atomic per AWS API) + @client.update_secret_version_stage( + secret_arn, + Aws::SecretsManagerClient::AWSCURRENT, + move_to_version_id: version_id, + remove_from_version_id: old_version_id, + ) + + # Remove AWSPENDING from new version (it's now AWSCURRENT) + @client.update_secret_version_stage( + secret_arn, + Aws::SecretsManagerClient::AWSPENDING, + remove_from_version_id: version_id, + ) rescue nil + end + + def rollback_apply(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = c + version_id = s.metadata["version_id"]? + secret_arn = s.metadata["secret_arn"]? + return unless version_id && secret_arn + @client.update_secret_version_stage( + secret_arn, + Aws::SecretsManagerClient::AWSPENDING, + remove_from_version_id: version_id, + ) rescue nil + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/env_file.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/env_file.cr new file mode 100644 index 00000000..e33a015a --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/env_file.cr @@ -0,0 +1,100 @@ +# =================== +# ©AngelaMos | 2026 +# env_file.cr +# =================== + +require "../crypto/random" +require "./rotator" + +module CRE::Rotators + # EnvFileRotator manages credentials stored as KEY=value lines in a .env file. + # The rotation produces fresh random bytes (base64-encoded) and atomically + # swaps the live file on commit using temp+rename. + # + # Cross-process safety: each instance writes to a per-PID pending file + # so two daemons targeting the same .env never collide on the staging + # write. The commit-time rename is serialized through an exclusive + # flock(2) on a sibling .lock file so the live file is updated by at + # most one process at a time. + # + # Credential.tags must include: + # "path" - absolute path to the .env file + # "key" - the key whose value rotates + class EnvFileRotator < Rotator + register_as :env_file + + DEFAULT_BYTES = 32 + + def kind : Symbol + :env_file + end + + def can_rotate?(c : Domain::Credential) : Bool + c.kind.env_file? && !c.tag("path").nil? && !c.tag("key").nil? + end + + def generate(c : Domain::Credential) : Domain::NewSecret + raise RotatorError.new("missing 'path' or 'key' tag") unless can_rotate?(c) + bytes = (c.tag("bytes") || DEFAULT_BYTES.to_s).to_i + raw = CRE::Crypto::Random.bytes(bytes) + encoded = Base64.urlsafe_encode(raw, padding: false) + Domain::NewSecret.new( + ciphertext: encoded.to_slice, + metadata: {"key" => c.tag("key").not_nil!}, + ) + end + + def apply(c : Domain::Credential, s : Domain::NewSecret) : Nil + path = c.tag("path").not_nil! + key = c.tag("key").not_nil! + pending = pending_path(path) + + existing = File.exists?(path) ? File.read(path) : "" + lines = existing.lines(chomp: true).reject { |line| line.strip.starts_with?("#{key}=") } + new_value = String.new(s.ciphertext) + lines << "#{key}=#{new_value}" + + File.write(pending, lines.join('\n') + "\n", perm: 0o600) + end + + def verify(c : Domain::Credential, s : Domain::NewSecret) : Bool + path = c.tag("path").not_nil! + key = c.tag("key").not_nil! + pending = pending_path(path) + return false unless File.exists?(pending) + + content = File.read(pending) + expected_line = "#{key}=#{String.new(s.ciphertext)}" + content.includes?(expected_line) && content.bytesize > 0 + end + + def commit(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = s + path = c.tag("path").not_nil! + pending = pending_path(path) + raise RotatorError.new("pending file missing at commit time: #{pending}") unless File.exists?(pending) + + with_lock(path) do + File.rename(pending, path) + end + end + + def rollback_apply(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = s + path = c.tag("path").not_nil! + pending = pending_path(path) + File.delete(pending) if File.exists?(pending) + end + + private def pending_path(path : String) : String + "#{path}.pending.#{Process.pid}" + end + + private def with_lock(path : String, & : -> _) : Nil + lock_path = "#{path}.lock" + File.open(lock_path, "w+") do |lock| + lock.flock_exclusive { yield } + end + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/github_pat.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/github_pat.cr new file mode 100644 index 00000000..85e353fa --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/github_pat.cr @@ -0,0 +1,78 @@ +# =================== +# ©AngelaMos | 2026 +# github_pat.cr +# =================== + +require "json" +require "../github/client" +require "./rotator" + +module CRE::Rotators + # GithubPatRotator manages fine-grained Personal Access Tokens. It uses an + # admin/issuer bearer to create the new PAT and to delete the old one. + # + # Required Credential.tags: + # "name" - PAT label + # "old_pat_id" - the GitHub PAT id to revoke on commit + # "scopes" - JSON-encoded array of scope strings (e.g. ["repo","read:org"]) + # Optional "expires_in_days" - default 90 + class GithubPatRotator < Rotator + register_as :github_pat + + def initialize(@client : Github::Client) + end + + def kind : Symbol + :github_pat + end + + def can_rotate?(c : Domain::Credential) : Bool + c.kind.github_pat? && !c.tag("name").nil? && !c.tag("scopes").nil? + end + + def generate(c : Domain::Credential) : Domain::NewSecret + raise RotatorError.new("missing 'name' or 'scopes' tag") unless can_rotate?(c) + scopes = Array(String).from_json(c.tag("scopes").not_nil!) + expires_in_days = (c.tag("expires_in_days") || "90").to_i + + new_token = @client.create_pat(c.tag("name").not_nil!, scopes, expires_in_days) + + Domain::NewSecret.new( + ciphertext: new_token.token_value.to_slice, + metadata: { + "new_pat_id" => new_token.id.to_s, + "old_pat_id" => c.tag("old_pat_id") || "", + "expires_at" => new_token.expires_at || "", + }, + ) + end + + def apply(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = {c, s} + # No-op: create_pat already exposed the token. Old PAT still works. + end + + def verify(c : Domain::Credential, s : Domain::NewSecret) : Bool + _ = c + probe = Github::Client.new(String.new(s.ciphertext)) + probe.me + true + rescue + false + end + + def commit(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = c + old = s.metadata["old_pat_id"]? + return if old.nil? || old.empty? + @client.delete_pat(old.to_i64) + end + + def rollback_apply(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = c + new_id = s.metadata["new_pat_id"]? + return if new_id.nil? || new_id.empty? + @client.delete_pat(new_id.to_i64) rescue nil + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/rotator.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/rotator.cr new file mode 100644 index 00000000..093187f1 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/rotator.cr @@ -0,0 +1,39 @@ +# =================== +# ©AngelaMos | 2026 +# rotator.cr +# =================== + +require "../domain/credential" +require "../domain/new_secret" + +module CRE::Rotators + class RotatorError < Exception; end + + abstract class Rotator + REGISTRY = {} of Symbol => Rotator.class + + abstract def kind : Symbol + abstract def can_rotate?(c : Domain::Credential) : Bool + + abstract def generate(c : Domain::Credential) : Domain::NewSecret + abstract def apply(c : Domain::Credential, s : Domain::NewSecret) : Nil + abstract def verify(c : Domain::Credential, s : Domain::NewSecret) : Bool + abstract def commit(c : Domain::Credential, s : Domain::NewSecret) : Nil + + # Default no-op; rotators override when apply() creates reversible side effects. + def rollback_apply(c : Domain::Credential, s : Domain::NewSecret) : Nil + end + + macro register_as(kind) + ::CRE::Rotators::Rotator::REGISTRY[{{ kind }}] = self + end + + def self.for(kind : Symbol) : Rotator.class | Nil + REGISTRY[kind]? + end + + def self.registered_kinds : Array(Symbol) + REGISTRY.keys + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/vault_dynamic.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/vault_dynamic.cr new file mode 100644 index 00000000..19ad4815 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/rotators/vault_dynamic.cr @@ -0,0 +1,85 @@ +# =================== +# ©AngelaMos | 2026 +# vault_dynamic.cr +# =================== + +require "json" +require "../vault/client" +require "./rotator" + +module CRE::Rotators + # VaultDynamicRotator manages dynamic-secrets-engine credentials in HashiCorp + # Vault. Vault itself is the secret factory: we ask it for fresh creds and + # revoke old leases on commit. + # + # Required Credential.tags: + # "role_path" - e.g. "database/creds/my-postgres-role" + # Optional "current_lease_id" - the lease to revoke on commit; if absent + # the rotator only revokes the NEW lease on rollback (apply step). + class VaultDynamicRotator < Rotator + register_as :vault_dynamic + + def initialize(@client : Vault::Client) + end + + def kind : Symbol + :vault_dynamic + end + + def can_rotate?(c : Domain::Credential) : Bool + c.kind.vault_dynamic? && !c.tag("role_path").nil? + end + + def generate(c : Domain::Credential) : Domain::NewSecret + raise RotatorError.new("missing 'role_path' tag") unless can_rotate?(c) + role_path = c.tag("role_path").not_nil! + ds = @client.read_dynamic(role_path) + + payload = { + "username" => ds.username, + "password" => ds.password, + }.to_json + + Domain::NewSecret.new( + ciphertext: payload.to_slice, + metadata: { + "lease_id" => ds.lease_id, + "lease_duration" => ds.lease_duration.to_s, + "old_lease_id" => c.tag("current_lease_id") || "", + "username" => ds.username, + }, + ) + end + + def apply(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = {c, s} + # Vault already issued the new credentials and they're live. No-op. + end + + def verify(c : Domain::Credential, s : Domain::NewSecret) : Bool + _ = c + lease_id = s.metadata["lease_id"]? + return false if lease_id.nil? || lease_id.empty? + # Lease renewal acts as a liveness check: if the lease is invalid Vault + # will return non-2xx and we get an exception. + @client.renew_lease(lease_id, increment: 0) + true + rescue + false + end + + def commit(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = c + old = s.metadata["old_lease_id"]? + return if old.nil? || old.empty? + @client.revoke_lease(old) + end + + def rollback_apply(c : Domain::Credential, s : Domain::NewSecret) : Nil + _ = c + lease_id = s.metadata["lease_id"]? + return if lease_id.nil? || lease_id.empty? + @client.revoke_lease(lease_id) rescue nil + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/ansi.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/ansi.cr new file mode 100644 index 00000000..3577f836 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/ansi.cr @@ -0,0 +1,72 @@ +# =================== +# ©AngelaMos | 2026 +# ansi.cr +# =================== + +module CRE::Tui + # Minimal ANSI escape helpers. We hand-roll instead of depending on a TUI + # framework so the rendering is small, predictable, and easy to test by + # capturing IO writes. + module Ansi + ESC = "\e[" + + CLEAR_SCREEN = "#{ESC}2J" + CLEAR_LINE = "#{ESC}2K" + HIDE_CURSOR = "#{ESC}?25l" + SHOW_CURSOR = "#{ESC}?25h" + HOME = "#{ESC}H" + RESET = "#{ESC}0m" + + BOLD = "#{ESC}1m" + DIM = "#{ESC}2m" + + FG_RED = "#{ESC}31m" + FG_GREEN = "#{ESC}32m" + FG_YELLOW = "#{ESC}33m" + FG_BLUE = "#{ESC}34m" + FG_CYAN = "#{ESC}36m" + FG_WHITE = "#{ESC}37m" + FG_GRAY = "#{ESC}90m" + + def self.move(row : Int, col : Int) : String + "#{ESC}#{row};#{col}H" + end + + def self.colorize(text : String, color : String) : String + "#{color}#{text}#{RESET}" + end + + def self.green(text : String) : String + colorize(text, FG_GREEN) + end + + def self.red(text : String) : String + colorize(text, FG_RED) + end + + def self.yellow(text : String) : String + colorize(text, FG_YELLOW) + end + + def self.cyan(text : String) : String + colorize(text, FG_CYAN) + end + + def self.gray(text : String) : String + colorize(text, FG_GRAY) + end + + def self.bold(text : String) : String + colorize(text, BOLD) + end + + def self.dim(text : String) : String + colorize(text, DIM) + end + + # Strip ANSI escape sequences (useful for testing rendered output). + def self.strip(text : String) : String + text.gsub(/\e\[[0-9;?]*[a-zA-Z]/, "") + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/renderer.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/renderer.cr new file mode 100644 index 00000000..68afb463 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/renderer.cr @@ -0,0 +1,112 @@ +# =================== +# ©AngelaMos | 2026 +# renderer.cr +# =================== + +require "./ansi" +require "./state" + +module CRE::Tui + # Renderer paints the four-panel TUI to a target IO. Decoupled from terminal + # ownership so it can render to STDOUT in production or to IO::Memory in + # tests for assertion. + class Renderer + HEADER = "Credential Rotation Enforcer" + PANEL_HR = "─" + PANEL_BL = "└" + PANEL_BR = "┘" + PANEL_TL = "┌" + PANEL_TR = "┐" + PANEL_VL = "│" + PANEL_LMID = "├" + PANEL_RMID = "┤" + WIDTH = 64 + + def initialize(@state : State, @io : IO = STDOUT, @use_color : Bool = true) + end + + def render : Nil + @io << Ansi::HOME + render_header + render_status + render_active + render_recent + render_footer + @io.flush + end + + private def render_header : Nil + title = "#{HEADER} - PID #{Process.pid} | Uptime #{format_span(@state.uptime)}" + line = pad_centered(title, WIDTH - 2) + @io << PANEL_TL << PANEL_HR * (WIDTH - 2) << PANEL_TR << '\n' + @io << PANEL_VL << colorize(line, Ansi::FG_CYAN) << PANEL_VL << '\n' + @io << PANEL_LMID << PANEL_HR * (WIDTH - 2) << PANEL_RMID << '\n' + end + + private def render_status : Nil + header = " STATUS CREDS DUE-NOW OVERDUE ROTATED-24h KEK" + values = " #{Ansi.green("● live")} #{cell(@state.creds_total, 8)}#{cell(@state.due_now, 11)}#{cell(@state.overdue, 11)}#{cell(@state.completed_24h, 15)}v#{@state.kek_version}" + @io << PANEL_VL << pad(header, WIDTH - 2) << PANEL_VL << '\n' + @io << PANEL_VL << pad(values, WIDTH - 2) << PANEL_VL << '\n' + @io << PANEL_LMID << " Active Rotations " << PANEL_HR * (WIDTH - 21) << PANEL_RMID << '\n' + end + + private def cell(n : Int, width : Int) : String + n.to_s.ljust(width) + end + + private def render_active : Nil + if @state.active.empty? + @io << PANEL_VL << pad(" (no active rotations)", WIDTH - 2) << PANEL_VL << '\n' + else + @state.active.values.first(State::MAX_ACTIVE_ROTATIONS).each do |row| + progress = "▰" * row.progress + "▱" * (4 - row.progress) + line = " [▶] #{row.rotator_kind.ljust(20)} #{progress} step #{row.progress}/4: #{row.step}" + @io << PANEL_VL << pad(line, WIDTH - 2) << PANEL_VL << '\n' + end + end + @io << PANEL_LMID << " Recent Events " << PANEL_HR * (WIDTH - 18) << PANEL_RMID << '\n' + end + + private def render_recent : Nil + if @state.recent.empty? + @io << PANEL_VL << pad(" (no events yet)", WIDTH - 2) << PANEL_VL << '\n' + else + @state.recent.last(8).each do |row| + ts = row.occurred_at.to_s("%H:%M:%S") + line = " #{ts} #{row.symbol} #{row.summary}" + @io << PANEL_VL << pad(line, WIDTH - 2) << PANEL_VL << '\n' + end + end + end + + private def render_footer : Nil + @io << PANEL_BL << PANEL_HR * (WIDTH - 2) << PANEL_BR << '\n' + @io << Ansi.dim(" Press Ctrl+C to exit") << '\n' + end + + private def colorize(text : String, color : String) : String + @use_color ? Ansi.colorize(text, color) : text + end + + private def pad(text : String, width : Int) : String + visible = Ansi.strip(text) + return text[0, width + (text.size - visible.size)] if visible.size >= width + text + " " * (width - visible.size) + end + + private def pad_centered(text : String, width : Int) : String + visible_size = Ansi.strip(text).size + return text[0, width] if visible_size >= width + pad = (width - visible_size) // 2 + " " * pad + text + " " * (width - pad - visible_size) + end + + private def format_span(span : Time::Span) : String + total = span.total_seconds.to_i + hours = total // 3600 + mins = (total % 3600) // 60 + "#{hours}h #{mins}m" + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/snapshotter.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/snapshotter.cr new file mode 100644 index 00000000..790ed522 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/snapshotter.cr @@ -0,0 +1,69 @@ +# =================== +# ©AngelaMos | 2026 +# snapshotter.cr +# =================== + +require "log" +require "./state" +require "../persistence/persistence" +require "../policy/policy" + +module CRE::Tui + # Snapshotter polls the persistence layer at a low frequency and updates + # State#creds_total / due_now / overdue. The TUI render path reads the + # cached snapshot, never the database — so a slow query can't stall + # frame paint. + class Snapshotter + Log = ::Log.for("cre.tui.snapshotter") + + @running : Bool + + def initialize( + @state : State, + @persistence : Persistence::Persistence, + @policies : Array(Policy::Policy) = Policy.registry, + @interval : Time::Span = 5.seconds, + ) + @running = false + end + + def start : Nil + @running = true + spawn(name: "tui-snapshotter") do + refresh + while @running + sleep @interval + break unless @running + refresh + end + end + end + + def stop : Nil + @running = false + end + + def refresh : Nil + now = Time.utc + creds = @persistence.credentials.all + total = creds.size + + due_now = 0 + overdue = 0 + creds.each do |c| + matching = @policies.select(&.matches?(c)) + next if matching.empty? + policy = matching.last + if policy.overdue?(c, now) + overdue += 1 + elsif policy.in_warning_window?(c, now) + due_now += 1 + end + end + + @state.update_counts(total, due_now, overdue) + rescue ex + Log.warn(exception: ex) { "tui snapshot refresh failed" } + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/state.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/state.cr new file mode 100644 index 00000000..479770bc --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/state.cr @@ -0,0 +1,122 @@ +# =================== +# ©AngelaMos | 2026 +# state.cr +# =================== + +require "../events/credential_events" +require "../events/system_events" + +module CRE::Tui + # State holds the rolling view of recent events for the TUI to render. + # Updated synchronously from the event subscriber; rendering reads it. + class State + MAX_RECENT_EVENTS = 20 + MAX_ACTIVE_ROTATIONS = 10 + + record EventRow, + occurred_at : Time, + symbol : String, + summary : String + + record RotationRow, + credential_id : UUID, + rotator_kind : String, + step : String, + progress : Int32 # 0..4 + + @recent : Array(EventRow) + @active : Hash(UUID, RotationRow) + @completed_24h : Int32 + @started_at : Time + @kek_version : Int32 + @creds_total : Int32 + @due_now : Int32 + @overdue : Int32 + + def initialize(@kek_version : Int32 = 0) + @recent = [] of EventRow + @active = {} of UUID => RotationRow + @completed_24h = 0 + @creds_total = 0 + @due_now = 0 + @overdue = 0 + @started_at = Time.utc + end + + def update_counts(creds_total : Int32, due_now : Int32, overdue : Int32) : Nil + @creds_total = creds_total + @due_now = due_now + @overdue = overdue + end + + def apply(ev : Events::Event) : Nil + case ev + when Events::RotationStarted + @active[ev.credential_id] = RotationRow.new( + credential_id: ev.credential_id, + rotator_kind: ev.rotator_kind, + step: "starting", + progress: 0, + ) + when Events::RotationStepStarted + if row = @active[ev.credential_id]? + @active[ev.credential_id] = RotationRow.new( + credential_id: row.credential_id, + rotator_kind: row.rotator_kind, + step: ev.step.to_s, + progress: row.progress, + ) + end + when Events::RotationStepCompleted + if row = @active[ev.credential_id]? + @active[ev.credential_id] = RotationRow.new( + credential_id: row.credential_id, + rotator_kind: row.rotator_kind, + step: ev.step.to_s, + progress: row.progress + 1, + ) + end + when Events::RotationCompleted + @active.delete(ev.credential_id) + @completed_24h += 1 + push_event("✓", "rotation completed for #{short(ev.credential_id)}") + when Events::RotationFailed + @active.delete(ev.credential_id) + push_event("!", "rotation FAILED for #{short(ev.credential_id)}: #{ev.reason}") + when Events::PolicyViolation + push_event("⚠", "policy '#{ev.policy_name}' violated by #{short(ev.credential_id)}") + when Events::DriftDetected + push_event("⚠", "drift detected on #{short(ev.credential_id)}") + when Events::AlertRaised + sym = case ev.severity + in Events::Severity::Critical then "!" + in Events::Severity::Warn then "⚠" + in Events::Severity::Info then "ℹ" + end + push_event(sym, ev.message) + end + end + + getter recent : Array(EventRow) + getter active : Hash(UUID, RotationRow) + getter completed_24h : Int32 + getter started_at : Time + getter kek_version : Int32 + getter creds_total : Int32 + getter due_now : Int32 + getter overdue : Int32 + + def uptime : Time::Span + Time.utc - @started_at + end + + private def push_event(symbol : String, summary : String) : Nil + @recent << EventRow.new(occurred_at: Time.utc, symbol: symbol, summary: summary) + @recent.shift if @recent.size > MAX_RECENT_EVENTS + end + + private def short(uuid : UUID) : String + uuid.to_s[0, 8] + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/tui.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/tui.cr new file mode 100644 index 00000000..f96348f2 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/tui/tui.cr @@ -0,0 +1,95 @@ +# =================== +# ©AngelaMos | 2026 +# tui.cr +# =================== + +require "./ansi" +require "./state" +require "./renderer" +require "./snapshotter" +require "../engine/event_bus" + +module CRE::Tui + # Tui glues State + Renderer to the event bus. A single fiber consumes events + # (Drop overflow - stale UI is acceptable) and triggers a repaint at most + # every refresh_interval to coalesce bursts. + class Tui + @running : Bool + @ch : ::Channel(Events::Event)? + @last_render : Time + + def initialize( + @bus : Engine::EventBus, + @state : State = State.new, + @io : IO = STDOUT, + @refresh_interval : Time::Span = 200.milliseconds, + @use_color : Bool = true, + ) + @running = false + @last_render = Time::UNIX_EPOCH + end + + def start : Nil + @running = true + ch = @bus.subscribe(buffer: 64, overflow: Engine::EventBus::Overflow::Drop) + @ch = ch + enter_alt_screen if @io == STDOUT + + spawn(name: "tui-events") do + while @running + begin + ev = ch.receive + rescue ::Channel::ClosedError + break + end + @state.apply(ev) + maybe_render + end + end + + spawn(name: "tui-tick") do + while @running + sleep @refresh_interval + maybe_render + end + end + + maybe_render(force: true) + end + + def stop : Nil + @running = false + @ch.try(&.close) + leave_alt_screen if @io == STDOUT + end + + def state : State + @state + end + + def force_render : Nil + Renderer.new(@state, @io, @use_color).render + @last_render = Time.utc + end + + private def maybe_render(force : Bool = false) : Nil + now = Time.utc + return if !force && (now - @last_render) < @refresh_interval + Renderer.new(@state, @io, @use_color).render + @last_render = now + end + + private def enter_alt_screen : Nil + @io << "\e[?1049h" + @io << Ansi::HIDE_CURSOR + @io << Ansi::CLEAR_SCREEN + @io.flush + end + + private def leave_alt_screen : Nil + @io << Ansi::SHOW_CURSOR + @io << "\e[?1049l" + @io.flush + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/vault/.gitkeep b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/vault/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/vault/client.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/vault/client.cr new file mode 100644 index 00000000..c722efc3 --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/vault/client.cr @@ -0,0 +1,74 @@ +# =================== +# ©AngelaMos | 2026 +# client.cr +# =================== + +require "http/client" +require "json" +require "../http/retry" + +module CRE::Vault + class VaultError < Exception + getter status : Int32 + + def initialize(message : String, @status : Int32) + super(message) + end + end + + class Client + record DynamicSecret, + lease_id : String, + lease_duration : Int32, + username : String, + password : String + + def initialize(@addr : String, @token : String) + end + + def read_dynamic(role_path : String) : DynamicSecret + json = http_get("/v1/#{role_path}") + data = json["data"] + lease_id = json["lease_id"].as_s + lease_duration = json["lease_duration"].as_i + DynamicSecret.new( + lease_id: lease_id, + lease_duration: lease_duration, + username: data["username"].as_s, + password: data["password"].as_s, + ) + end + + def revoke_lease(lease_id : String) : Nil + http_put("/v1/sys/leases/revoke", {"lease_id" => lease_id}.to_json) + end + + def renew_lease(lease_id : String, increment : Int32 = 0) : Int32 + payload = increment > 0 ? {"lease_id" => lease_id, "increment" => increment} : {"lease_id" => lease_id} + json = http_put("/v1/sys/leases/renew", payload.to_json) + json["lease_duration"].as_i + end + + def health : Hash(String, JSON::Any) + json = http_get("/v1/sys/health") + json.as_h + end + + private def http_get(path : String) : JSON::Any + headers = HTTP::Headers{"X-Vault-Token" => @token} + response = CRE::Http.request("GET", @addr + path, headers, label: "vault.GET#{path}") + raise VaultError.new("vault GET #{path}: #{response.body[0, 200]?}", response.status_code) unless response.status_code < 300 + JSON.parse(response.body) + end + + private def http_put(path : String, body : String) : JSON::Any + headers = HTTP::Headers{ + "X-Vault-Token" => @token, + "Content-Type" => "application/json", + } + response = CRE::Http.request("PUT", @addr + path, headers, body, label: "vault.PUT#{path}") + raise VaultError.new("vault PUT #{path}: #{response.body[0, 200]?}", response.status_code) unless response.status_code < 300 + response.body.empty? ? JSON::Any.new(Hash(String, JSON::Any).new) : JSON.parse(response.body) + end + end +end diff --git a/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/version.cr b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/version.cr new file mode 100644 index 00000000..40aae0cd --- /dev/null +++ b/PROJECTS/intermediate/credential-rotation-enforcer/src/cre/version.cr @@ -0,0 +1,8 @@ +# =================== +# ©AngelaMos | 2026 +# version.cr +# =================== + +module CRE + VERSION = "0.1.0" +end