forked from Talenttrust/Talenttrust-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit.ts
More file actions
324 lines (287 loc) · 8.62 KB
/
Copy pathaudit.ts
File metadata and controls
324 lines (287 loc) · 8.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/**
* Compliance Audit Logging Service
*
* Tracks all data retention, archival, and deletion actions for
* compliance auditing, regulatory reporting, and forensic analysis.
*
* @module retention/audit
*/
import { ComplianceAuditLog, RetentionAction, DataEntityType } from "./types";
import * as crypto from "crypto";
import { validateEnv } from "../config/env.schema";
/**
* Compliance audit log entry builder
* @interface AuditLogEntry
*/
export interface AuditLogEntry {
entityId: string;
entityType: DataEntityType;
action: RetentionAction;
actor: string;
details: Record<string, unknown>;
compliance?: string;
notes?: string;
}
/**
* Audit log query filter options
* @interface AuditLogFilter
*/
export interface AuditLogFilter {
entityId?: string;
entityType?: DataEntityType;
action?: RetentionAction;
actor?: string;
compliance?: string;
startDate?: Date;
endDate?: Date;
}
/**
* Compliance audit logging service
*
* Maintains immutable audit logs of all retention-related operations
* for compliance verification and forensic investigation.
*
* @class ComplianceAuditLogger
*/
export class ComplianceAuditLogger {
private auditLogs: Map<string, ComplianceAuditLog> = new Map();
private logQueue: ComplianceAuditLog[] = [];
private logIndex: Map<string, Set<string>> = new Map(); // entityId -> logIds
/**
* Log a retention-related action
*
* Creates an immutable audit trail entry for retention operations,
* useful for compliance verification and regulatory reporting.
*
* @param {AuditLogEntry} entry - Audit log entry details
* @returns {ComplianceAuditLog} Created audit log
*/
logAction(entry: AuditLogEntry): ComplianceAuditLog {
const auditLog: ComplianceAuditLog = {
id: this.generateAuditLogId(),
entityId: entry.entityId,
entityType: entry.entityType,
action: entry.action,
actor: entry.actor,
timestamp: new Date(),
details: entry.details,
compliance: entry.compliance || "GENERAL",
notes: entry.notes,
};
// Generate proof for deletion or if explicitly requested
if (
entry.action === RetentionAction.DELETE ||
entry.action === RetentionAction.ARCHIVE
) {
auditLog.proof = this.generateProof(auditLog);
}
this.auditLogs.set(auditLog.id, auditLog);
this.logQueue.push(auditLog);
this.addToIndex(entry.entityId, auditLog.id);
return auditLog;
}
/**
* Generate a verifiable cryptographic proof for an audit entry
*
* @param {Omit<ComplianceAuditLog, 'id' | 'proof'>} log - Audit log entry
* @returns {string} SHA-256 HMAC signature
* @private
*/
private generateProof(log: any): string {
const payload = JSON.stringify({
entityId: log.entityId,
entityType: log.entityType,
action: log.action,
actor: log.actor,
timestamp: log.timestamp.toISOString(),
details: log.details,
compliance: log.compliance,
});
// Use the validated runtime configuration instead of reading raw env values.
const secret = validateEnv(process.env).COMPLIANCE_AUDIT_SECRET;
return crypto.createHmac("sha256", secret).update(payload).digest("hex");
}
/**
* Verify an audit log entry proof
*
* @param {ComplianceAuditLog} log - Audit log entry to verify
* @returns {boolean}
*/
verifyProof(log: ComplianceAuditLog): boolean {
if (!log.proof) return false;
const expectedProof = this.generateProof(log);
return log.proof === expectedProof;
}
/**
* Retrieve audit logs for a specific data entity
*
* Returns complete audit trail for a data entity, showing all
* operations performed on it.
*
* @param {string} entityId - Entity identifier
* @returns {ComplianceAuditLog[]} All audit logs for entity
*/
getLogsForEntity(entityId: string): ComplianceAuditLog[] {
const logIds = this.logIndex.get(entityId);
if (!logIds) return [];
return Array.from(logIds)
.map((id) => this.auditLogs.get(id))
.filter((log): log is ComplianceAuditLog => log !== undefined)
.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
}
/**
* Query audit logs with filters
*
* Searches audit logs based on multiple criteria for compliance
* reporting and investigation.
*
* @param {AuditLogFilter} filter - Query filters
* @returns {ComplianceAuditLog[]} Matching audit logs
*/
queryLogs(filter: AuditLogFilter): ComplianceAuditLog[] {
let results = Array.from(this.auditLogs.values());
if (filter.entityId) {
results = results.filter((log) => log.entityId === filter.entityId);
}
if (filter.entityType) {
results = results.filter((log) => log.entityType === filter.entityType);
}
if (filter.action) {
results = results.filter((log) => log.action === filter.action);
}
if (filter.actor) {
results = results.filter((log) => log.actor === filter.actor);
}
if (filter.compliance) {
results = results.filter((log) => log.compliance === filter.compliance);
}
if (filter.startDate) {
results = results.filter((log) => log.timestamp >= filter.startDate!);
}
if (filter.endDate) {
results = results.filter((log) => log.timestamp <= filter.endDate!);
}
return results.sort(
(a, b) => a.timestamp.getTime() - b.timestamp.getTime(),
);
}
/**
* Get audit log by ID
*
* @param {string} logId - Audit log identifier
* @returns {ComplianceAuditLog | undefined}
*/
getLogById(logId: string): ComplianceAuditLog | undefined {
return this.auditLogs.get(logId);
}
/**
* Get compliance report for audit trail
*
* Generates a summary report of retention and archival activities
* grouped by compliance standard.
*
* @returns {Record<string, {count: number; actions: Record<string, number>}>} Compliance report
*/
getComplianceReport(): Record<
string,
{ count: number; actions: Record<string, number> }
> {
const report: Record<
string,
{ count: number; actions: Record<string, number> }
> = {};
for (const log of this.auditLogs.values()) {
if (!report[log.compliance]) {
report[log.compliance] = { count: 0, actions: {} };
}
report[log.compliance].count++;
if (!report[log.compliance].actions[log.action]) {
report[log.compliance].actions[log.action] = 0;
}
report[log.compliance].actions[log.action]++;
}
return report;
}
/**
* Get audit trail summary for entity
*
* @param {string} entityId - Entity identifier
* @returns {{entity: string; firstAction: Date; lastAction: Date; actionCount: number; actions: string[]}}
*/
getEntityAuditSummary(entityId: string): {
entity: string;
firstAction: Date;
lastAction: Date;
actionCount: number;
actions: string[];
} {
const logs = this.getLogsForEntity(entityId);
if (logs.length === 0) {
return {
entity: entityId,
firstAction: new Date(),
lastAction: new Date(),
actionCount: 0,
actions: [],
};
}
const actions = Array.from(new Set(logs.map((log) => log.action)));
return {
entity: entityId,
firstAction: logs[0].timestamp,
lastAction: logs[logs.length - 1].timestamp,
actionCount: logs.length,
actions,
};
}
/**
* Export audit logs as JSON for compliance reporting
*
* @param {AuditLogFilter} [filter] - Optional filter criteria
* @returns {ComplianceAuditLog[]} Audit logs as JSON-serializable array
*/
exportLogs(filter?: AuditLogFilter): ComplianceAuditLog[] {
const logs = filter
? this.queryLogs(filter)
: Array.from(this.auditLogs.values());
return logs.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
}
/**
* Clear audit logs (use with caution - for testing only)
*
* @returns {void}
*/
clearLogs(): void {
this.auditLogs.clear();
this.logQueue = [];
this.logIndex.clear();
}
/**
* Get total audit log count
*
* @returns {number}
*/
getLogCount(): number {
return this.auditLogs.size;
}
/**
* Add log ID to entity index
* @private
* @param {string} entityId - Entity identifier
* @param {string} logId - Audit log identifier
*/
private addToIndex(entityId: string, logId: string): void {
if (!this.logIndex.has(entityId)) {
this.logIndex.set(entityId, new Set());
}
this.logIndex.get(entityId)!.add(logId);
}
/**
* Generate unique audit log ID
* @private
* @returns {string}
*/
private generateAuditLogId(): string {
return `audit_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
}