Debian Codegraph @

ansible_collections/splunk/es/plugins/action/splunk_finding.py

raw
1 #
2 # Copyright 2026 Red Hat Inc.
3 #
4 # This file is part of Ansible
5 #
6 # Ansible is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Ansible is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 """
21 The action module for splunk_finding
22 """
23
24 from typing import Any
25
26 from ansible.errors import AnsibleActionFail
27 from ansible.module_utils.connection import Connection
28 from ansible.module_utils.six.moves.urllib.parse import quote
29 from ansible.plugins.action import ActionBase
30 from ansible.utils.display import Display
31
32 from ansible_collections.splunk.es.plugins.module_utils import dict_utils as utils
33 from ansible_collections.splunk.es.plugins.module_utils.finding import (
34 FINDING_KEY_TRANSFORM,
35 build_finding_api_path,
36 extract_notable_time,
37 get_earliest_from_ref_id,
38 map_finding_from_api,
39 )
40 from ansible_collections.splunk.es.plugins.module_utils.splunk import (
41 SplunkRequest,
42 check_argspec,
43 )
44 from ansible_collections.splunk.es.plugins.module_utils.splunk_utils import (
45 DEFAULT_API_APP,
46 DEFAULT_API_APP_SECURITY_SUITE,
47 DEFAULT_API_NAMESPACE,
48 DEFAULT_API_USER,
49 DISPOSITION_TO_API,
50 STATUS_TO_API,
51 )
52 from ansible_collections.splunk.es.plugins.modules.splunk_finding import DOCUMENTATION
53
54
55 # Initialize display for debug output
56 display = Display()
57
58
59 class ActionModule(ActionBase):
60 """Action module for managing Splunk ES findings."""
61
62 # Key transformation for update API: module param -> API param
63 UPDATE_KEY_TRANSFORM = {
64 "owner": "assignee",
65 "status": "status",
66 "urgency": "urgency",
67 "disposition": "disposition",
68 }
69
70 @staticmethod
71 def build_update_api_path(
72 ref_id: str,
73 namespace: str = DEFAULT_API_NAMESPACE,
74 user: str = DEFAULT_API_USER,
75 ) -> str:
76 """Build the investigations update API path.
77
78 The update API uses a fixed app (missioncontrol).
79
80 Args:
81 ref_id: The finding reference ID (e.g., 'uuid@@notable@@time{timestamp}').
82 namespace: The namespace portion of the path. Defaults to 'servicesNS'.
83 user: The user portion of the path. Defaults to 'nobody'.
84
85 Returns:
86 The investigations update API path (without query parameters).
87 """
88 return f"{namespace}/{user}/{DEFAULT_API_APP}/v1/investigations/{ref_id}"
89
90 @classmethod
91 def map_finding_to_api(
92 cls,
93 finding: dict[str, Any],
94 key_transform: dict[str, str] = None,
95 ) -> dict[str, Any]:
96 """Convert module params to API payload format.
97
98 Args:
99 finding: The finding parameters dictionary.
100 key_transform: Optional key transformation dict. Defaults to FINDING_KEY_TRANSFORM.
101
102 Returns:
103 Dictionary formatted for the Splunk findings API.
104 """
105 from ansible_collections.splunk.es.plugins.module_utils.splunk_utils import (
106 map_obj_to_params,
107 )
108
109 if key_transform is None:
110 key_transform = FINDING_KEY_TRANSFORM
111
112 # Use the helper from module_utils
113 res = map_obj_to_params(finding.copy(), key_transform)
114
115 # Add default values for API
116 res["app"] = DEFAULT_API_APP_SECURITY_SUITE
117 res["creator"] = "admin"
118
119 # Handle status conversion
120 if "status" in res and res["status"]:
121 res["status"] = STATUS_TO_API.get(res["status"], res["status"])
122
123 # Handle disposition conversion
124 if "disposition" in res and res["disposition"]:
125 res["disposition"] = DISPOSITION_TO_API.get(res["disposition"], res["disposition"])
126
127 # Handle custom fields - flatten them into the payload
128 if "fields" in finding and finding["fields"]:
129 for field in finding["fields"]:
130 if "name" in field and "value" in field:
131 res[field["name"]] = field["value"]
132
133 return res
134
135 @classmethod
136 def map_update_to_api(cls, finding: dict[str, Any]) -> dict[str, Any]:
137 """Convert module params to API payload format for updating findings.
138
139 Args:
140 finding: The finding parameters dictionary.
141
142 Returns:
143 Dictionary formatted for the Splunk investigations update API.
144 """
145 res = {}
146
147 for module_key, api_key in cls.UPDATE_KEY_TRANSFORM.items():
148 if module_key in finding and finding[module_key] is not None:
149 value = finding[module_key]
150
151 # Handle status conversion
152 if module_key == "status":
153 value = STATUS_TO_API.get(value, value)
154
155 # Handle disposition conversion
156 if module_key == "disposition":
157 value = DISPOSITION_TO_API.get(value, value)
158
159 res[api_key] = value
160
161 return res
162
163 def __init__(self, *args: Any, **kwargs: Any) -> None:
164 super().__init__(*args, **kwargs)
165 self._result = None
166 self.module_name = "finding"
167 self.key_transform = FINDING_KEY_TRANSFORM
168 self.api_namespace = DEFAULT_API_NAMESPACE
169 self.api_user = DEFAULT_API_USER
170 self.api_app = DEFAULT_API_APP_SECURITY_SUITE
171 self.api_object = None # Will be built dynamically
172
173 def fail_json(self, msg: str) -> None:
174 """Raise an AnsibleActionFail with a cleaned up message.
175
176 Args:
177 msg: The message for the failure.
178
179 Raises:
180 AnsibleActionFail: Always raised with the provided message.
181 """
182 msg = msg.replace("(basic.py)", self._task.action)
183 raise AnsibleActionFail(msg)
184
185 def _build_api_path(self) -> str:
186 """Build the findings API path from configured components.
187
188 Returns:
189 The complete findings API path.
190 """
191 return build_finding_api_path(self.api_namespace, self.api_user, self.api_app)
192
193 def _configure_api(self) -> None:
194 """Configure API path components from task arguments."""
195 self.api_namespace = self._task.args.get("api_namespace", DEFAULT_API_NAMESPACE)
196 self.api_user = self._task.args.get("api_user", DEFAULT_API_USER)
197 self.api_app = self._task.args.get("api_app", DEFAULT_API_APP_SECURITY_SUITE)
198 self.api_object = self._build_api_path()
199 display.vv(f"splunk_finding: using API path: {self.api_object}")
200
201 def _build_finding_params(self) -> dict[str, Any]:
202 """Build finding dictionary from task arguments.
203
204 Returns:
205 Dictionary containing finding parameters from task args.
206 """
207 finding = {}
208 title = self._task.args.get("title")
209 if title:
210 finding["title"] = title
211
212 param_keys = [
213 "description",
214 "security_domain",
215 "entity",
216 "entity_type",
217 "finding_score",
218 "owner",
219 "status",
220 "urgency",
221 "disposition",
222 "fields",
223 ]
224 for key in param_keys:
225 if value := self._task.args.get(key):
226 finding[key] = value
227
228 return finding
229
230 def _validate_create_params(self, finding: dict[str, Any]) -> str:
231 """Validate required parameters for creating a new finding.
232
233 Args:
234 finding: The finding parameters dictionary.
235
236 Returns:
237 Error message if validation fails, empty string if valid.
238 """
239 if "title" not in finding:
240 return "Missing required parameter: title"
241
242 required_fields = [
243 "description",
244 "security_domain",
245 "entity",
246 "entity_type",
247 "finding_score",
248 ]
249 missing = [f for f in required_fields if f not in finding]
250 if missing:
251 return f"Missing required parameters for creating finding: {', '.join(missing)}"
252
253 return ""
254
255 def _set_result_message(self, changed: bool) -> None:
256 """Set the appropriate result message based on check mode and changed status.
257
258 Args:
259 changed: Whether the operation resulted in changes.
260 """
261 if self._task.check_mode:
262 self._result["msg"] = (
263 "Check mode: would create/update finding"
264 if changed
265 else "Check mode: no changes required"
266 )
267 else:
268 self._result["msg"] = (
269 "Finding created/updated successfully" if changed else "No changes required"
270 )
271
272 def get_finding_by_id(self, conn_request: SplunkRequest, ref_id: str) -> dict[str, Any]:
273 """Get an existing finding by its reference ID.
274
275 Args:
276 conn_request: The SplunkRequest instance.
277 ref_id: The reference ID (finding ID) to search for.
278
279 Returns:
280 The existing finding if found, empty dict otherwise.
281 """
282 display.vv(f"splunk_finding: getting finding by ref_id: {ref_id}")
283
284 query_params = {}
285 earliest = get_earliest_from_ref_id(ref_id)
286 if earliest:
287 query_params["earliest"] = earliest
288 display.vvv(f"splunk_finding: using earliest={earliest} from ref_id")
289
290 query_dict = conn_request.get_by_path(
291 f"{self.api_object}/{quote(ref_id)}",
292 query_params=query_params if query_params else None,
293 )
294
295 search_result = {}
296
297 if query_dict:
298 display.vvv(f"splunk_finding: raw API response: {query_dict}")
299 search_result = map_finding_from_api(query_dict, self.key_transform)
300 search_result["ref_id"] = ref_id
301 display.vv(f"splunk_finding: found existing finding: {search_result}")
302 else:
303 display.vv(f"splunk_finding: no finding found with ref_id: {ref_id}")
304
305 return search_result
306
307 def _post_finding(
308 self,
309 conn_request: SplunkRequest,
310 finding: dict[str, Any],
311 ) -> dict[str, Any]:
312 """Send finding payload to API for creating a new finding.
313
314 Args:
315 conn_request: The SplunkRequest instance.
316 finding: The finding parameters.
317
318 Returns:
319 Parsed finding from API response.
320 """
321 payload = self.map_finding_to_api(finding, self.key_transform)
322
323 display.vvv(f"splunk_finding: posting to {self.api_object}")
324 display.vvv(f"splunk_finding: payload: {payload}")
325 api_response = conn_request.create_update(self.api_object, data=payload, json_payload=True)
326
327 after = {}
328 if api_response:
329 display.vvv(f"splunk_finding: API response: {api_response}")
330 after = map_finding_from_api(api_response, self.key_transform)
331
332 return after
333
334 def _post_update(
335 self,
336 conn_request: SplunkRequest,
337 ref_id: str,
338 finding: dict[str, Any],
339 ) -> dict[str, Any]:
340 """Send finding payload to API and return parsed response.
341
342 Args:
343 conn_request: The SplunkRequest instance.
344 ref_id: The reference ID of the finding to update.
345 finding: The finding parameters to update.
346
347 Returns:
348 The updated finding parameters.
349 """
350 # Build the update API path
351 update_url = self.build_update_api_path(ref_id, self.api_namespace, self.api_user)
352
353 # Extract notable_time from ref_id for query param
354 notable_time = extract_notable_time(ref_id)
355 if not notable_time:
356 self.fail_json(
357 msg=f"Cannot extract notable_time from ref_id '{ref_id}'. "
358 "Expected format: uuid@@notable@@time{{timestamp}}",
359 )
360
361 query_params = {"notable_time": notable_time}
362
363 # Map to update API payload format (owner -> assignee, etc.)
364 payload = self.map_update_to_api(finding)
365
366 display.vvv(f"splunk_finding: posting update to {update_url}")
367 display.vvv(f"splunk_finding: query_params: {query_params}")
368 display.vvv(f"splunk_finding: update payload: {payload}")
369
370 api_response = conn_request.create_update(
371 update_url,
372 data=payload,
373 query_params=query_params,
374 json_payload=True,
375 )
376
377 display.vvv(f"splunk_finding: update API response: {api_response}")
378
379 # Return the expected state after update
380 # The investigations API may not return full finding data
381 return finding
382
383 def create_finding(
384 self,
385 conn_request: SplunkRequest,
386 finding: dict[str, Any],
387 ) -> tuple[dict[str, Any], bool]:
388 """Create a new finding.
389
390 Args:
391 conn_request: The SplunkRequest instance.
392 finding: The finding parameters.
393
394 Returns:
395 Tuple of (result_dict, changed).
396 """
397 title = finding.get("title", "")
398 display.v(f"splunk_finding: creating new finding with title: {title}")
399
400 if self._task.check_mode:
401 display.v("splunk_finding: check mode - would create finding")
402 return {"before": None, "after": finding}, True
403
404 want_conf = utils.remove_empties(finding)
405 after = self._post_finding(conn_request, want_conf)
406
407 display.v("splunk_finding: created finding successfully")
408 return {"before": None, "after": after}, True
409
410 def update_finding(
411 self,
412 conn_request: SplunkRequest,
413 ref_id: str,
414 finding: dict[str, Any],
415 ) -> tuple[dict[str, Any], bool]:
416 """Update an existing finding by reference ID.
417
418 Args:
419 conn_request: The SplunkRequest instance.
420 ref_id: The reference ID of the finding to update.
421 finding: The finding parameters.
422
423 Returns:
424 Tuple of (result_dict, changed).
425 """
426 display.v(f"splunk_finding: updating finding with ref_id: {ref_id}")
427
428 # Validate that only updatable fields are provided
429 non_updatable = [k for k in finding if k not in self.UPDATE_KEY_TRANSFORM]
430 if non_updatable:
431 display.vv(f"splunk_finding: ignoring non-updatable fields: {non_updatable}")
432 # Filter to only updatable fields
433 finding = {k: v for k, v in finding.items() if k in self.UPDATE_KEY_TRANSFORM}
434
435 if not finding:
436 display.v("splunk_finding: no updatable fields provided")
437 return {
438 "before": None,
439 "after": None,
440 "error": "No updatable fields provided. Only owner, status, urgency, and disposition can be updated.",
441 }, False
442
443 # Get existing finding to verify it exists
444 have_conf = self.get_finding_by_id(conn_request, ref_id)
445
446 if not have_conf:
447 display.v(f"splunk_finding: finding with ref_id {ref_id} not found")
448 return {
449 "before": None,
450 "after": None,
451 "error": f"Finding with ref_id '{ref_id}' not found",
452 }, False
453
454 display.vv(f"splunk_finding: existing finding found: {have_conf}")
455
456 # Compare to detect changes (only for updatable fields)
457 want_conf = utils.remove_empties(finding)
458 have_updatable = {k: have_conf.get(k) for k in self.UPDATE_KEY_TRANSFORM if k in have_conf}
459 diff = utils.dict_diff(have_updatable, want_conf)
460
461 if diff:
462 display.vv(f"splunk_finding: changes detected: {diff}")
463
464 # Check mode - don't make actual changes
465 if self._task.check_mode:
466 display.v("splunk_finding: check mode - would update finding")
467 after_conf = have_conf.copy()
468 after_conf.update(want_conf)
469 return {"before": have_conf, "after": after_conf}, True
470
471 # Use the investigations API for updates
472 self._post_update(conn_request, ref_id, want_conf)
473
474 # Build expected after state
475 after_conf = have_conf.copy()
476 after_conf.update(want_conf)
477
478 display.v("splunk_finding: updated finding successfully")
479 return {"before": have_conf, "after": after_conf}, True
480 else:
481 display.v("splunk_finding: no changes needed")
482 return {"before": have_conf, "after": have_conf}, False
483
484 def _handle_update(
485 self,
486 conn_request: SplunkRequest,
487 ref_id: str,
488 finding: dict[str, Any],
489 ) -> bool:
490 """Handle update operation for an existing finding.
491
492 Args:
493 conn_request: The SplunkRequest instance.
494 ref_id: The reference ID of the finding to update.
495 finding: The finding parameters.
496
497 Returns:
498 True if operation completed successfully, False if error occurred.
499 """
500 display.v("splunk_finding: ref_id provided, will update existing finding")
501 finding_result, changed = self.update_finding(conn_request, ref_id, finding)
502
503 if "error" in finding_result:
504 self._result["failed"] = True
505 self._result["msg"] = finding_result["error"]
506 return False
507
508 self._result[self.module_name] = finding_result
509 self._result["changed"] = changed
510 return True
511
512 def _handle_create(self, conn_request: SplunkRequest, finding: dict[str, Any]) -> bool:
513 """Handle create operation for a new finding.
514
515 Args:
516 conn_request: The SplunkRequest instance.
517 finding: The finding parameters.
518
519 Returns:
520 True if operation completed successfully, False if validation failed.
521 """
522 display.v("splunk_finding: no ref_id provided, will create new finding")
523
524 error_msg = self._validate_create_params(finding)
525 if error_msg:
526 self._result["failed"] = True
527 self._result["msg"] = error_msg
528 display.v(f"splunk_finding: {error_msg}")
529 return False
530
531 finding_result, changed = self.create_finding(conn_request, finding)
532 self._result[self.module_name] = finding_result
533 self._result["changed"] = changed
534 return True
535
536 def run(self, tmp=None, task_vars=None):
537 """Execute the action module."""
538 self._supports_check_mode = True
539 self._result = super().run(tmp, task_vars)
540
541 display.v("splunk_finding: starting module execution")
542
543 # Validate arguments
544 if not check_argspec(self, self._result, DOCUMENTATION):
545 display.v(f"splunk_finding: argument validation failed: {self._result.get('msg')}")
546 return self._result
547
548 # Initialize result structure
549 self._result[self.module_name] = {}
550 self._result["changed"] = False
551
552 self._configure_api()
553
554 ref_id = self._task.args.get("ref_id")
555 finding = self._build_finding_params()
556
557 display.vv(f"splunk_finding: finding parameters: {finding}")
558 display.vv(f"splunk_finding: ref_id: {ref_id}")
559
560 # Setup connection
561 conn = Connection(self._connection.socket_path)
562 conn_request = SplunkRequest(
563 action_module=self,
564 connection=conn,
565 not_rest_data_keys=["ref_id", "api_namespace", "api_user", "api_app"],
566 )
567
568 if ref_id:
569 if not self._handle_update(conn_request, ref_id, finding):
570 return self._result
571 else:
572 if not self._handle_create(conn_request, finding):
573 return self._result
574
575 self._set_result_message(self._result["changed"])
576 display.v(f"splunk_finding: module completed with changed={self._result['changed']}")
577 return self._result