Debian Codegraph @

ansible_collections/splunk/es/tests/unit/plugins/module_utils/test_finding_utils.py

raw
1 # Copyright 2026 Red Hat Inc.
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 #
18
19 """
20 Unit tests for the finding module utilities.
21
22 These tests verify that the utility functions in plugins/module_utils/finding.py
23 work correctly for:
24 - Building API paths
25 - Extracting notable time from ref_ids
26 - Mapping between API and module parameter formats
27 - Status and disposition value conversions
28 """
29
30
31 from ansible_collections.splunk.es.plugins.action.splunk_finding import (
32 ActionModule,
33 )
34 from ansible_collections.splunk.es.plugins.module_utils.finding import (
35 FINDING_KEY_TRANSFORM,
36 build_finding_api_path,
37 extract_notable_time,
38 get_earliest_from_ref_id,
39 map_finding_from_api,
40 )
41 from ansible_collections.splunk.es.plugins.module_utils.splunk_utils import (
42 DEFAULT_API_APP,
43 DEFAULT_API_APP_SECURITY_SUITE,
44 DEFAULT_API_NAMESPACE,
45 DEFAULT_API_USER,
46 DISPOSITION_FROM_API,
47 DISPOSITION_TO_API,
48 STATUS_FROM_API,
49 STATUS_TO_API,
50 )
51
52
53 class TestBuildFindingApiPath:
54 """Tests for the build_finding_api_path function.
55
56 This function constructs the REST API path for the findings endpoint.
57 It should handle default values and custom namespace/user/app overrides.
58 """
59
60 def test_build_finding_api_path_defaults(self):
61 """Test that default API path is constructed correctly.
62
63 When called without arguments, should use the default namespace,
64 user, and app values defined in the module.
65 """
66 result = build_finding_api_path()
67
68 expected = f"{DEFAULT_API_NAMESPACE}/{DEFAULT_API_USER}/{DEFAULT_API_APP_SECURITY_SUITE}/public/v2/findings"
69 assert result == expected
70
71 def test_build_finding_api_path_custom_namespace(self):
72 """Test API path with custom namespace value."""
73 result = build_finding_api_path(namespace="customNS")
74
75 expected = (
76 f"customNS/{DEFAULT_API_USER}/{DEFAULT_API_APP_SECURITY_SUITE}/public/v2/findings"
77 )
78 assert result == expected
79
80 def test_build_finding_api_path_custom_user(self):
81 """Test API path with custom user value."""
82 result = build_finding_api_path(user="admin")
83
84 expected = (
85 f"{DEFAULT_API_NAMESPACE}/admin/{DEFAULT_API_APP_SECURITY_SUITE}/public/v2/findings"
86 )
87 assert result == expected
88
89 def test_build_finding_api_path_custom_app(self):
90 """Test API path with custom app value."""
91 result = build_finding_api_path(app="CustomSecurityApp")
92
93 expected = (
94 f"{DEFAULT_API_NAMESPACE}/{DEFAULT_API_USER}/CustomSecurityApp/public/v2/findings"
95 )
96 assert result == expected
97
98 def test_build_finding_api_path_all_custom(self):
99 """Test API path with all custom values."""
100 result = build_finding_api_path(
101 namespace="myNS",
102 user="myuser",
103 app="MyApp",
104 )
105
106 assert result == "myNS/myuser/MyApp/public/v2/findings"
107
108
109 class TestBuildUpdateApiPath:
110 """Tests for the ActionModule.build_update_api_path method.
111
112 This method constructs the REST API path for updating findings
113 via the investigations API (uses missioncontrol app).
114 """
115
116 def test_build_update_api_path_defaults(self):
117 """Test update API path with default namespace and user."""
118 ref_id = "abc-123@@notable@@time1234567890"
119 result = ActionModule.build_update_api_path(ref_id)
120
121 expected = f"{DEFAULT_API_NAMESPACE}/{DEFAULT_API_USER}/{DEFAULT_API_APP}/v1/investigations/{ref_id}"
122 assert result == expected
123 assert "missioncontrol" in result
124
125 def test_build_update_api_path_custom_namespace(self):
126 """Test update API path with custom namespace."""
127 ref_id = "abc-123@@notable@@time1234567890"
128 result = ActionModule.build_update_api_path(ref_id, namespace="customNS")
129
130 expected = f"customNS/{DEFAULT_API_USER}/{DEFAULT_API_APP}/v1/investigations/{ref_id}"
131 assert result == expected
132
133 def test_build_update_api_path_custom_user(self):
134 """Test update API path with custom user."""
135 ref_id = "abc-123@@notable@@time1234567890"
136 result = ActionModule.build_update_api_path(ref_id, user="admin")
137
138 expected = f"{DEFAULT_API_NAMESPACE}/admin/{DEFAULT_API_APP}/v1/investigations/{ref_id}"
139 assert result == expected
140
141 def test_build_update_api_path_special_characters_in_ref_id(self):
142 """Test update API path handles special characters in ref_id.
143
144 The ref_id is included as-is in the path; URL encoding happens elsewhere.
145 """
146 ref_id = "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865"
147 result = ActionModule.build_update_api_path(ref_id)
148
149 assert ref_id in result
150
151
152 class TestExtractNotableTime:
153 """Tests for the extract_notable_time function.
154
155 This function extracts the timestamp from a finding reference ID.
156 The ref_id format is: uuid@@notable@@time{timestamp}
157 """
158
159 def test_extract_notable_time_valid(self):
160 """Test extraction from a valid ref_id format."""
161 ref_id = "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865"
162 result = extract_notable_time(ref_id)
163
164 assert result == "1768225865"
165
166 def test_extract_notable_time_different_uuid(self):
167 """Test extraction works with different UUID formats."""
168 ref_id = "abc123@@notable@@time9999999999"
169 result = extract_notable_time(ref_id)
170
171 assert result == "9999999999"
172
173 def test_extract_notable_time_empty_string(self):
174 """Test that empty string returns None."""
175 result = extract_notable_time("")
176
177 assert result is None
178
179 def test_extract_notable_time_none(self):
180 """Test that None input returns None."""
181 result = extract_notable_time(None)
182
183 assert result is None
184
185 def test_extract_notable_time_no_time_prefix(self):
186 """Test that ref_id without 'time' prefix returns None."""
187 ref_id = "abc-123@@notable@@1768225865"
188 result = extract_notable_time(ref_id)
189
190 assert result is None
191
192 def test_extract_notable_time_invalid_format(self):
193 """Test that completely invalid format returns None."""
194 ref_id = "just-some-random-string"
195 result = extract_notable_time(ref_id)
196
197 assert result is None
198
199 def test_extract_notable_time_no_digits_after_time(self):
200 """Test that 'time' without digits returns None."""
201 ref_id = "abc-123@@notable@@time"
202 result = extract_notable_time(ref_id)
203
204 assert result is None
205
206
207 class TestGetEarliestFromRefId:
208 """Tests for the get_earliest_from_ref_id function.
209
210 This function extracts the notable time from a ref_id and applies a 1-second
211 buffer so the resulting 'earliest' value is guaranteed to include the finding
212 in Splunk time-range queries.
213 """
214
215 def test_get_earliest_from_ref_id_valid(self):
216 """Test that a valid ref_id returns the timestamp minus 1 second."""
217 ref_id = "2008e99d-af14-4fec-89da-b9b17a81820a@@notable@@time1768225865"
218 result = get_earliest_from_ref_id(ref_id)
219
220 assert result == "1768225864"
221
222 def test_get_earliest_from_ref_id_different_timestamp(self):
223 """Test with a different timestamp value."""
224 ref_id = "abc123@@notable@@time1000000000"
225 result = get_earliest_from_ref_id(ref_id)
226
227 assert result == "999999999"
228
229 def test_get_earliest_from_ref_id_empty_string(self):
230 """Test that empty ref_id returns None."""
231 result = get_earliest_from_ref_id("")
232
233 assert result is None
234
235 def test_get_earliest_from_ref_id_none(self):
236 """Test that None ref_id returns None."""
237 result = get_earliest_from_ref_id(None)
238
239 assert result is None
240
241 def test_get_earliest_from_ref_id_no_time(self):
242 """Test that ref_id without time component returns None."""
243 ref_id = "just-a-uuid-without-time"
244 result = get_earliest_from_ref_id(ref_id)
245
246 assert result is None
247
248 def test_get_earliest_from_ref_id_timestamp_1(self):
249 """Test boundary: timestamp of 1 returns '0'."""
250 ref_id = "abc@@notable@@time1"
251 result = get_earliest_from_ref_id(ref_id)
252
253 assert result == "0"
254
255
256 class TestMapFindingFromApi:
257 """Tests for the map_finding_from_api function.
258
259 This function converts the API response format to the module parameter format.
260 It handles key renaming, status/disposition conversion, and type normalization.
261 """
262
263 def test_map_finding_from_api_basic(self):
264 """Test basic field mapping from API to module format."""
265 api_response = {
266 "rule_title": "Test Finding",
267 "rule_description": "A test description",
268 "security_domain": "access",
269 "risk_object": "testuser",
270 "risk_object_type": "user",
271 "risk_score": "50",
272 }
273
274 result = map_finding_from_api(api_response, FINDING_KEY_TRANSFORM)
275
276 assert result["title"] == "Test Finding"
277 assert result["description"] == "A test description"
278 assert result["security_domain"] == "access"
279 assert result["entity"] == "testuser"
280 assert result["entity_type"] == "user"
281 assert result["finding_score"] == 50 # Converted to int
282
283 def test_map_finding_from_api_with_finding_id(self):
284 """Test that finding_id is extracted as ref_id."""
285 api_response = {
286 "finding_id": "abc-123@@notable@@time1234567890",
287 "rule_title": "Test Finding",
288 }
289
290 result = map_finding_from_api(api_response, FINDING_KEY_TRANSFORM)
291
292 assert result["ref_id"] == "abc-123@@notable@@time1234567890"
293
294 def test_map_finding_from_api_status_conversion(self):
295 """Test that numeric status codes are converted to string names."""
296 api_response = {
297 "rule_title": "Test",
298 "status": "1", # API uses numeric codes
299 }
300
301 result = map_finding_from_api(api_response, FINDING_KEY_TRANSFORM)
302
303 assert result["status"] == "new" # Converted to human-readable
304
305 def test_map_finding_from_api_all_status_values(self):
306 """Test all status value conversions."""
307 for api_value, module_value in STATUS_FROM_API.items():
308 api_response = {"rule_title": "Test", "status": api_value}
309 result = map_finding_from_api(api_response, FINDING_KEY_TRANSFORM)
310 assert result["status"] == module_value
311
312 def test_map_finding_from_api_disposition_conversion(self):
313 """Test that disposition codes are converted to string names."""
314 api_response = {
315 "rule_title": "Test",
316 "disposition": "disposition:6", # API format
317 }
318
319 result = map_finding_from_api(api_response, FINDING_KEY_TRANSFORM)
320
321 assert result["disposition"] == "undetermined"
322
323 def test_map_finding_from_api_all_disposition_values(self):
324 """Test all disposition value conversions."""
325 for api_value, module_value in DISPOSITION_FROM_API.items():
326 api_response = {"rule_title": "Test", "disposition": api_value}
327 result = map_finding_from_api(api_response, FINDING_KEY_TRANSFORM)
328 assert result["disposition"] == module_value
329
330 def test_map_finding_from_api_finding_score_float_string(self):
331 """Test that finding_score handles float strings like '50.0'."""
332 api_response = {
333 "rule_title": "Test",
334 "risk_score": "75.5",
335 }
336
337 result = map_finding_from_api(api_response, FINDING_KEY_TRANSFORM)
338
339 assert result["finding_score"] == 75 # Truncated to int
340
341 def test_map_finding_from_api_empty_config(self):
342 """Test handling of empty configuration."""
343 result = map_finding_from_api({}, FINDING_KEY_TRANSFORM)
344
345 assert result == {}
346
347 def test_map_finding_from_api_default_key_transform(self):
348 """Test that default key_transform is used when not provided."""
349 api_response = {
350 "rule_title": "Test Finding",
351 }
352
353 result = map_finding_from_api(api_response)
354
355 assert result["title"] == "Test Finding"
356
357
358 class TestMapFindingToApi:
359 """Tests for the ActionModule.map_finding_to_api method.
360
361 This method converts module parameters to API payload format.
362 It handles key renaming and adds required default values.
363 """
364
365 def test_map_finding_to_api_basic(self):
366 """Test basic field mapping from module to API format."""
367 finding = {
368 "title": "Test Finding",
369 "description": "A test description",
370 "security_domain": "access",
371 "entity": "testuser",
372 "entity_type": "user",
373 "finding_score": 50,
374 }
375
376 result = ActionModule.map_finding_to_api(finding, FINDING_KEY_TRANSFORM)
377
378 assert result["rule_title"] == "Test Finding"
379 assert result["rule_description"] == "A test description"
380 assert result["security_domain"] == "access"
381 assert result["risk_object"] == "testuser"
382 assert result["risk_object_type"] == "user"
383 assert result["risk_score"] == 50
384
385 def test_map_finding_to_api_adds_defaults(self):
386 """Test that app and creator defaults are added."""
387 finding = {"title": "Test"}
388
389 result = ActionModule.map_finding_to_api(finding, FINDING_KEY_TRANSFORM)
390
391 assert result["app"] == "SplunkEnterpriseSecuritySuite"
392 assert result["creator"] == "admin"
393
394 def test_map_finding_to_api_status_conversion(self):
395 """Test that string status is converted to numeric code."""
396 finding = {
397 "title": "Test",
398 "status": "new",
399 }
400
401 result = ActionModule.map_finding_to_api(finding, FINDING_KEY_TRANSFORM)
402
403 assert result["status"] == "1"
404
405 def test_map_finding_to_api_all_status_values(self):
406 """Test all status value conversions to API format."""
407 for module_value, api_value in STATUS_TO_API.items():
408 finding = {"title": "Test", "status": module_value}
409 result = ActionModule.map_finding_to_api(finding, FINDING_KEY_TRANSFORM)
410 assert result["status"] == api_value
411
412 def test_map_finding_to_api_disposition_conversion(self):
413 """Test that string disposition is converted to API format."""
414 finding = {
415 "title": "Test",
416 "disposition": "true_positive",
417 }
418
419 result = ActionModule.map_finding_to_api(finding, FINDING_KEY_TRANSFORM)
420
421 assert result["disposition"] == "disposition:1"
422
423 def test_map_finding_to_api_all_disposition_values(self):
424 """Test all disposition value conversions to API format."""
425 for module_value, api_value in DISPOSITION_TO_API.items():
426 finding = {"title": "Test", "disposition": module_value}
427 result = ActionModule.map_finding_to_api(finding, FINDING_KEY_TRANSFORM)
428 assert result["disposition"] == api_value
429
430 def test_map_finding_to_api_with_custom_fields(self):
431 """Test that custom fields are flattened into payload."""
432 finding = {
433 "title": "Test",
434 "fields": [
435 {"name": "custom_field_a", "value": "value1"},
436 {"name": "custom_field_b", "value": "value2"},
437 ],
438 }
439
440 result = ActionModule.map_finding_to_api(finding, FINDING_KEY_TRANSFORM)
441
442 assert result["custom_field_a"] == "value1"
443 assert result["custom_field_b"] == "value2"
444
445 def test_map_finding_to_api_empty_fields(self):
446 """Test handling of empty fields list."""
447 finding = {
448 "title": "Test",
449 "fields": [],
450 }
451
452 result = ActionModule.map_finding_to_api(finding, FINDING_KEY_TRANSFORM)
453
454 # Should not raise error, just skip empty fields
455 assert "rule_title" in result
456
457
458 class TestMapUpdateToApi:
459 """Tests for the ActionModule.map_update_to_api method.
460
461 This method converts module parameters to the update API payload format.
462 Only updatable fields (owner, status, urgency, disposition) are included.
463 """
464
465 def test_map_update_to_api_owner(self):
466 """Test that owner is mapped to assignee."""
467 finding = {"owner": "admin"}
468
469 result = ActionModule.map_update_to_api(finding)
470
471 assert result["assignee"] == "admin"
472 assert "owner" not in result
473
474 def test_map_update_to_api_status(self):
475 """Test that status is converted to numeric code."""
476 finding = {"status": "resolved"}
477
478 result = ActionModule.map_update_to_api(finding)
479
480 assert result["status"] == "4"
481
482 def test_map_update_to_api_urgency(self):
483 """Test that urgency is passed through."""
484 finding = {"urgency": "high"}
485
486 result = ActionModule.map_update_to_api(finding)
487
488 assert result["urgency"] == "high"
489
490 def test_map_update_to_api_disposition(self):
491 """Test that disposition is converted to API format."""
492 finding = {"disposition": "false_positive"}
493
494 result = ActionModule.map_update_to_api(finding)
495
496 assert result["disposition"] == "disposition:3"
497
498 def test_map_update_to_api_all_updatable_fields(self):
499 """Test mapping with all updatable fields."""
500 finding = {
501 "owner": "analyst",
502 "status": "in_progress",
503 "urgency": "critical",
504 "disposition": "true_positive",
505 }
506
507 result = ActionModule.map_update_to_api(finding)
508
509 assert result["assignee"] == "analyst"
510 assert result["status"] == "2"
511 assert result["urgency"] == "critical"
512 assert result["disposition"] == "disposition:1"
513
514 def test_map_update_to_api_ignores_non_updatable(self):
515 """Test that non-updatable fields are ignored."""
516 finding = {
517 "title": "Should be ignored",
518 "description": "Also ignored",
519 "owner": "admin",
520 }
521
522 result = ActionModule.map_update_to_api(finding)
523
524 assert "title" not in result
525 assert "rule_title" not in result
526 assert "description" not in result
527 assert result["assignee"] == "admin"
528
529 def test_map_update_to_api_none_values(self):
530 """Test that None values are excluded."""
531 finding = {
532 "owner": None,
533 "status": "new",
534 }
535
536 result = ActionModule.map_update_to_api(finding)
537
538 assert "assignee" not in result
539 assert result["status"] == "1"
540
541 def test_map_update_to_api_empty_dict(self):
542 """Test handling of empty dictionary."""
543 result = ActionModule.map_update_to_api({})
544
545 assert result == {}
546
547
548 class TestStatusMappings:
549 """Tests for status mapping constants.
550
551 Verify that STATUS_TO_API and STATUS_FROM_API are consistent inverses.
552 """
553
554 def test_status_mappings_are_inverses(self):
555 """Test that TO_API and FROM_API mappings are consistent inverses."""
556 for module_val, api_val in STATUS_TO_API.items():
557 assert STATUS_FROM_API[api_val] == module_val
558
559 def test_status_mappings_complete(self):
560 """Test that all expected status values are mapped."""
561 expected_statuses = ["unassigned", "new", "in_progress", "pending", "resolved", "closed"]
562
563 for status in expected_statuses:
564 assert status in STATUS_TO_API
565
566
567 class TestDispositionMappings:
568 """Tests for disposition mapping constants.
569
570 Verify that DISPOSITION_TO_API and DISPOSITION_FROM_API are consistent inverses.
571 """
572
573 def test_disposition_mappings_are_inverses(self):
574 """Test that TO_API and FROM_API mappings are consistent inverses."""
575 for module_val, api_val in DISPOSITION_TO_API.items():
576 assert DISPOSITION_FROM_API[api_val] == module_val
577
578 def test_disposition_mappings_complete(self):
579 """Test that all expected disposition values are mapped."""
580 expected_dispositions = [
581 "unassigned",
582 "true_positive",
583 "benign_positive",
584 "false_positive",
585 "false_positive_inaccurate_data",
586 "other",
587 "undetermined",
588 ]
589
590 for disposition in expected_dispositions:
591 assert disposition in DISPOSITION_TO_API
592
593
594 class TestUpdateKeyTransform:
595 """Tests for the ActionModule.UPDATE_KEY_TRANSFORM constant."""
596
597 def test_update_key_transform_contains_expected_keys(self):
598 """Test that UPDATE_KEY_TRANSFORM contains the correct updatable fields."""
599 expected = ["owner", "status", "urgency", "disposition"]
600
601 assert set(ActionModule.UPDATE_KEY_TRANSFORM.keys()) == set(expected)
602
603 def test_update_key_transform_excludes_create_only(self):
604 """Test that create-only fields are not in UPDATE_KEY_TRANSFORM."""
605 create_only = [
606 "title",
607 "description",
608 "security_domain",
609 "entity",
610 "entity_type",
611 "finding_score",
612 ]
613
614 for field in create_only:
615 assert field not in ActionModule.UPDATE_KEY_TRANSFORM
616
617 def test_update_key_transform_owner_maps_to_assignee(self):
618 """Test that owner is mapped to assignee for the API."""
619 assert ActionModule.UPDATE_KEY_TRANSFORM["owner"] == "assignee"