-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtest_splunk_adapter.py
433 lines (339 loc) · 13.7 KB
/
test_splunk_adapter.py
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
import datetime
import json
import sys
from typing import Iterator
from unittest.mock import ANY, MagicMock, patch
import pytest
import flow.record.adapter.splunk
from flow.record import RecordDescriptor
from flow.record.adapter.splunk import (
ESCAPE,
RESERVED_FIELDS,
Protocol,
SourceType,
SplunkWriter,
escape_field_name,
record_to_splunk_http_api_json,
record_to_splunk_kv_line,
record_to_splunk_tcp_api_json,
)
from flow.record.jsonpacker import JsonRecordPacker
# These base fields are always part of the splunk output. As they are ordered
# and ordered last in the record fields we can append them to any check of the
# splunk output values.
BASE_FIELD_JSON_VALUES = {
f"{ESCAPE}_source": None,
f"{ESCAPE}_classification": None,
f"{ESCAPE}_generated": ANY,
}
BASE_FIELDS_KV_SUFFIX = f'{ESCAPE}_source=None {ESCAPE}_classification=None {ESCAPE}_generated="'
JSON_PACKER = JsonRecordPacker(pack_descriptors=False)
@pytest.fixture
def mock_httpx_package(monkeypatch: pytest.MonkeyPatch) -> Iterator[MagicMock]:
with monkeypatch.context() as m:
mock_httpx = MagicMock()
m.setitem(sys.modules, "httpx", mock_httpx)
yield mock_httpx
escaped_fields = list(
RESERVED_FIELDS.union(
set(["_underscore_field"]),
),
)
@pytest.mark.parametrize(
"field, escaped", list(zip(escaped_fields, [True] * len(escaped_fields))) + [("not_escaped", False)]
)
def test_escape_field_name(field, escaped):
if escaped:
assert escape_field_name(field) == f"{ESCAPE}{field}"
else:
assert escape_field_name(field) == field
def test_splunkify_reserved_field():
test_record_descriptor = RecordDescriptor(
"test/record",
[("string", "rdtag")],
)
test_record = test_record_descriptor(rdtag="bar")
output_key_value = record_to_splunk_kv_line(test_record)
output_http_json = record_to_splunk_http_api_json(JSON_PACKER, test_record)
output_tcp_json = record_to_splunk_tcp_api_json(JSON_PACKER, test_record)
json_dict = dict(
{
"rdtag": None,
"rdtype": "test/record",
f"{ESCAPE}rdtag": "bar",
},
**BASE_FIELD_JSON_VALUES,
)
assert output_key_value.startswith(f'rdtype="test/record" rdtag=None {ESCAPE}rdtag="bar" {BASE_FIELDS_KV_SUFFIX}')
assert json.loads(output_http_json) == {"event": json_dict}
assert json.loads(output_tcp_json) == json_dict
def test_splunkify_normal_field():
test_record_descriptor = RecordDescriptor(
"test/record",
[("string", "foo")],
)
test_record = test_record_descriptor(foo="bar")
output_key_value = record_to_splunk_kv_line(test_record)
output_http_json = record_to_splunk_http_api_json(JSON_PACKER, test_record)
output_tcp_json = record_to_splunk_tcp_api_json(JSON_PACKER, test_record)
json_dict = dict(
{
"rdtag": None,
"rdtype": "test/record",
"foo": "bar",
},
**BASE_FIELD_JSON_VALUES,
)
assert output_key_value.startswith(f'rdtype="test/record" rdtag=None foo="bar" {BASE_FIELDS_KV_SUFFIX}')
assert json.loads(output_http_json) == {"event": json_dict}
assert json.loads(output_tcp_json) == json_dict
def test_splunkify_source_field():
test_record_descriptor = RecordDescriptor(
"test/record",
[("string", "source")],
)
test_record = test_record_descriptor(source="file_on_target")
test_record._source = "path_of_target"
output_key_value = record_to_splunk_kv_line(test_record)
output_http_json = record_to_splunk_http_api_json(JSON_PACKER, test_record)
output_tcp_json = record_to_splunk_tcp_api_json(JSON_PACKER, test_record)
base_fields_kv_suffix = BASE_FIELDS_KV_SUFFIX.replace(
f"{ESCAPE}_source=None",
f'{ESCAPE}_source="{test_record._source}"',
)
base_field_json_values = BASE_FIELD_JSON_VALUES.copy()
base_field_json_values[f"{ESCAPE}_source"] = test_record._source
json_dict = dict(
{
"rdtag": None,
"rdtype": "test/record",
f"{ESCAPE}source": "file_on_target",
},
**base_field_json_values,
)
assert output_key_value.startswith(
f'rdtype="test/record" rdtag=None {ESCAPE}source="file_on_target" {base_fields_kv_suffix}'
)
assert json.loads(output_http_json) == {"event": json_dict}
assert json.loads(output_tcp_json) == json_dict
def test_splunkify_rdtag_field():
test_record_descriptor = RecordDescriptor("test/record", [])
test_record = test_record_descriptor()
output_key_value = record_to_splunk_kv_line(test_record, tag="bar")
output_http_json = record_to_splunk_http_api_json(JSON_PACKER, test_record, tag="bar")
output_tcp_json = record_to_splunk_tcp_api_json(JSON_PACKER, test_record, tag="bar")
json_dict = dict(
{
"rdtag": "bar",
"rdtype": "test/record",
},
**BASE_FIELD_JSON_VALUES,
)
assert output_key_value.startswith(f'rdtype="test/record" rdtag="bar" {BASE_FIELDS_KV_SUFFIX}')
assert json.loads(output_http_json) == {"event": json_dict}
assert json.loads(output_tcp_json) == json_dict
def test_splunkify_none_field():
test_record_descriptor = RecordDescriptor(
"test/record",
[("string", "foo")],
)
test_record = test_record_descriptor()
output_key_value = record_to_splunk_kv_line(test_record)
output_http_json = record_to_splunk_http_api_json(JSON_PACKER, test_record)
output_tcp_json = record_to_splunk_tcp_api_json(JSON_PACKER, test_record)
json_dict = dict(
{
"rdtag": None,
"rdtype": "test/record",
"foo": None,
},
**BASE_FIELD_JSON_VALUES,
)
assert output_key_value.startswith(f'rdtype="test/record" rdtag=None foo=None {BASE_FIELDS_KV_SUFFIX}')
assert json.loads(output_http_json) == {"event": json_dict}
assert json.loads(output_tcp_json) == json_dict
def test_splunkify_byte_field():
test_record_descriptor = RecordDescriptor(
"test/record",
[("bytes", "foo")],
)
test_record = test_record_descriptor(foo=b"bar")
output_key_value = record_to_splunk_kv_line(test_record)
output_http_json = record_to_splunk_http_api_json(JSON_PACKER, test_record)
output_tcp_json = record_to_splunk_tcp_api_json(JSON_PACKER, test_record)
json_dict = dict(
{
"rdtag": None,
"rdtype": "test/record",
"foo": "YmFy",
},
**BASE_FIELD_JSON_VALUES,
)
assert output_key_value.startswith(f'rdtype="test/record" rdtag=None foo="YmFy" {BASE_FIELDS_KV_SUFFIX}')
assert json.loads(output_http_json) == {"event": json_dict}
assert json.loads(output_tcp_json) == json_dict
def test_splunkify_backslash_quote_field():
test_record_descriptor = RecordDescriptor(
"test/record",
[("string", "foo")],
)
test_record = test_record_descriptor(foo=b'\\"')
output = record_to_splunk_kv_line(test_record)
output_http_json = record_to_splunk_http_api_json(JSON_PACKER, test_record)
output_tcp_json = record_to_splunk_tcp_api_json(JSON_PACKER, test_record)
json_dict = dict(
{
"rdtag": None,
"rdtype": "test/record",
"foo": '\\"',
},
**BASE_FIELD_JSON_VALUES,
)
assert output.startswith(f'rdtype="test/record" rdtag=None foo="\\\\\\"" {BASE_FIELDS_KV_SUFFIX}')
assert json.loads(output_http_json) == {"event": json_dict}
assert json.loads(output_tcp_json) == json_dict
def test_record_to_splunk_http_api_json_special_fields():
test_record_descriptor = RecordDescriptor(
"test/record",
[
("datetime", "ts"),
("string", "hostname"),
("string", "foo"),
],
)
# Datetimes should be converted to epoch
test_record = test_record_descriptor(ts=datetime.datetime(1970, 1, 1, 4, 0), hostname="RECYCLOPS", foo="bar")
output = record_to_splunk_http_api_json(JSON_PACKER, test_record)
assert '"time": 14400.0,' in output
assert '"host": "RECYCLOPS"' in output
def test_tcp_protocol_records_sourcetype():
with patch("socket.socket") as mock_socket:
tcp_writer = SplunkWriter("splunk:1337")
assert tcp_writer.host == "splunk"
assert tcp_writer.port == 1337
assert tcp_writer.protocol == Protocol.TCP
assert tcp_writer.sourcetype == SourceType.RECORDS
mock_socket.assert_called()
mock_socket.return_value.connect.assert_called_with(("splunk", 1337))
test_record_descriptor = RecordDescriptor(
"test/record",
[("string", "foo")],
)
test_record = test_record_descriptor(foo="bar")
tcp_writer.write(test_record)
args, _ = mock_socket.return_value.sendall.call_args
written_to_splunk = args[0]
assert written_to_splunk.startswith(
b'rdtype="test/record" rdtag=None foo="bar" ' + BASE_FIELDS_KV_SUFFIX.encode()
)
assert written_to_splunk.endswith(b'"\n')
def test_tcp_protocol_json_sourcetype():
with patch("socket.socket") as mock_socket:
tcp_writer = SplunkWriter("splunk:1337", sourcetype="json")
assert tcp_writer.host == "splunk"
assert tcp_writer.port == 1337
assert tcp_writer.protocol == Protocol.TCP
assert tcp_writer.sourcetype == SourceType.JSON
mock_socket.assert_called()
mock_socket.return_value.connect.assert_called_with(("splunk", 1337))
test_record_descriptor = RecordDescriptor(
"test/record",
[("string", "foo")],
)
test_record = test_record_descriptor(foo="bar")
tcp_writer.write(test_record)
args, _ = mock_socket.return_value.sendall.call_args
written_to_splunk = args[0]
json_dict = dict(
{
"rdtag": None,
"rdtype": "test/record",
"foo": "bar",
},
**BASE_FIELD_JSON_VALUES,
)
assert json.loads(written_to_splunk) == json_dict
assert written_to_splunk.endswith(b"\n")
def test_https_protocol_records_sourcetype(mock_httpx_package: MagicMock):
if "flow.record.adapter.splunk" in sys.modules:
del sys.modules["flow.record.adapter.splunk"]
from flow.record.adapter.splunk import Protocol, SourceType, SplunkWriter
with patch.object(
flow.record.adapter.splunk,
"HAS_HTTPX",
True,
):
mock_httpx_package.Client.return_value.post.return_value.status_code = 200
https_writer = SplunkWriter("https://splunk:8088", token="password123")
assert https_writer.host == "splunk"
assert https_writer.protocol == Protocol.HTTPS
assert https_writer.sourcetype == SourceType.RECORDS
assert https_writer.verify is True
assert https_writer.url == "https://splunk:8088/services/collector/raw?auto_extract_timestamp=true"
_, kwargs = mock_httpx_package.Client.call_args
assert kwargs["verify"] is True
given_headers = kwargs["headers"]
assert given_headers["Authorization"] == "Splunk password123"
assert "X-Splunk-Request-Channel" in given_headers
test_record_descriptor = RecordDescriptor(
"test/record",
[("string", "foo")],
)
test_record = test_record_descriptor(foo="bar")
https_writer.write(test_record)
mock_httpx_package.Client.return_value.post.assert_not_called()
https_writer.close()
mock_httpx_package.Client.return_value.post.assert_called_with(
"https://splunk:8088/services/collector/raw?auto_extract_timestamp=true",
data=ANY,
)
_, kwargs = mock_httpx_package.Client.return_value.post.call_args
sent_data = kwargs["data"]
assert sent_data.startswith(b'rdtype="test/record" rdtag=None foo="bar" ' + BASE_FIELDS_KV_SUFFIX.encode())
assert sent_data.endswith(b'"\n')
def test_https_protocol_json_sourcetype(mock_httpx_package: MagicMock):
if "flow.record.adapter.splunk" in sys.modules:
del sys.modules["flow.record.adapter.splunk"]
from flow.record.adapter.splunk import SplunkWriter
with patch.object(
flow.record.adapter.splunk,
"HAS_HTTPX",
True,
):
mock_httpx_package.Client.return_value.post.return_value.status_code = 200
https_writer = SplunkWriter("https://splunk:8088", token="password123", sourcetype="json")
test_record_descriptor = RecordDescriptor(
"test/record",
[("string", "foo")],
)
https_writer.write(test_record_descriptor(foo="bar"))
https_writer.write(test_record_descriptor(foo="baz"))
mock_httpx_package.Client.return_value.post.assert_not_called()
https_writer.close()
mock_httpx_package.Client.return_value.post.assert_called_with(
"https://splunk:8088/services/collector/event?auto_extract_timestamp=true",
data=ANY,
)
_, kwargs = mock_httpx_package.Client.return_value.post.call_args
sent_data = kwargs["data"]
first_record_json, _, second_record_json = sent_data.partition(b"\n")
assert json.loads(first_record_json) == {
"event": dict(
{
"rdtag": None,
"rdtype": "test/record",
"foo": "bar",
},
**BASE_FIELD_JSON_VALUES,
)
}
assert json.loads(second_record_json) == {
"event": dict(
{
"rdtag": None,
"rdtype": "test/record",
"foo": "baz",
},
**BASE_FIELD_JSON_VALUES,
)
}