Merge pull request #203 from CarterPerez-dev/chore/credential-rotation-enforcer-finish
Chore/credential rotation enforcer finish
This commit is contained in:
commit
b826b6caed
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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/
|
||||
|
|
@ -0,0 +1,603 @@
|
|||
<!--
|
||||
©AngelaMos | 2026
|
||||
CONFIGURATION.md
|
||||
-->
|
||||
|
||||
# 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 <<SQL
|
||||
CREATE USER cre WITH PASSWORD 'change-me-strong';
|
||||
CREATE DATABASE cre_prod OWNER cre;
|
||||
\c cre_prod
|
||||
GRANT ALL PRIVILEGES ON SCHEMA public TO cre;
|
||||
SQL
|
||||
```
|
||||
|
||||
### Set DATABASE_URL
|
||||
|
||||
```bash
|
||||
export DATABASE_URL="postgres://cre:change-me-strong@db.internal:5432/cre_prod"
|
||||
```
|
||||
|
||||
### Migrations
|
||||
|
||||
`cre run` calls `persist.migrate!` automatically on first boot, which creates all tables, indexes, append-only triggers, and grants. No manual migration step needed.
|
||||
|
||||
### Hardening (optional but recommended)
|
||||
|
||||
After first migrate, demote the app role to INSERT-only on the audit table:
|
||||
|
||||
```sql
|
||||
REVOKE ALL ON audit_events FROM cre;
|
||||
GRANT INSERT, SELECT ON audit_events TO cre;
|
||||
GRANT USAGE, SELECT ON SEQUENCE audit_events_seq_seq TO cre;
|
||||
```
|
||||
|
||||
This means even an SQL-injection attacker with the app's connection string can't `UPDATE` or `DELETE` audit rows — they get a permission-denied error in addition to the trigger refusing.
|
||||
|
||||
---
|
||||
|
||||
## 3. Generate the cryptographic keys
|
||||
|
||||
Two distinct keys, both 32 random bytes (64 hex chars):
|
||||
|
||||
```bash
|
||||
openssl rand -hex 32 # use for CRE_KEK_HEX
|
||||
openssl rand -hex 32 # use for CRE_HMAC_KEY_HEX
|
||||
```
|
||||
|
||||
| Variable | What it does | Loss impact |
|
||||
|---|---|---|
|
||||
| `CRE_KEK_HEX` | Wraps every per-row DEK that encrypts a credential ciphertext | **All credentials become unreadable**. KEK is the master crypto root. |
|
||||
| `CRE_HMAC_KEY_HEX` | Initial HMAC key for the audit-log ratchet | Audit log can't be HMAC-verified after this point; hash chain still works. Old logs (signed under earlier ratchet generations) remain verifiable independently. |
|
||||
|
||||
### Where to store these
|
||||
|
||||
- **Tier 1 / dev:** plain env vars in your shell or `.envrc` (gitignored)
|
||||
- **Production:** AWS KMS, HashiCorp Vault transit engine, or your secrets manager. Inject at process boot via systemd `LoadCredentialEncrypted=` or similar.
|
||||
- **Never:** in Git, even in private repos. Even in `.env` files committed by accident.
|
||||
|
||||
> 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<TOKEN>/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 <credential-id>` | viewer | Last 10 audit events for one credential |
|
||||
| `/alerts` | viewer | Pointer to `cre audit verify` |
|
||||
| `/help` | viewer | Command list |
|
||||
| `/rotate <credential-id>` | operator | Manually trigger rotation |
|
||||
| `/snooze <credential-id> 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` |
|
||||
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
|
@ -0,0 +1,171 @@
|
|||
<!--
|
||||
©AngelaMos | 2026
|
||||
README.md
|
||||
-->
|
||||
|
||||
```regex
|
||||
██████╗██████╗ ███████╗
|
||||
██╔════╝██╔══██╗██╔════╝
|
||||
██║ ██████╔╝█████╗
|
||||
██║ ██╔══██╗██╔══╝
|
||||
╚██████╗██║ ██║███████╗
|
||||
╚═════╝╚═╝ ╚═╝╚══════╝
|
||||
```
|
||||
|
||||
[](https://github.com/CarterPerez-dev/Cybersecurity-Projects/tree/main/PROJECTS/intermediate/credential-rotation-enforcer)
|
||||
[](https://crystal-lang.org)
|
||||
[](https://www.gnu.org/licenses/agpl-3.0)
|
||||
[](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 <credential-id> # 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.<region>.amazonaws.com` | SigV4 (rolled from scratch in `src/cre/aws/signer.cr`) |
|
||||
| HashiCorp Vault | `vault read database/creds/<role>` + 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
|
||||
|
|
@ -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
|
||||
|
|
@ -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"]
|
||||
|
|
@ -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/<int:pat_id>", 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)
|
||||
|
|
@ -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
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
<!--
|
||||
©AngelaMos | 2026
|
||||
00-OVERVIEW.md
|
||||
-->
|
||||
|
||||
# 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 <repo> && 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 <id>` | 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 <name>` | 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 <zip>` | 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)
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
<!--
|
||||
©AngelaMos | 2026
|
||||
01-CONCEPTS.md
|
||||
-->
|
||||
|
||||
# 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 <id>` 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)
|
||||
|
|
@ -0,0 +1,178 @@
|
|||
<!--
|
||||
©AngelaMos | 2026
|
||||
02-ARCHITECTURE.md
|
||||
-->
|
||||
|
||||
# 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`.
|
||||
|
|
@ -0,0 +1,158 @@
|
|||
<!--
|
||||
©AngelaMos | 2026
|
||||
03-IMPLEMENTATION.md
|
||||
-->
|
||||
|
||||
# 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 '<name>'")` 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=<id>|kind=<k>`),
|
||||
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<version>`). 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 <id>` 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.
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
<!--
|
||||
©AngelaMos | 2026
|
||||
04-CHALLENGES.md
|
||||
-->
|
||||
|
||||
# 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=<id>|kind=<k>|tenant=<t>`; 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/<area>/` 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)
|
||||
|
|
@ -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."
|
||||
|
|
@ -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
|
||||
|
|
@ -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 <carterperez2222@gmail.com>
|
||||
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
|
||||
0
PROJECTS/intermediate/credential-rotation-enforcer/spec/fixtures/policies/.gitkeep
vendored
Normal file
0
PROJECTS/intermediate/credential-rotation-enforcer/spec/fixtures/policies/.gitkeep
vendored
Normal file
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
# ===================
|
||||
# ©AngelaMos | 2026
|
||||
# spec_helper.cr
|
||||
# ===================
|
||||
|
||||
require "spec"
|
||||
require "../src/cre"
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue