Best Practices, Audit & Compliance
Production hardening guidance, the at-rest encryption scheme, the tamper-evident audit trail, and framework mappings for teams under SOC 2 / HIPAA / PCI / GDPR obligations.
Encryption at Rest (EncryptionService)
| Parameter | Value |
|---|---|
| Cipher | AES-256-GCM (authenticated encryption, confidentiality + integrity) |
| Key derivation | PBKDF2(ENCRYPTION_KEY, random 32-byte salt, 100,000 iterations, SHA-512) |
| Wire format | enc: + base64(salt[32] ‖ iv[16] ‖ tag[16] ‖ ciphertext) |
| Applied to | Connection passwords, MFA seeds, sensitive settings (batched via encryptJsonFields()) |
Per-record salt means every ciphertext derives an independent subkey, a single leaked derived key does not generalize. The GCM tag authenticates each record; tampering fails decryption rather than yielding garbage plaintext. The prefix makes encrypted values self-identifying, enabling transparent migration and mixed-state reads. Fail-loud invariant: with ENCRYPTION_KEY unset the service silently degrades to plaintext with only a warning, CI aside, an unset key in any real environment is a critical misconfiguration.
Audit Middleware & Redaction
auditMiddleware is mounted globally and records every state-changing verb (POST/PUT/PATCH/DELETE) plus login, approval, and execution events; read-only queries are not logged. Entity IDs are derived from the URL path UUID or the response body. Sensitive fields, password, token, secret, apiKey, mfaToken, and peers, are redacted before the record is written, so before/after diffs never persist live secrets.
{
"id": 12345,
"timestamp": "2025-01-15T14:30:00.000Z",
"userEmail": "developer@company.com",
"action": "script.execute",
"entityType": "script",
"entityId": 42,
"oldValues": { ... },
"newValues": { ... },
"ipAddress": "192.168.1.100",
"success": true
}
Immutable, Tamper-Evident Audit Trail
The trail is append-only and cryptographically sealed by the database. On insert, a trigger assigns a monotonic sequence number, links the row to the hash of its predecessor, and stores a SHA-256 over the record contents concatenated with that prior hash. Each hash therefore depends on the entire prefix of the chain: any modification, deletion, reorder, or back-dated insertion of a historical record invalidates every subsequent hash and is detectable.
- Append-only enforcement: triggers reject
UPDATEandDELETEon the audit table outright. The application cannot mutate a sealed record; the only sanctioned deletion is the controlled retention purge. - Sealing occurs in the database, not the application layer, a compromised or malicious app process cannot forge, reorder, or backdate the chain.
- Verification:
GET /api/db-devops/audit/integrity(Enterprise) walks the whole chain and returns{ valid, brokenSeq, total }.valid: falseplusbrokenSeqpinpoints the first record whose hash no longer reconciles, including tampering performed by a database superuser editing the table directly.
Honest caveat: stock PostgreSQL cannot make a table physically unwritable to a superuser. This design does not claim to prevent superuser writes; it makes any such write cryptographically detectable and blocks every ordinary mutation path. Where hardware-enforced immutability is mandated, target a ledger-backed or WORM store (append-only object storage, or a managed ledger database) behind the same interface.
Retention
Records live in the DevOps Postgres database; retention is the only sanctioned removal path.
- Default 90 days, configurable in Settings → Audit.
- Purge mechanism: a privileged, itself-audited database function removes only the oldest records, the tail of the chain, so the surviving chain stays internally verifiable end-to-end. Ad-hoc
DELETEis refused by the append-only triggers. - Archival: export the tail to S3 / Azure Blob / a log platform before purge for long-horizon retention (compliance windows commonly ≥1 year).
Production Hardening
Network
- TLS 1.2+ at the edge; TLS 1.0/1.1 disabled; trusted-CA certs; HSTS via Helmet.
- App and datastore in private subnets; egress via NAT only for the repo integrations that need it (GitHub, GitLab, Dropbox, S3).
- Security groups: inbound 80/443 to the edge only; app→Postgres on 5432; deny-all otherwise.
- Prefer VPN / private-link for internal-only deployments to remove public exposure entirely.
Secrets
| Secret | Store | Rotation |
|---|---|---|
JWT_SECRET | Secrets Manager / Key Vault / K8s Secret | Annually or on suspicion |
ENCRYPTION_KEY | Same | Requires re-encryption tooling; treat rotation as a migration, not a swap |
| DevOps DB password | Same | Quarterly |
| Repo/cloud tokens | Encrypted in-DB (automatic) | Per provider policy |
Never place secrets in source, committed .env, image layers, or logs. Note that keys/license-private.pem is currently committed to the repo, a tracked debt item; inject it from a secrets manager for real signing.
Container & Datastore
- Non-root runtime user; minimal (Alpine) base; scan and block critical/high CVEs; pin immutable tags;
readOnlyRootFilesystemwith writable mounts scoped to/tmpand logs. - Dedicated least-privilege Postgres role (DML +
CREATE TABLEfor migrations; no SUPERUSER/CREATEDB/CREATEROLE);sslmode=require|verify-full; storage encryption on; aCONNECTION LIMITto bound pool exhaustion.
Compliance Framework Mapping
SOC 2 (Type II)
| Criterion | Supporting control |
|---|---|
| CC6.1, Logical access | JWT authn, 5-role RBAC, license-tier gating, optional TOTP MFA |
| CC6.2, Provisioning | Admin-managed user creation and role assignment; SSO provisioning (Enterprise) |
| CC6.3, Access removal | Deactivation blocks new logins; JWT_SECRET rotation forces global revocation. Per-token revocation is eventual, bounded by the 8h lifetime. |
| CC7.1, Monitoring | Health endpoints, structured Pino logging, sealed audit chain |
| CC7.2, Anomaly detection | Rate limiting, failed-login capture, SecurityAlertService |
| CC8.1, Change management | Approval workflows, script versioning, immutable execution records |
HIPAA (164.312)
| Safeguard | Supporting control |
|---|---|
| (a) Access control | Unique identities, RBAC, 8h token expiry, MFA |
| (b) Audit controls | Tamper-evident hash-chained trail with cryptographic integrity verification |
| (c) Integrity | Two-person approval gate; GCM-authenticated at-rest storage |
| (e) Transmission security | TLS in transit end-to-end |
PCI DSS
| Requirement | Supporting control |
|---|---|
| Req 2, No defaults | Fail-loud on unset JWT_SECRET/ENCRYPTION_KEY; no shipped credentials |
| Req 7, Restrict access | Least-privilege RBAC |
| Req 8, Identify users | Unique accounts, bcrypt(12) + JWT + MFA |
| Req 10, Track access | Sealed, integrity-verifiable audit chain with redaction |
| Req 11, Test security | Rate limiting, CORS allowlist, health probes |
GDPR
| Principle | Supporting control |
|---|---|
| Data minimization | Local accounts store only email, name, role |
| Accountability | Full who/what/when audit trail |
| Right to erasure | Admin deactivation/deletion of accounts |
| Protection by design | bcrypt hashing, AES-256-GCM at rest, TLS in transit |
Scope note: these controls support compliance; they do not constitute it. Certification depends on your full stack, organizational policy, physical and vendor controls, and evidence collection beyond this application. Engage your auditor for an authoritative assessment.