Task Assignment: Move Audit Logging to Backend
Memory Bank Protocol
IMPORTANT: Before implementing, read and understand:
- Current frontend audit implementation in
src/providers/dataProvider/resource-callbacks/
- Backend extension patterns in
_extensions/api.js and _devExtensions/api.js
- Soul-cli REST API structure and middleware capabilities
- Existing audit table schema and TypeScript types
Key Context:
- Soul-cli v0.7.8 serves SQLite via REST at
/api/tables/*
- JWT tokens used for authentication (no explicit middleware shown, may be in soul-cli)
- Audit table already exists with all required fields
- Frontend currently uses lifecycle callbacks via React-Admin's
withLifecycleCallbacks
Current State Analysis
Frontend Audit Implementation
- Location:
src/providers/dataProvider/index.ts orchestrates lifecycle callbacks
- Pattern: Each resource has lifecycle callbacks in
src/providers/dataProvider/resource-callbacks/
- Audit Function:
trackEvent() in src/utils/audit.ts creates audit entries
- Coverage: All CREATE, UPDATE, DELETE operations via React-Admin UI
- Gap: Direct API calls bypass these lifecycle callbacks entirely
Backend Structure
- Extensions: Custom Express routes added via
_extensions/api.js (production) and _devExtensions/api.js (dev)
- Auth Handling: Login controller validates users, but JWT middleware not explicitly visible
- Database: SQLite with audit table containing: id, user, resource, dataId, activityType, dateTime, label, activityDetail, securityRelated, subjectId, subjectResource, ip
Requirements
Functional Requirements
Non-Functional Requirements
Technical Approach
Phase 1: Implement Backend Audit Middleware
Phase 2: Integrate Middleware with Soul-CLI
Phase 3: Testing Implementation
Phase 4: Parallel Run Verification
Phase 5: Frontend Cleanup
Phase 6: Documentation
Testing Requirements
Test Coverage Checklist
Test Scenarios
- Happy Path: Normal CRUD operations generate correct audit entries
- Bulk Operations: UpdateMany and DeleteMany create appropriate audit trails
- Failed Operations: Failed requests don't create audit entries
- Missing Auth: Requests without valid JWT are still audited (as failed auth attempts)
- Direct API: Bypass frontend completely, verify audit trail exists
Migration Strategy
Rollout Plan
- Week 1: Deploy middleware to development environment
- Week 2: Run parallel audit (both frontend and backend) in dev
- Week 3: Deploy to staging/test with parallel run
- Week 4: Production deployment with parallel run
- Week 5: Verify audit completeness, remove frontend audit code
- Week 6: Final production deployment without frontend audit
Rollback Plan
- Frontend audit code remains until fully verified
- Middleware can be disabled via environment variable flag
- If issues found, disable middleware and continue with frontend audit
Success Criteria
Questions to Resolve
-
JWT Structure: How does soul-cli handle JWT tokens? Need to investigate token payload structure to extract user ID correctly.
-
Soul-CLI Middleware: How does soul-cli v0.7.8 handle Express middleware? Does it expose the Express app instance for middleware registration?
-
Transaction Handling: Should audit entries be part of same transaction as data modifications? Currently seems independent.
-
Audit Entry IDs: For newly created records, response contains lastInsertRowid - need to ensure this is captured for audit.
-
Performance Impact: Should audit writes be asynchronous to minimize latency? Consider using setImmediate or process.nextTick.
-
Field-Level Changes: Current frontend tracks some field-level changes. Should backend middleware also capture before/after values?
Implementation Notes
Key Files to Modify
_extensions/api.js - Add audit middleware registration
_devExtensions/api.js - Add audit middleware for development
_extensions/auditMiddleware.js - New file with core middleware logic
src/providers/dataProvider/resource-callbacks/*.ts - Remove audit calls (Phase 5)
src/providers/dataProvider/index.ts - Remove audit parameter (Phase 5)
Activity Type Mapping
Current frontend uses these activity types (from src/utils/activity-types):
- LOGIN = 0
- CREATE = 1
- UPDATE = 2
- DELETE = 3
- LOAN = 4
- RETURN = 5
- DISPATCH = 6
- ADD_ITEM_TO_BATCH = 7
- ADD_ITEM_TO_DESTRUCTION = 8
- FINALISE_BATCH = 9
- FINALISE_DESTRUCTION = 10
- HASTENER_SENT = 11
- ADD_ITEM_TO_DISPATCH = 12
Backend middleware should use same numeric values for consistency.
IP Address Extraction
// Priority order for IP extraction:
const getClientIp = (req) => {
return req.headers['x-forwarded-for']?.split(',')[0].trim() ||
req.headers['x-real-ip'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
'unknown';
};
Agent Instructions
Your Role: Backend developer with Express/Node.js and SQLite expertise
Starting Point: Begin with Phase 1 - creating the audit middleware module. Focus on getting basic audit capture working for a single resource type (e.g., items) before expanding to all resources.
Key Constraints:
- Must work with existing soul-cli v0.7.8 REST API structure
- Cannot modify soul-cli core - only add middleware via extensions
- Must maintain backward compatibility during parallel run period
- Audit failures must not break main operations
Deliverables:
- Working audit middleware that captures all write operations
- Comprehensive test suite with >90% coverage
- Documentation of middleware configuration and behavior
- Clean removal of frontend audit code (after verification)
Remember: This is a security-critical change. Ensure no edge cases where audit can be bypassed. Test thoroughly with direct API access, not just through the UI.
Task Assignment: Move Audit Logging to Backend
Memory Bank Protocol
IMPORTANT: Before implementing, read and understand:
src/providers/dataProvider/resource-callbacks/_extensions/api.jsand_devExtensions/api.jsKey Context:
/api/tables/*withLifecycleCallbacksCurrent State Analysis
Frontend Audit Implementation
src/providers/dataProvider/index.tsorchestrates lifecycle callbackssrc/providers/dataProvider/resource-callbacks/trackEvent()insrc/utils/audit.tscreates audit entriesBackend Structure
_extensions/api.js(production) and_devExtensions/api.js(dev)Requirements
Functional Requirements
/api/tables/*endpoints/api/tables/items/rows→ "items")x-forwarded-for)Non-Functional Requirements
Technical Approach
Phase 1: Implement Backend Audit Middleware
Create audit middleware module (
_extensions/auditMiddleware.js):Extract user from JWT token:
Map operations to audit types:
Capture resource details:
Create audit entries:
Phase 2: Integrate Middleware with Soul-CLI
Register middleware in extensions:
_extensions/api.js(production) and_devExtensions/api.js(dev)app.use()Handle soul-cli response interception:
Phase 3: Testing Implementation
Unit tests for middleware (
_extensions/tests/auditMiddleware.test.js):Integration tests per resource:
Direct API testing:
Phase 4: Parallel Run Verification
Deploy with both audit systems active:
Comparison testing checklist:
Phase 5: Frontend Cleanup
Remove frontend audit code:
trackEventcalls from all lifecycle callbackslifecycleCallbacksfunction signatureUpdate type definitions:
Phase 6: Documentation
Update technical documentation:
Security documentation:
Testing Requirements
Test Coverage Checklist
Test Scenarios
Migration Strategy
Rollout Plan
Rollback Plan
Success Criteria
Questions to Resolve
JWT Structure: How does soul-cli handle JWT tokens? Need to investigate token payload structure to extract user ID correctly.
Soul-CLI Middleware: How does soul-cli v0.7.8 handle Express middleware? Does it expose the Express app instance for middleware registration?
Transaction Handling: Should audit entries be part of same transaction as data modifications? Currently seems independent.
Audit Entry IDs: For newly created records, response contains
lastInsertRowid- need to ensure this is captured for audit.Performance Impact: Should audit writes be asynchronous to minimize latency? Consider using setImmediate or process.nextTick.
Field-Level Changes: Current frontend tracks some field-level changes. Should backend middleware also capture before/after values?
Implementation Notes
Key Files to Modify
_extensions/api.js- Add audit middleware registration_devExtensions/api.js- Add audit middleware for development_extensions/auditMiddleware.js- New file with core middleware logicsrc/providers/dataProvider/resource-callbacks/*.ts- Remove audit calls (Phase 5)src/providers/dataProvider/index.ts- Remove audit parameter (Phase 5)Activity Type Mapping
Current frontend uses these activity types (from
src/utils/activity-types):Backend middleware should use same numeric values for consistency.
IP Address Extraction
Agent Instructions
Your Role: Backend developer with Express/Node.js and SQLite expertise
Starting Point: Begin with Phase 1 - creating the audit middleware module. Focus on getting basic audit capture working for a single resource type (e.g., items) before expanding to all resources.
Key Constraints:
Deliverables:
Remember: This is a security-critical change. Ensure no edge cases where audit can be bypassed. Test thoroughly with direct API access, not just through the UI.