| 1 |
# Copyright 2026 Red Hat Inc. |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
""" |
| 5 |
The action plugin file for splunk_finding_info |
| 6 |
""" |
| 7 |
|
| 8 |
from typing import Any, Dict, List, Optional |
| 9 |
|
| 10 |
from ansible.errors import AnsibleActionFail |
| 11 |
from ansible.module_utils.connection import Connection |
| 12 |
from ansible.module_utils.six.moves.urllib.parse import quote |
| 13 |
from ansible.plugins.action import ActionBase |
| 14 |
from ansible.utils.display import Display |
| 15 |
|
| 16 |
from ansible_collections.splunk.es.plugins.module_utils.finding import ( |
| 17 |
FINDING_KEY_TRANSFORM, |
| 18 |
build_finding_api_path, |
| 19 |
get_earliest_from_ref_id, |
| 20 |
map_finding_from_api, |
| 21 |
) |
| 22 |
from ansible_collections.splunk.es.plugins.module_utils.splunk import ( |
| 23 |
SplunkRequest, |
| 24 |
check_argspec, |
| 25 |
) |
| 26 |
from ansible_collections.splunk.es.plugins.module_utils.splunk_utils import ( |
| 27 |
DEFAULT_API_APP_SECURITY_SUITE, |
| 28 |
DEFAULT_API_NAMESPACE, |
| 29 |
DEFAULT_API_USER, |
| 30 |
) |
| 31 |
from ansible_collections.splunk.es.plugins.modules.splunk_finding_info import ( |
| 32 |
DOCUMENTATION, |
| 33 |
) |
| 34 |
|
| 35 |
|
| 36 |
# Initialize display for debug output |
| 37 |
display = Display() |
| 38 |
|
| 39 |
|
| 40 |
class ActionModule(ActionBase): |
| 41 |
"""Action module for querying Splunk ES findings.""" |
| 42 |
|
| 43 |
def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 44 |
super().__init__(*args, **kwargs) |
| 45 |
self._result = None |
| 46 |
self.key_transform = FINDING_KEY_TRANSFORM |
| 47 |
# API path components - will be set in run() from task args |
| 48 |
self.api_namespace = DEFAULT_API_NAMESPACE |
| 49 |
self.api_user = DEFAULT_API_USER |
| 50 |
self.api_app = DEFAULT_API_APP_SECURITY_SUITE |
| 51 |
self.api_object = None # Will be built dynamically |
| 52 |
|
| 53 |
def fail_json(self, msg: str) -> None: |
| 54 |
"""Raise an AnsibleActionFail with a cleaned up message. |
| 55 |
|
| 56 |
Args: |
| 57 |
msg: The message for the failure. |
| 58 |
|
| 59 |
Raises: |
| 60 |
AnsibleActionFail: Always raised with the provided message. |
| 61 |
""" |
| 62 |
msg = msg.replace("(basic.py)", self._task.action) |
| 63 |
raise AnsibleActionFail(msg) |
| 64 |
|
| 65 |
def _build_api_path(self) -> str: |
| 66 |
"""Build the findings API path from configured components. |
| 67 |
|
| 68 |
Returns: |
| 69 |
The complete findings API path. |
| 70 |
""" |
| 71 |
return build_finding_api_path(self.api_namespace, self.api_user, self.api_app) |
| 72 |
|
| 73 |
def _build_query_params(self) -> Optional[Dict[str, Any]]: |
| 74 |
"""Build query params dict with earliest/latest/limit if provided. |
| 75 |
|
| 76 |
Returns: |
| 77 |
Dict with query params if any are set, None otherwise. |
| 78 |
""" |
| 79 |
query_params: Dict[str, Any] = {} |
| 80 |
earliest = self._task.args.get("earliest") |
| 81 |
latest = self._task.args.get("latest") |
| 82 |
limit = self._task.args.get("limit") |
| 83 |
if earliest: |
| 84 |
query_params["earliest"] = earliest |
| 85 |
if latest: |
| 86 |
query_params["latest"] = latest |
| 87 |
if limit: |
| 88 |
query_params["limit"] = limit |
| 89 |
|
| 90 |
return query_params if query_params else None |
| 91 |
|
| 92 |
def get_finding_by_id(self, conn_request: SplunkRequest, ref_id: str) -> Dict[str, Any]: |
| 93 |
"""Get an existing finding by its reference ID. |
| 94 |
|
| 95 |
The time is extracted from the ref_id itself (format: uuid@@notable@@time{timestamp}). |
| 96 |
User-provided earliest/latest parameters are ignored when querying by ref_id. |
| 97 |
|
| 98 |
Args: |
| 99 |
conn_request: The SplunkRequest instance. |
| 100 |
ref_id: The reference ID (finding ID) to search for. |
| 101 |
|
| 102 |
Returns: |
| 103 |
The existing finding if found, empty dict otherwise. |
| 104 |
""" |
| 105 |
display.vv(f"splunk_finding_info: getting finding by ref_id: {ref_id}") |
| 106 |
|
| 107 |
query_params = {} |
| 108 |
earliest = get_earliest_from_ref_id(ref_id) |
| 109 |
if earliest: |
| 110 |
query_params["earliest"] = earliest |
| 111 |
display.vvv(f"splunk_finding_info: using earliest={earliest} from ref_id") |
| 112 |
|
| 113 |
query_dict = conn_request.get_by_path( |
| 114 |
f"{self.api_object}/{quote(ref_id)}", |
| 115 |
query_params=query_params if query_params else None, |
| 116 |
) |
| 117 |
|
| 118 |
if query_dict: |
| 119 |
display.vvv(f"splunk_finding_info: raw API response: {query_dict}") |
| 120 |
result = map_finding_from_api(query_dict, self.key_transform) |
| 121 |
result["ref_id"] = ref_id |
| 122 |
display.vv(f"splunk_finding_info: found finding: {result}") |
| 123 |
return result |
| 124 |
|
| 125 |
display.vv(f"splunk_finding_info: no finding found with ref_id: {ref_id}") |
| 126 |
return {} |
| 127 |
|
| 128 |
def get_all_findings(self, conn_request: SplunkRequest) -> List[Dict[str, Any]]: |
| 129 |
"""Get all findings from the API. |
| 130 |
|
| 131 |
Args: |
| 132 |
conn_request: The SplunkRequest instance. |
| 133 |
|
| 134 |
Returns: |
| 135 |
List of all findings. |
| 136 |
""" |
| 137 |
display.vv("splunk_finding_info: fetching all findings") |
| 138 |
|
| 139 |
query_params = self._build_query_params() |
| 140 |
display.vv(f"splunk_finding_info: query_params={query_params}") |
| 141 |
|
| 142 |
query_dict = conn_request.get_by_path(self.api_object, query_params=query_params) |
| 143 |
|
| 144 |
findings = [] |
| 145 |
if query_dict: |
| 146 |
display.vvv(f"splunk_finding_info: raw API response type: {type(query_dict)}") |
| 147 |
|
| 148 |
# v2 findings API returns findings under "items" key |
| 149 |
raw_findings = query_dict.get("items", []) |
| 150 |
|
| 151 |
for finding in raw_findings: |
| 152 |
if finding: |
| 153 |
mapped = map_finding_from_api(finding.copy(), self.key_transform) |
| 154 |
if mapped: |
| 155 |
findings.append(mapped) |
| 156 |
|
| 157 |
display.vv(f"splunk_finding_info: found {len(findings)} findings") |
| 158 |
|
| 159 |
return findings |
| 160 |
|
| 161 |
def filter_findings_by_title( |
| 162 |
self, |
| 163 |
findings: List[Dict[str, Any]], |
| 164 |
title: str, |
| 165 |
) -> List[Dict[str, Any]]: |
| 166 |
"""Filter findings by exact title match. |
| 167 |
|
| 168 |
Args: |
| 169 |
findings: List of findings to filter. |
| 170 |
title: The title to match. |
| 171 |
|
| 172 |
Returns: |
| 173 |
Filtered list of findings. |
| 174 |
""" |
| 175 |
display.vv(f"splunk_finding_info: filtering findings by title: {title}") |
| 176 |
|
| 177 |
filtered = [f for f in findings if f.get("title") == title] |
| 178 |
|
| 179 |
display.vv(f"splunk_finding_info: found {len(filtered)} findings with matching title") |
| 180 |
return filtered |
| 181 |
|
| 182 |
def run(self, tmp=None, task_vars=None): |
| 183 |
"""Execute the action module.""" |
| 184 |
self._supports_check_mode = True |
| 185 |
self._result = super().run(tmp, task_vars) |
| 186 |
|
| 187 |
display.v("splunk_finding_info: starting module execution") |
| 188 |
|
| 189 |
# Validate arguments |
| 190 |
if not check_argspec(self, self._result, DOCUMENTATION): |
| 191 |
display.v(f"splunk_finding_info: argument validation failed: {self._result.get('msg')}") |
| 192 |
return self._result |
| 193 |
|
| 194 |
# Get API path configuration from task args |
| 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 |
|
| 199 |
# Build the API path |
| 200 |
self.api_object = self._build_api_path() |
| 201 |
display.vv(f"splunk_finding_info: using API path: {self.api_object}") |
| 202 |
|
| 203 |
# Setup connection |
| 204 |
conn = Connection(self._connection.socket_path) |
| 205 |
conn_request = SplunkRequest( |
| 206 |
action_module=self, |
| 207 |
connection=conn, |
| 208 |
not_rest_data_keys=[ |
| 209 |
"ref_id", |
| 210 |
"title", |
| 211 |
"earliest", |
| 212 |
"latest", |
| 213 |
"limit", |
| 214 |
"api_namespace", |
| 215 |
"api_user", |
| 216 |
"api_app", |
| 217 |
], |
| 218 |
) |
| 219 |
|
| 220 |
# Get query parameters |
| 221 |
ref_id = self._task.args.get("ref_id") |
| 222 |
title = self._task.args.get("title") |
| 223 |
|
| 224 |
try: |
| 225 |
if ref_id: |
| 226 |
# Query specific finding by ref_id |
| 227 |
display.v(f"splunk_finding_info: querying by ref_id: {ref_id}") |
| 228 |
finding = self.get_finding_by_id(conn_request, ref_id) |
| 229 |
# Return as list for consistency |
| 230 |
self._result["findings"] = [finding] if finding else [] |
| 231 |
|
| 232 |
elif title: |
| 233 |
# Query all findings and filter by title |
| 234 |
display.v(f"splunk_finding_info: querying by title: {title}") |
| 235 |
all_findings = self.get_all_findings(conn_request) |
| 236 |
self._result["findings"] = self.filter_findings_by_title(all_findings, title) |
| 237 |
|
| 238 |
else: |
| 239 |
# Return all findings |
| 240 |
display.v("splunk_finding_info: querying all findings") |
| 241 |
self._result["findings"] = self.get_all_findings(conn_request) |
| 242 |
|
| 243 |
self._result["changed"] = False |
| 244 |
display.v(f"splunk_finding_info: returning {len(self._result['findings'])} finding(s)") |
| 245 |
|
| 246 |
except Exception as e: |
| 247 |
error_msg = str(e) |
| 248 |
if "404" in error_msg or "not found" in error_msg.lower(): |
| 249 |
# Handle 404 gracefully - return empty list |
| 250 |
self._result["changed"] = False |
| 251 |
self._result["findings"] = [] |
| 252 |
display.v("splunk_finding_info: no findings found (404)") |
| 253 |
else: |
| 254 |
self.fail_json( |
| 255 |
msg=f"Failed to query finding(s): {error_msg}", |
| 256 |
) |
| 257 |
|
| 258 |
return self._result |