-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptions_test.go
More file actions
433 lines (376 loc) · 14 KB
/
options_test.go
File metadata and controls
433 lines (376 loc) · 14 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
// Copyright 2026 AxonOps Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package audit_test
import (
"sync"
"testing"
"time"
"github.com/axonops/audit"
"github.com/axonops/audit/internal/testhelper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/goleak"
)
// ---------------------------------------------------------------------------
// New default config (#388 AC-1)
// ---------------------------------------------------------------------------
func TestNew_NoConfigOptions_UsesDefaults(t *testing.T) {
defer goleak.VerifyNone(t)
out := testhelper.NewMockOutput("defaults")
auditor, err := audit.New(
audit.WithTaxonomy(testhelper.ValidTaxonomy()),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
audit.WithOutputs(out),
)
require.NoError(t, err)
// Emit an event to verify the auditor works with defaults.
err = auditor.AuditEvent(audit.NewEvent("auth_failure", audit.Fields{
"outcome": "failure",
"actor_id": "bob",
}))
require.NoError(t, err)
require.NoError(t, auditor.Close())
assert.Equal(t, 1, out.EventCount(), "default auditor should deliver events")
}
// ---------------------------------------------------------------------------
// New without taxonomy (#388 AC-2)
// ---------------------------------------------------------------------------
func TestNew_WithoutTaxonomy_ReturnsError(t *testing.T) {
_, err := audit.New()
require.Error(t, err)
assert.ErrorIs(t, err, audit.ErrTaxonomyRequired)
}
// ---------------------------------------------------------------------------
// WithDisabled (#388 AC-3)
// ---------------------------------------------------------------------------
func TestNew_WithDisabled_CreatesNoOpLogger(t *testing.T) {
defer goleak.VerifyNone(t)
out := testhelper.NewMockOutput("disabled")
auditor, err := audit.New(
audit.WithDisabled(),
audit.WithTaxonomy(testhelper.ValidTaxonomy()),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
audit.WithOutputs(out),
)
require.NoError(t, err)
require.NotNil(t, auditor)
// Disabled auditor returns nil without delivering.
err = auditor.AuditEvent(audit.NewEvent("auth_failure", audit.Fields{
"outcome": "failure",
"actor_id": "bob",
}))
assert.NoError(t, err)
require.NoError(t, auditor.Close())
assert.Equal(t, 0, out.EventCount(), "disabled auditor must not deliver events")
}
func TestNew_WithDisabled_NoTaxonomy(t *testing.T) {
defer goleak.VerifyNone(t)
auditor, err := audit.New(audit.WithDisabled())
require.NoError(t, err, "disabled auditor must not require a taxonomy")
require.NotNil(t, auditor)
assert.True(t, auditor.IsDisabled())
// AuditEvent silently discards.
err = auditor.AuditEvent(audit.NewEvent("anything", audit.Fields{"k": "v"}))
assert.NoError(t, err)
// Close is safe.
assert.NoError(t, auditor.Close())
}
func TestDisabledAuditor_EnableCategory_ReturnsErrDisabled(t *testing.T) {
auditor, err := audit.New(audit.WithDisabled())
require.NoError(t, err)
defer func() { _ = auditor.Close() }()
assert.ErrorIs(t, auditor.EnableCategory("foo"), audit.ErrDisabled)
assert.ErrorIs(t, auditor.DisableCategory("foo"), audit.ErrDisabled)
assert.ErrorIs(t, auditor.EnableEvent("foo"), audit.ErrDisabled)
assert.ErrorIs(t, auditor.DisableEvent("foo"), audit.ErrDisabled)
assert.ErrorIs(t, auditor.SetOutputRoute("foo", nil), audit.ErrDisabled)
}
func TestDisabledAuditor_Handle_ReturnsValidHandle(t *testing.T) {
auditor, err := audit.New(audit.WithDisabled())
require.NoError(t, err)
defer func() { _ = auditor.Close() }()
handle, handleErr := auditor.Handle("anything")
require.NoError(t, handleErr)
require.NotNil(t, handle)
assert.Equal(t, "anything", handle.EventType())
// Audit on the handle silently discards.
assert.NoError(t, handle.Audit(audit.Fields{"k": "v"}))
}
func TestDisabledAuditor_MustHandle_DoesNotPanic(t *testing.T) {
auditor, err := audit.New(audit.WithDisabled())
require.NoError(t, err)
defer func() { _ = auditor.Close() }()
assert.NotPanics(t, func() {
h := auditor.MustHandle("anything")
assert.NotNil(t, h)
})
}
// ---------------------------------------------------------------------------
// WithQueueSize (#388 AC-4)
// ---------------------------------------------------------------------------
func TestNew_WithQueueSize_SetsCustomSize(t *testing.T) {
defer goleak.VerifyNone(t)
auditor, err := audit.New(
audit.WithQueueSize(50000),
audit.WithTaxonomy(testhelper.ValidTaxonomy()),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
)
require.NoError(t, err)
require.NoError(t, auditor.Close())
}
func TestNew_WithQueueSize_RejectsOverMax(t *testing.T) {
_, err := audit.New(
audit.WithQueueSize(audit.MaxQueueSize+1),
audit.WithTaxonomy(testhelper.ValidTaxonomy()),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
)
require.Error(t, err)
assert.ErrorIs(t, err, audit.ErrConfigInvalid)
assert.Contains(t, err.Error(), "exceeds maximum")
}
// ---------------------------------------------------------------------------
// WithShutdownTimeout (#388 AC-5)
// ---------------------------------------------------------------------------
func TestNew_WithShutdownTimeout_SetsCustomTimeout(t *testing.T) {
defer goleak.VerifyNone(t)
auditor, err := audit.New(
audit.WithShutdownTimeout(30*time.Second),
audit.WithTaxonomy(testhelper.ValidTaxonomy()),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
)
require.NoError(t, err)
require.NoError(t, auditor.Close())
}
func TestNew_WithShutdownTimeout_RejectsOverMax(t *testing.T) {
_, err := audit.New(
audit.WithShutdownTimeout(audit.MaxShutdownTimeout+1),
audit.WithTaxonomy(testhelper.ValidTaxonomy()),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
)
require.Error(t, err)
assert.ErrorIs(t, err, audit.ErrConfigInvalid)
assert.Contains(t, err.Error(), "exceeds maximum")
}
// ---------------------------------------------------------------------------
// WithValidationMode (#388 AC-6)
// ---------------------------------------------------------------------------
func TestNew_WithValidationMode_SetsMode(t *testing.T) {
defer goleak.VerifyNone(t)
out := testhelper.NewMockOutput("permissive")
auditor, err := audit.New(
audit.WithValidationMode(audit.ValidationPermissive),
audit.WithTaxonomy(testhelper.ValidTaxonomy()),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
audit.WithOutputs(out),
)
require.NoError(t, err)
// Unknown fields accepted in permissive mode.
err = auditor.AuditEvent(audit.NewEvent("auth_failure", audit.Fields{
"outcome": "failure",
"actor_id": "bob",
"bogus": "value",
}))
assert.NoError(t, err, "permissive mode should accept unknown fields")
require.NoError(t, auditor.Close())
}
// ---------------------------------------------------------------------------
// WithOmitEmpty (#388 AC-7)
// ---------------------------------------------------------------------------
func TestNew_WithOmitEmpty_OmitsZeroFields(t *testing.T) {
defer goleak.VerifyNone(t)
out := testhelper.NewMockOutput("omit-empty")
auditor, err := audit.New(
audit.WithOmitEmpty(),
audit.WithValidationMode(audit.ValidationPermissive),
audit.WithTaxonomy(testhelper.ValidTaxonomy()),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
audit.WithOutputs(out),
)
require.NoError(t, err)
err = auditor.AuditEvent(audit.NewEvent("auth_failure", audit.Fields{
"outcome": "failure",
"actor_id": "bob",
"empty": "",
}))
require.NoError(t, err)
require.NoError(t, auditor.Close())
require.Equal(t, 1, out.EventCount())
ev := out.GetEvent(0)
_, hasEmpty := ev["empty"]
assert.False(t, hasEmpty, "empty string field should be omitted with WithOmitEmpty")
}
// Note: `WithConfig` and the `Config` struct were removed in #579
// (see docs/adr/0003-config-pattern.md). Functional options
// (`WithQueueSize`, `WithShutdownTimeout`, `WithValidationMode`,
// `WithOmitEmpty`) are the sole configuration mechanism; their
// individual tests appear earlier in this file.
// ---------------------------------------------------------------------------
// Fields defined type (#388 AC-12, AC-13, AC-14)
// ---------------------------------------------------------------------------
func TestFields_DefinedType_Conversion(t *testing.T) {
// Explicit conversion from map[string]any compiles.
m := map[string]any{"k": "v"}
f := audit.Fields(m)
assert.Equal(t, "v", f["k"])
}
func TestFields_DefinedType_Has(t *testing.T) {
f := audit.Fields{"k": "v"}
assert.True(t, f.Has("k"))
assert.False(t, f.Has("missing"))
}
func TestFields_DefinedType_String(t *testing.T) {
f := audit.Fields{"name": "alice", "count": 42}
assert.Equal(t, "alice", f.String("name"))
assert.Equal(t, "", f.String("count"), "non-string should return empty")
assert.Equal(t, "", f.String("missing"), "missing key should return empty")
}
func TestFields_DefinedType_Int(t *testing.T) {
f := audit.Fields{"count": 42, "rate": 3.14, "name": "alice"}
assert.Equal(t, 42, f.Int("count"))
assert.Equal(t, 3, f.Int("rate"), "float64 should truncate to int")
assert.Equal(t, 0, f.Int("name"), "non-numeric should return 0")
assert.Equal(t, 0, f.Int("missing"), "missing key should return 0")
}
// ---------------------------------------------------------------------------
// SuppressEventCategory zero value (#388 AC-15)
// ---------------------------------------------------------------------------
func TestSuppressEventCategory_ZeroValue_EmitsCategory(t *testing.T) {
var tax audit.Taxonomy
assert.False(t, tax.SuppressEventCategory, "zero value should be false (emit category)")
}
func TestSuppressEventCategory_True_SuppressesCategory(t *testing.T) {
defer goleak.VerifyNone(t)
out := testhelper.NewMockOutput("suppress-cat")
tax := &audit.Taxonomy{
Version: 1,
SuppressEventCategory: true,
Categories: map[string]*audit.CategoryDef{"security": {Events: []string{"auth_failure"}}},
Events: map[string]*audit.EventDef{"auth_failure": {Required: []string{"outcome", "actor_id"}}},
}
auditor, err := audit.New(
audit.WithTaxonomy(tax),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
audit.WithOutputs(out),
)
require.NoError(t, err)
err = auditor.AuditEvent(audit.NewEvent("auth_failure", audit.Fields{
"outcome": "failure",
"actor_id": "bob",
}))
require.NoError(t, err)
require.NoError(t, auditor.Close())
require.Equal(t, 1, out.EventCount())
ev := out.GetEvent(0)
_, hasCategory := ev["event_category"]
assert.False(t, hasCategory, "event_category should be suppressed when SuppressEventCategory=true")
}
// ---------------------------------------------------------------------------
// Concurrent construction (#388 AC-16 subset)
// ---------------------------------------------------------------------------
func TestNew_ConcurrentConstruction_NoRace(t *testing.T) {
defer goleak.VerifyNone(t)
var wg sync.WaitGroup
for range 10 {
wg.Add(1)
go func() {
defer wg.Done()
// Each goroutine gets its own taxonomy to avoid data race
// on internal precomputation (precomputeTaxonomy mutates
// EventDef slices/maps).
tax := testhelper.ValidTaxonomy()
auditor, err := audit.New(
audit.WithTaxonomy(tax),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
)
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
_ = auditor.Close()
}()
}
wg.Wait()
}
// ---------------------------------------------------------------------------
// Benchmark: NewLogger construction (#388)
// ---------------------------------------------------------------------------
func BenchmarkNew_Construction(b *testing.B) {
tax := testhelper.ValidTaxonomy()
out := testhelper.NewMockOutput("bench")
for b.Loop() {
auditor, err := audit.New(
audit.WithTaxonomy(tax),
audit.WithAppName("test-app"),
audit.WithHost("test-host"),
audit.WithOutputs(out),
)
if err != nil {
b.Fatal(err)
}
_ = auditor.Close()
}
}
// ---------------------------------------------------------------------------
// Required AppName / Host (#593 B-41)
// ---------------------------------------------------------------------------
func TestNew_MissingAppName_ReturnsErrAppNameRequired(t *testing.T) {
t.Parallel()
out := testhelper.NewMockOutput("test")
_, err := audit.New(
audit.WithTaxonomy(testhelper.ValidTaxonomy()),
audit.WithHost("test-host"),
audit.WithOutputs(out),
)
require.Error(t, err)
assert.ErrorIs(t, err, audit.ErrAppNameRequired)
}
func TestNew_MissingHost_ReturnsErrHostRequired(t *testing.T) {
t.Parallel()
out := testhelper.NewMockOutput("test")
_, err := audit.New(
audit.WithTaxonomy(testhelper.ValidTaxonomy()),
audit.WithAppName("test-app"),
audit.WithOutputs(out),
)
require.Error(t, err)
assert.ErrorIs(t, err, audit.ErrHostRequired)
}
func TestNew_WithDisabled_AllowsMissingAppNameAndHost(t *testing.T) {
t.Parallel()
auditor, err := audit.New(audit.WithDisabled())
require.NoError(t, err, "disabled auditor must not require AppName or Host")
require.NotNil(t, auditor)
require.NoError(t, auditor.Close())
}
// ---------------------------------------------------------------------------
// Severity constants (#593 B-27)
// ---------------------------------------------------------------------------
func TestSeverity_ExportedConstants(t *testing.T) {
t.Parallel()
// Constants exist with the documented values. Downstream code and
// integrations rely on these so they form part of the v1.0 API
// surface; regressing them requires a major-version bump.
assert.Equal(t, 0, audit.MinSeverity)
assert.Equal(t, 10, audit.MaxSeverity)
}