-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathaudit.test.ts
More file actions
598 lines (517 loc) · 15.5 KB
/
Copy pathaudit.test.ts
File metadata and controls
598 lines (517 loc) · 15.5 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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
import { describe, it, expect } from 'vitest';
import {
AuditEventType,
AuditEventSeverity,
AuditEventActorSchema,
AuditEventTargetSchema,
AuditEventChangeSchema,
AuditEventSchema,
AuditRetentionPolicySchema,
SuspiciousActivityRuleSchema,
AuditStorageConfigSchema,
AuditEventFilterSchema,
AuditConfigSchema,
DEFAULT_SUSPICIOUS_ACTIVITY_RULES,
type AuditEvent,
type AuditConfig,
type SuspiciousActivityRule,
} from './audit.zod';
describe('AuditEventType', () => {
it('should accept valid event types', () => {
const validTypes = [
'data.create',
'data.read',
'data.update',
'data.delete',
'auth.login',
'auth.login_failed',
'auth.logout',
'authz.permission_granted',
'authz.role_assigned',
'security.access_denied',
];
validTypes.forEach((type) => {
expect(() => AuditEventType.parse(type)).not.toThrow();
});
});
it('should reject invalid event types', () => {
expect(() => AuditEventType.parse('invalid.type')).toThrow();
expect(() => AuditEventType.parse('dataCreate')).toThrow();
});
});
describe('AuditEventSeverity', () => {
it('should accept valid severity levels', () => {
const validLevels = ['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency'];
validLevels.forEach((level) => {
expect(() => AuditEventSeverity.parse(level)).not.toThrow();
});
});
it('should reject invalid severity levels', () => {
expect(() => AuditEventSeverity.parse('invalid')).toThrow();
expect(() => AuditEventSeverity.parse('high')).toThrow();
});
});
describe('AuditEventActorSchema', () => {
it('should accept valid actor configuration', () => {
const validActor = {
type: 'user',
id: 'user_123',
name: 'John Doe',
email: 'john@example.com',
ipAddress: '192.168.1.1',
userAgent: 'Mozilla/5.0',
};
expect(() => AuditEventActorSchema.parse(validActor)).not.toThrow();
});
it('should accept minimal actor configuration', () => {
const minimalActor = {
type: 'system',
id: 'system',
};
expect(() => AuditEventActorSchema.parse(minimalActor)).not.toThrow();
});
it('should reject invalid email', () => {
const invalidActor = {
type: 'user',
id: 'user_123',
email: 'not-an-email',
};
expect(() => AuditEventActorSchema.parse(invalidActor)).toThrow();
});
});
describe('AuditEventTargetSchema', () => {
it('should accept valid target configuration', () => {
const validTarget = {
type: 'record',
id: 'rec_456',
name: 'Customer Record #456',
metadata: {
objectName: 'customer',
fields: ['name', 'email'],
},
};
expect(() => AuditEventTargetSchema.parse(validTarget)).not.toThrow();
});
it('should accept minimal target configuration', () => {
const minimalTarget = {
type: 'object',
id: 'obj_789',
};
expect(() => AuditEventTargetSchema.parse(minimalTarget)).not.toThrow();
});
});
describe('AuditEventChangeSchema', () => {
it('should accept valid change record', () => {
const validChange = {
field: 'email',
oldValue: 'old@example.com',
newValue: 'new@example.com',
};
expect(() => AuditEventChangeSchema.parse(validChange)).not.toThrow();
});
it('should accept change with only new value', () => {
const createChange = {
field: 'name',
newValue: 'John Doe',
};
expect(() => AuditEventChangeSchema.parse(createChange)).not.toThrow();
});
});
describe('AuditEventSchema', () => {
it('should accept complete audit event', () => {
const validEvent: AuditEvent = {
id: 'evt_123',
eventType: 'data.update',
severity: 'info',
timestamp: new Date().toISOString(),
actor: {
type: 'user',
id: 'user_123',
email: 'user@example.com',
},
target: {
type: 'record',
id: 'rec_456',
},
description: 'User updated customer record',
changes: [
{
field: 'email',
oldValue: 'old@example.com',
newValue: 'new@example.com',
},
],
result: 'success',
tenantId: 'tenant_789',
requestId: 'req_abc',
};
expect(() => AuditEventSchema.parse(validEvent)).not.toThrow();
});
it('should accept minimal audit event', () => {
const minimalEvent = {
id: 'evt_456',
eventType: 'auth.login',
timestamp: new Date().toISOString(),
actor: {
type: 'user',
id: 'user_123',
},
description: 'User logged in',
};
expect(() => AuditEventSchema.parse(minimalEvent)).not.toThrow();
});
it('should default severity to info', () => {
const event = {
id: 'evt_789',
eventType: 'data.read',
timestamp: new Date().toISOString(),
actor: {
type: 'user',
id: 'user_123',
},
description: 'User viewed record',
};
const parsed = AuditEventSchema.parse(event);
expect(parsed.severity).toBe('info');
});
it('should default result to success', () => {
const event = {
id: 'evt_101',
eventType: 'data.create',
timestamp: new Date().toISOString(),
actor: {
type: 'user',
id: 'user_123',
},
description: 'User created record',
};
const parsed = AuditEventSchema.parse(event);
expect(parsed.result).toBe('success');
});
it('should accept failed event with error message', () => {
const failedEvent = {
id: 'evt_202',
eventType: 'auth.login',
severity: 'warning',
timestamp: new Date().toISOString(),
actor: {
type: 'user',
id: 'user_123',
},
description: 'Login attempt failed',
result: 'failure',
errorMessage: 'Invalid password',
};
expect(() => AuditEventSchema.parse(failedEvent)).not.toThrow();
});
});
describe('AuditRetentionPolicySchema', () => {
it('should accept valid retention policy', () => {
const validPolicy = {
retentionDays: 365,
archiveAfterRetention: true,
archiveStorage: {
type: 's3',
bucket: 'audit-logs-archive',
path: 'logs/',
},
customRetention: {
'auth.login_failed': 730, // 2 years
'security.data_breach': 2555, // 7 years
},
minimumRetentionDays: 180,
};
expect(() => AuditRetentionPolicySchema.parse(validPolicy)).not.toThrow();
});
it('should default to 180 days retention', () => {
const policy = {};
const parsed = AuditRetentionPolicySchema.parse(policy);
expect(parsed.retentionDays).toBe(180);
});
it('should default to archiving enabled', () => {
const policy = {};
const parsed = AuditRetentionPolicySchema.parse(policy);
expect(parsed.archiveAfterRetention).toBe(true);
});
it('should reject negative retention days', () => {
const invalidPolicy = {
retentionDays: -30,
};
expect(() => AuditRetentionPolicySchema.parse(invalidPolicy)).toThrow();
});
});
describe('SuspiciousActivityRuleSchema', () => {
it('should accept valid suspicious activity rule', () => {
const validRule: SuspiciousActivityRule = {
id: 'rule_123',
name: 'Multiple Failed Logins',
description: 'Detects brute force attacks',
enabled: true,
eventTypes: ['auth.login_failed'],
condition: {
threshold: 5,
windowSeconds: 600,
groupBy: ['actor.id'],
},
actions: ['alert', 'lock_account'],
alertSeverity: 'critical',
notifications: {
email: ['security@example.com'],
slack: 'https://hooks.slack.com/services/xxx',
},
};
expect(() => SuspiciousActivityRuleSchema.parse(validRule)).not.toThrow();
});
it('should default enabled to true', () => {
const rule = {
id: 'rule_456',
name: 'Test Rule',
eventTypes: ['data.export'],
condition: {
threshold: 10,
windowSeconds: 3600,
},
actions: ['alert'],
};
const parsed = SuspiciousActivityRuleSchema.parse(rule);
expect(parsed.enabled).toBe(true);
});
it('should default alert severity to warning', () => {
const rule = {
id: 'rule_789',
name: 'Test Rule',
eventTypes: ['data.delete'],
condition: {
threshold: 3,
windowSeconds: 300,
},
actions: ['alert'],
};
const parsed = SuspiciousActivityRuleSchema.parse(rule);
expect(parsed.alertSeverity).toBe('warning');
});
});
describe('AuditStorageConfigSchema', () => {
it('should accept database storage configuration', () => {
const dbStorage = {
type: 'database',
connectionString: 'postgresql://localhost:5432/audit',
bufferEnabled: true,
bufferSize: 100,
flushIntervalSeconds: 5,
compression: true,
};
expect(() => AuditStorageConfigSchema.parse(dbStorage)).not.toThrow();
});
it('should accept elasticsearch storage configuration', () => {
const esStorage = {
type: 'elasticsearch',
connectionString: 'https://elasticsearch:9200',
config: {
index: 'audit-logs',
shards: 5,
},
};
expect(() => AuditStorageConfigSchema.parse(esStorage)).not.toThrow();
});
it('should default buffer settings', () => {
const storage = {
type: 'mongodb',
};
const parsed = AuditStorageConfigSchema.parse(storage);
expect(parsed.bufferEnabled).toBe(true);
expect(parsed.bufferSize).toBe(100);
expect(parsed.flushIntervalSeconds).toBe(5);
expect(parsed.compression).toBe(true);
});
});
describe('AuditEventFilterSchema', () => {
it('should accept complete filter configuration', () => {
const validFilter = {
eventTypes: ['data.create', 'data.update'],
severities: ['warning', 'error', 'critical'],
actorId: 'user_123',
tenantId: 'tenant_456',
timeRange: {
from: '2024-01-01T00:00:00Z',
to: '2024-12-31T23:59:59Z',
},
result: 'failure',
searchQuery: 'password reset',
};
expect(() => AuditEventFilterSchema.parse(validFilter)).not.toThrow();
});
it('should accept minimal filter configuration', () => {
const minimalFilter = {};
expect(() => AuditEventFilterSchema.parse(minimalFilter)).not.toThrow();
});
it('should accept partial filters', () => {
const partialFilter = {
eventTypes: ['auth.login'],
timeRange: {
from: '2024-01-01T00:00:00Z',
to: '2024-01-31T23:59:59Z',
},
};
expect(() => AuditEventFilterSchema.parse(partialFilter)).not.toThrow();
});
});
describe('AuditConfigSchema', () => {
it('should accept complete audit configuration', () => {
const validConfig: AuditConfig = {
name: 'main_audit',
label: 'Main Audit Configuration',
enabled: true,
eventTypes: ['data.create', 'data.update', 'auth.login'],
minimumSeverity: 'info',
storage: {
type: 'database',
connectionString: 'postgresql://localhost/audit',
},
retentionPolicy: {
retentionDays: 365,
},
suspiciousActivityRules: [
{
id: 'failed_logins',
name: 'Failed Logins',
eventTypes: ['auth.login_failed'],
condition: {
threshold: 5,
windowSeconds: 600,
},
actions: ['alert'],
},
],
includeSensitiveData: false,
logReads: false,
compliance: {
standards: ['gdpr', 'sox'],
immutableLogs: true,
},
};
expect(() => AuditConfigSchema.parse(validConfig)).not.toThrow();
});
it('should accept minimal audit configuration', () => {
const minimalConfig = {
name: 'basic_audit',
label: 'Basic Audit',
storage: {
type: 'database',
},
};
expect(() => AuditConfigSchema.parse(minimalConfig)).not.toThrow();
});
it('should enforce snake_case naming convention', () => {
const invalidConfig = {
name: 'mainAudit', // camelCase, should be snake_case
label: 'Main Audit',
storage: {
type: 'database',
},
};
expect(() => AuditConfigSchema.parse(invalidConfig)).toThrow();
});
it('should accept valid snake_case names', () => {
const validNames = ['audit_config', 'main_audit', 'security_audit_log'];
validNames.forEach((name) => {
const config = {
name,
label: 'Test Audit',
storage: { type: 'database' },
};
expect(() => AuditConfigSchema.parse(config)).not.toThrow();
});
});
it('should default enabled to true', () => {
const config = {
name: 'test_audit',
label: 'Test Audit',
storage: { type: 'database' },
};
const parsed = AuditConfigSchema.parse(config);
expect(parsed.enabled).toBe(true);
});
it('should default minimumSeverity to info', () => {
const config = {
name: 'test_audit',
label: 'Test Audit',
storage: { type: 'database' },
};
const parsed = AuditConfigSchema.parse(config);
expect(parsed.minimumSeverity).toBe('info');
});
it('should default redactFields to common sensitive fields', () => {
const config = {
name: 'test_audit',
label: 'Test Audit',
storage: { type: 'database' },
};
const parsed = AuditConfigSchema.parse(config);
expect(parsed.redactFields).toContain('password');
expect(parsed.redactFields).toContain('token');
expect(parsed.redactFields).toContain('apiKey');
});
it('should default logReads to false', () => {
const config = {
name: 'test_audit',
label: 'Test Audit',
storage: { type: 'database' },
};
const parsed = AuditConfigSchema.parse(config);
expect(parsed.logReads).toBe(false);
});
it('should default readSamplingRate to 0.1', () => {
const config = {
name: 'test_audit',
label: 'Test Audit',
storage: { type: 'database' },
};
const parsed = AuditConfigSchema.parse(config);
expect(parsed.readSamplingRate).toBe(0.1);
});
it('should accept compliance configuration', () => {
const config = {
name: 'compliance_audit',
label: 'Compliance Audit',
storage: { type: 'database' },
compliance: {
standards: ['sox', 'hipaa', 'gdpr'],
immutableLogs: true,
requireSigning: true,
signingKey: 'secret-key-123',
},
};
expect(() => AuditConfigSchema.parse(config)).not.toThrow();
});
});
describe('DEFAULT_SUSPICIOUS_ACTIVITY_RULES', () => {
it('should have valid default rules', () => {
expect(DEFAULT_SUSPICIOUS_ACTIVITY_RULES.length).toBeGreaterThan(0);
DEFAULT_SUSPICIOUS_ACTIVITY_RULES.forEach((rule) => {
expect(() => SuspiciousActivityRuleSchema.parse(rule)).not.toThrow();
});
});
it('should include multiple failed logins rule', () => {
const rule = DEFAULT_SUSPICIOUS_ACTIVITY_RULES.find(
(r) => r.id === 'multiple_failed_logins'
);
expect(rule).toBeDefined();
expect(rule?.eventTypes).toContain('auth.login_failed');
expect(rule?.condition.threshold).toBe(5);
});
it('should include bulk data export rule', () => {
const rule = DEFAULT_SUSPICIOUS_ACTIVITY_RULES.find(
(r) => r.id === 'bulk_data_export'
);
expect(rule).toBeDefined();
expect(rule?.eventTypes).toContain('data.export');
});
it('should include permission changes rule', () => {
const rule = DEFAULT_SUSPICIOUS_ACTIVITY_RULES.find(
(r) => r.id === 'suspicious_permission_changes'
);
expect(rule).toBeDefined();
expect(rule?.actions).toContain('alert');
});
});