strapi-plugin-enterprise-audit
v1.0.1
Published
Enterprise-grade audit logging platform for Strapi v4 and v5 with PBAC, tamper-resistant integrity chains, before/after change tracking, PII protection, configurable retention, and SIEM-ready architecture.
Maintainers
Readme
strapi-plugin-enterprise-audit
Enterprise-grade audit logging platform for Strapi v4 and v5 with PBAC (Policy-Based Access Control), tamper-resistant integrity chains, before/after change tracking, PII protection, configurable retention, and SIEM-ready architecture.
Features
- CRUD Auditing — Automatic create/update/delete tracking for configurable content types with before/after change diffs
- Authentication Auditing — Login, logout, password changes, account events, API token lifecycle
- Authorization Auditing — Role/permission CRUD, user-role assignments, privilege changes
- PBAC Engine — Policy-Based Access Control with subjects, resources, actions, conditions (time, IP/CIDR, attributes)
- Before/After Change Tracking — Structured field-level diffs for every update operation
- PII Protection — Configurable masking (redact, mask, hash, exclude) for sensitive fields
- Tamper Resistance — SHA-256 hash chaining with integrity verification
- Configurable Retention — Per-event-type retention policies with automatic cleanup
- Legal Hold — Preservation flags to prevent retention deletion
- Admin Panel UI — Dashboard, event browser, policy editor, retention management, settings viewer
- REST API — Full query API with pagination, filtering, export (JSON/CSV)
- Observability — Internal metrics, health checks, structured logging
- Strapi v4/v5 Support — Compatibility layer for both major versions
- RBAC Permissions — 15 granular permissions across 6 subcategories
Compliance Support
Provides technical controls that support organizational compliance with:
| Framework | Controls Provided | |-----------|------------------| | SOC 2 | Audit trails, RBAC, tamper protection, change tracking | | ISO 27001 | A.8.15 logging, A.8.16 monitoring, access control | | PCI DSS 4.0 | Req 10 logging, integrity verification, automated retention | | SOX | Financial audit trails, segregation of duties support | | HIPAA | User attribution, ePHI access tracking, retention | | GDPR | PII masking, data minimization, purpose-based retention |
Note: This plugin provides technical capabilities. It does not by itself make an organization compliant with any regulation. Organizations must configure the plugin according to their specific legal, regulatory, and business requirements.
Installation
npm install strapi-plugin-enterprise-auditOr as a local plugin, copy to src/plugins/enterprise-audit/.
Configuration
Plugin Configuration (config/plugins.js)
module.exports = {
'enterprise-audit': {
enabled: true,
config: {
// Operating mode: 'STRICT' fails business ops on audit failure,
// 'BEST_EFFORT' logs and continues
auditMode: 'BEST_EFFORT',
// Enable async event processing (requires queue provider)
async: false,
// Capture read operations (high volume — disabled by default)
captureReads: false,
// Capture API request bodies (disabled by default for privacy)
captureRequestBody: false,
// Maximum audit event payload size in bytes
maxPayloadSize: 65536,
// Truncate payloads exceeding maxPayloadSize
truncate: true,
// Integrity hash algorithm
hashAlgorithm: 'sha256',
// Enable integrity hash chaining
integrityEnabled: true,
// Retention
retentionEnabled: true,
retentionDays: 365,
retentionPolicies: {
security: { days: 730 },
authentication: { days: 365 },
business: { days: 2555 },
debug: { days: 90 },
},
// Archive (extensible — providers are interfaces)
archiveEnabled: false,
// Sensitive field protection
sensitiveFields: [
'password', 'passwordHash', 'token', 'accessToken',
'refreshToken', 'apiKey', 'secret', 'secretKey',
'privateKey', 'creditCard', 'ssn', 'encryptionKey',
],
maskingStrategy: 'redact', // 'redact' | 'mask' | 'hash' | 'exclude'
// Content type auditing configuration
contentTypes: {
// Example: audit all operations on invoices
'api::invoice.invoice': {
create: true,
read: false,
update: true,
delete: true,
},
// Example: audit only writes on users
'plugin::users-permissions.user': {
create: true,
read: false,
update: true,
delete: true,
},
},
// Fields to never include in audit records
excludedFields: ['createdBy', 'updatedBy', 'createdAt', 'updatedAt'],
// PBAC (Policy-Based Access Control)
pbac: {
enabled: true,
cacheTimeout: 60000, // Policy cache TTL in ms
},
},
},
};Environment Variables
AUDIT_ENABLED=true
AUDIT_ASYNC=false
AUDIT_RETENTION_ENABLED=true
AUDIT_RETENTION_DAYS=365
AUDIT_CAPTURE_READS=false
AUDIT_CAPTURE_REQUEST_BODY=false
AUDIT_MAX_PAYLOAD_SIZE=65536
AUDIT_INTEGRITY_ENABLED=true
AUDIT_HASH_ALGORITHM=sha256
AUDIT_ARCHIVE_ENABLED=false
AUDIT_LOG_LEVEL=infoPBAC (Policy-Based Access Control)
The plugin implements a practical PBAC engine inspired by the XACML PDP/PEP/PIP/PAP architecture:
Policy Structure
{
"name": "finance-audit-access",
"effect": "ALLOW",
"priority": 10,
"enabled": true,
"subjects": {
"roles": ["finance-manager", "cfo"],
"userIds": [],
"attributes": { "department": "finance" }
},
"resources": {
"types": ["audit-event"],
"modules": ["finance", "invoicing"],
"severities": ["*"]
},
"actions": ["audit.read", "audit.search", "audit.export"],
"conditions": {
"timeRestriction": { "startHour": 6, "endHour": 22 },
"ipRestriction": { "allowedCIDRs": ["10.0.0.0/8"] },
"maxExportRecords": 10000
}
}Combining Algorithm
Uses DENY-OVERRIDES: any matching DENY policy overrides all ALLOW policies.
Supported Conditions
- Time restriction — startHour/endHour (24h)
- IP restriction — CIDR-based allowlists
- Export limits — Maximum records per export
- Custom conditions via the conditions JSON field
API Reference
All endpoints are under /enterprise-audit/ and require appropriate permissions.
Events
| Method | Path | Permission | Description | |--------|------|------------|-------------| | GET | /events | audit.read | List events with filters | | GET | /events/:id | audit.read | Get event detail | | GET | /events/export | audit.export | Export events (JSON/CSV) | | GET | /events/statistics | audit.read | Aggregate statistics |
Integrity
| Method | Path | Permission | Description | |--------|------|------------|-------------| | GET | /integrity | audit.integrity.verify | Integrity status | | POST | /integrity/verify | audit.integrity.verify | Run verification |
Retention
| Method | Path | Permission | Description | |--------|------|------------|-------------| | GET | /retention | audit.retention.view | Retention status | | POST | /retention/execute | audit.retention.manage | Execute cleanup | | GET | /retention/logs | audit.retention.view | Execution history |
Policies (PBAC)
| Method | Path | Permission | Description | |--------|------|------------|-------------| | GET | /policies | audit.policy.read | List policies | | GET | /policies/:id | audit.policy.read | Get policy | | POST | /policies | audit.policy.create | Create policy | | PUT | /policies/:id | audit.policy.update | Update policy | | DELETE | /policies/:id | audit.policy.delete | Delete policy | | POST | /policies/test | audit.policy.test | Test policy | | POST | /policies/evaluate | audit.policy.evaluate | Evaluate access |
System
| Method | Path | Permission | Description | |--------|------|------------|-------------| | GET | /health | audit.read | Health check | | GET | /config | audit.configuration.view | Current config | | GET | /config/content-types | audit.configuration.view | Content type config |
Event Query Filters
| Parameter | Type | Description | |-----------|------|-------------| | actorId | string | Filter by actor ID | | eventType | string | AUTHENTICATION, AUTHORIZATION, DATA_CHANGE, etc. | | action | string | CREATE, UPDATE, DELETE, LOGIN, etc. | | severity | string | INFO, NOTICE, WARNING, ERROR, CRITICAL, SECURITY | | source | string | admin-panel, api, webhook, cron, system, etc. | | resourceType | string | Content type UID | | resourceId | string | Resource document ID | | success | boolean | Success/failure filter | | ipAddress | string | IP address filter | | requestId | string | Request correlation | | correlationId | string | Workflow correlation | | sessionId | string | Session correlation | | module | string | Application module | | dateFrom | ISO date | Start of date range | | dateTo | ISO date | End of date range | | search | string | Full-text search | | page | number | Page number (default 1) | | pageSize | number | Page size (default 25, max 100) | | sortBy | string | Sort field | | sortOrder | asc/desc | Sort direction |
Permissions
The plugin registers 15 RBAC permissions across 6 subcategories:
| Subcategory | Permissions | |-------------|------------| | Events | audit.read, audit.search, audit.export | | Integrity | audit.integrity.verify | | Retention | audit.retention.view, audit.retention.manage | | Archive | audit.archive.manage | | Configuration | audit.configuration.view, audit.configuration.manage | | Policies | audit.policy.read, audit.policy.create, audit.policy.update, audit.policy.delete, audit.policy.test, audit.policy.evaluate |
Masking Strategies
| Strategy | Behavior | Example |
|----------|----------|---------|
| redact | Replace with [REDACTED] | secret123 → [REDACTED] |
| mask | Keep first/last chars, mask middle | secret123 → s*******3 |
| hash | Replace with SHA-256 hash | secret123 → ef92b778... |
| exclude | Remove field entirely | secret123 → (field removed) |
Retention Policies
Configure per-event-type retention periods:
retentionPolicies: {
security: { days: 730 }, // 2 years
authentication: { days: 365 }, // 1 year
business: { days: 2555 }, // 7 years (SOX)
debug: { days: 90 }, // 3 months
}The retention cron runs daily at 2 AM. Records under legal hold are never deleted by retention.
Extensibility
The plugin is designed for extension through provider interfaces:
- AuditArchiveProvider — S3, Azure Blob, GCS, custom storage
- AuditQueueProvider — Redis, RabbitMQ, custom queue
- AuditSIEMProvider — Splunk, ELK, custom SIEM
- AuditExporter — Custom export formats
Strapi v4/v5 Compatibility
The plugin includes a compatibility layer (server/utils/strapi-compat.js) that provides a unified API:
- Strapi v5: Uses
strapi.documents()(Document Service API) - Strapi v4: Falls back to
strapi.entityService
Detection is automatic — no configuration needed.
Testing
npm test # Run all tests
npm run test:coverage # Run with coverage reportThe test suite covers:
- strapi-compat — v4/v5 adapter layer (version detection, unified API delegation)
- pbac-engine — IP/CIDR matching, subject/resource/action matching, conditions, deny-overrides combining
- change-tracker — field-level diffing, include/exclude filters, truncation
- pii-filter — sensitive field detection, masking strategies (redact/mask/hash/exclude), deep filtering
- integrity — SHA-256 hash computation, chain verification, tamper detection
- metrics — counter increments, latency recording, p95 computation
- helpers — UUID generation, IP extraction, User-Agent extraction, retention calculations
Project Structure
strapi-plugin-enterprise-audit/
├── admin/ # Admin panel UI
│ └── src/
│ ├── pages/
│ │ ├── Dashboard/ # Audit dashboard
│ │ ├── Events/ # Event browser + detail
│ │ ├── Policies/ # PBAC policy management
│ │ ├── Retention/ # Retention management
│ │ └── Settings/ # Configuration viewer
│ ├── hooks/ # React hooks
│ └── api/ # API client
├── server/ # Server-side plugin
│ ├── config/ # Plugin configuration + validation
│ ├── content-types/ # Database schemas
│ │ ├── audit-event/ # Main audit event table
│ │ ├── audit-policy/ # PBAC policy table
│ │ └── audit-retention-log/ # Retention execution log
│ ├── controllers/admin/ # Admin API controllers
│ ├── routes/ # API routes
│ ├── services/ # Business logic
│ │ ├── audit-engine.js # Core audit engine
│ │ ├── pbac-engine.js # PBAC policy engine
│ │ ├── change-tracker.js # Before/after diff
│ │ ├── pii-filter.js # PII masking
│ │ ├── integrity.js # Hash chain integrity
│ │ ├── retention.js # Retention policies
│ │ ├── exporter.js # JSON/CSV export
│ │ ├── metrics.js # Observability
│ │ └── health.js # Health checks
│ ├── hooks/ # Event capture hooks
│ │ ├── lifecycle-subscriber.js # CRUD auditing
│ │ ├── auth-hooks.js # Auth event capture
│ │ └── authorization-hooks.js # Authz event capture
│ ├── middlewares/ # API activity auditing
│ ├── migrations/ # Database indexes
│ ├── policies/ # Permission enforcement
│ └── utils/ # Shared utilities
│ └── strapi-compat.js # v4/v5 compatibility adapter
└── tests/ # Automated tests
└── unit/ # Unit testsLicense
MIT
