Skip to content

[M2.1b] Envelope encryption, domain events and audit log - #28

Merged
samuelmbabhazi merged 6 commits into
mainfrom
feat/m2.1b-crypto-events-audit
Nov 3, 2026
Merged

samuelmbabhazi merged 6 commits into
mainfrom
feat/m2.1b-crypto-events-audit

Conversation

@samuelmbabhazi

Copy link
Copy Markdown
Collaborator

Task

[M2.1b] Shared foundations of the control plane (second half of M2.1). Closes #20

What changed

Domain (packages/domain)

  • DomainEvent with type (<aggregate>.<verb>), occurredAt, optional organizationId, actor (user, api_token, system, node with id and ip) and target; createEvent() validates the type name and target.

Envelope encryption (apps/api/src/platform/crypto, SPEC section 9)

  • Primitives: AES-256-GCM, random 12-byte nonce, 16-byte tag, versioned blob 0x01 | nonce | tag | ciphertext, associated data on every message. wrapDataKey / unwrapDataKey bind a DEK to its scope and KEK version.
  • loadKek(path): 32 raw bytes or base64, refuses files readable by group or others, missing files and non-files. The key is a Secret.
  • EnvelopeService.encryptFor(scope, purpose, bytes) / decryptFor: one DEK per scope, generated on first use, wrapped by the KEK and stored in data_encryption_keys (unique scope; a concurrent insert is read back instead of failing). Unwrapped DEKs are cached in memory as Secrets. A stored key with another KEK version is refused with a message pointing to rotation.

Domain events and audit (platform/events, modules/audit)

  • DomainEventBus: in-process, ordered delivery, subscriber errors propagate to the publisher so a failed audit write fails the command (CLAUDE.md rule 6).
  • audit module laid out per CLAUDE.md: domain/audit-record.ts (pure mapping event to record), application/ (AuditEventStore port with append only, AuditRecorder subscribed for the app lifetime, UUIDv7 ids), infrastructure/PrismaAuditEventStore. No update or delete path exists.

Database

  • Prisma models AuditEvent (audit_events, indexes on organization + time and on target) and DataEncryptionKey (data_encryption_keys), initial migration 20261103123622_init. pnpm dev now runs prisma migrate deploy and creates the development KEK (tools/dev/ensure-kek.mjs, gitignored path, mode 0400).

Tests

  • Unit: primitives (round trip, flipped bits in version, nonce, tag and ciphertext, truncation, wrong key, wrong AAD, error messages free of plaintext and key), KEK loader (raw, base64, permissions, sizes, missing), EnvelopeService (one DEK per scope, scope and purpose binding, foreign KEK, concurrent insert), bus (ordering, propagation, unsubscribe), audit mapping and recorder (UUIDv7, ordering, store failure).
  • Integration (Testcontainers or CI PostgreSQL): migrations applied through plain SQL with pg (no process spawning), readiness probe, two published events become two audit rows with the expected tenant, actor and metadata, a value encrypted through the service round-trips and the stored key row contains neither the plaintext nor the unwrapped key.
  • Unit tests now always override DATABASE_URL and the KEK path (Nx loads the developer .env into process.env), so they never touch the development database or key.

Why

Every later module needs secrets at rest (M3.7, identity secrets in M2.2) and emits audit events from its first command. Putting both in place now means no module ships without them.

How it was tested

  • pnpm nx run-many -t lint typecheck test build: all 7 projects green (api: 9 test files).
  • pnpm test:integration with a clean environment: 3 tests against PostgreSQL 17.
  • pnpm gen twice: no drift. Semgrep custom rules: no findings. prettier --check: clean.

Security considerations

  • KEK: refused unless file mode excludes group and others; never logged (Secret). The development KEK lives under the gitignored deploy/dev/secrets/.
  • Ciphertexts carry associated data shipkeep:data:<scope>:<purpose>, so a blob copied to another environment or column fails to decrypt. GCM failures are reported uniformly to avoid oracle behaviour.
  • DEKs are never stored unwrapped and never leave EnvelopeService.
  • Audit: append-only in code; database-level REVOKE UPDATE, DELETE is task M2.4 as planned.
  • DataEncryptionKey table added to SPEC section 4 as the persistence of the DEKs the spec already required; no change to the agent action list or to invariants of existing entities.

Checklist

  • Acceptance criteria from docs/PLAN.md are met and M2.1b (and M2.1) are ticked
  • Lint, TS tests, Go tests and buf lint pass
  • Tests added, including tamper, wrong-key and permission tests
  • No new shell invocation and no new secret exposure path
  • Audit events: the audit path itself is delivered and tested end to end
  • SPEC and CLAUDE.md updated

@samuelmbabhazi
samuelmbabhazi merged commit bbf0f88 into main Nov 3, 2026
10 checks passed
@samuelmbabhazi
samuelmbabhazi deleted the feat/m2.1b-crypto-events-audit branch November 3, 2026 12:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[M2.1] API skeleton

1 participant