Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Infoblox manage session with cookies in integration storage #37240

Open
wants to merge 17 commits into
base: contrib/jesusgpo_contrib/infoblox-manage-session-cookies-in-context
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Packs/Infoblox/CONTRIBUTORS.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[
"Jesús García Potes <jesusgarciapotes95@gmail.com>"
]
71 changes: 69 additions & 2 deletions Packs/Infoblox/Integrations/Infoblox/Infoblox.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from enum import Enum, unique
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
from enum import Enum, unique


import json

''' IMPORTS '''
Expand All @@ -17,6 +19,7 @@
INTEGRATION_CONTEXT_NAME = 'Infoblox'
INTEGRATION_HOST_RECORDS_CONTEXT_NAME = "Host"
INTEGRATION_NETWORK_INFO_CONTEXT_KEY = "NetworkInfo"
INTEGRATION_AUTHORIZATION_EXCEPTION_MESSAGE = "Authorization error, check your credentials."

# COMMON RAW RESULT KEYS
INTEGRATION_COMMON_RAW_RESULT_REFERENCE_KEY = "_ref"
Expand Down Expand Up @@ -161,6 +164,69 @@ class IPv4AddressStatus(Enum):
USED = "USED"


def inject_cookies(func: Callable) -> Callable:
"""
Decorator to manage session persistence and handle authentication for API requests.

This decorator attempts to execute the provided function using existing session cookies
stored in the 'integration_context'. If no valid cookies are available, or if the existing
session is no longer valid the auth generate new cookies to save, bad credentials force the
storage clean.

The decorator handles saving and loading cookies between different executions, allowing for
session persistence across multiple API calls.

Args:
func (Callable): The API request function to be executed.

Raises:
DemistoException: If the API request fails.

Returns:
Callable: The result from executing 'func' with the provided arguments and keyword arguments.
"""

@wraps(wrapped=func)
def wrapper(client: "InfoBloxNIOSClient", *args, **kwargs):

def save_cookies_to_context(client: "InfoBloxNIOSClient") -> None:
cookies_dict = {}
for cookie in client._session.cookies:
cookies_dict[cookie.name] = {
'value': cookie.value,
'domain': cookie.domain,
'path': cookie.path
}
set_integration_context({'cookies': cookies_dict})

def load_cookies(client: "InfoBloxNIOSClient", cookies_dict: dict) -> None:
for name, cookie_data in cookies_dict.items():
client._session.cookies.set(
name,
cookie_data['value'],
domain=cookie_data['domain'],
path=cookie_data['path']
)

integration_context = get_integration_context()
if (
integration_context
and (context_cookies := integration_context.get("cookies"))
):
load_cookies(client, context_cookies)

try:
response = func(client, *args, **kwargs)
save_cookies_to_context(client)
return response
except DemistoException as error:
if error.message and error.message == INTEGRATION_AUTHORIZATION_EXCEPTION_MESSAGE:
set_integration_context({})
raise error

return wrapper


class InfoBloxNIOSClient(BaseClient):

REQUEST_PARAMS_RETURN_AS_OBJECT_KEY = '_return_as_object'
Expand All @@ -182,6 +248,7 @@ def __init__(self, base_url, verify=True, proxy=False, ok_codes=(), headers=None
super().__init__(base_url, verify, proxy, ok_codes, headers, auth)
self.params: dict[str, Any] = {self.REQUEST_PARAMS_RETURN_AS_OBJECT_KEY: '1'}

@inject_cookies
def _http_request( # type: ignore[override]
self, method, url_suffix, full_url=None, headers=None, auth=None,
json_data=None, params=None, data=None, files=None,
Expand Down Expand Up @@ -584,7 +651,7 @@ def get_network_info(
def parse_demisto_exception(error: DemistoException, field_in_error: str = 'text'):
err_msg = err_string = error.args[0]
if '[401]' in err_string:
err_msg = 'Authorization error, check your credentials.'
err_msg = INTEGRATION_AUTHORIZATION_EXCEPTION_MESSAGE
elif 'Failed to parse json object' in err_string:
err_msg = 'Cannot connect to Infoblox server, check your proxy and connection.'
elif 'Error in API call' in err_string:
Expand Down
2 changes: 1 addition & 1 deletion Packs/Infoblox/Integrations/Infoblox/Infoblox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,7 @@ script:
- contextPath: Infoblox.NetworkInfo.AdditionalFields
description: The additional fields for network.
type: Unknown
dockerimage: demisto/python3:3.11.10.115186
dockerimage: demisto/python3:3.11.10.116949
runonce: false
script: ''
subtype: python3
Expand Down
5 changes: 1 addition & 4 deletions Packs/Infoblox/ReleaseNotes/1_1_3.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,4 @@
#### Integrations

##### Infoblox
- Updated the Docker image to: *demisto/python3:3.11.10.115186*.



- Updated the Docker image to: *demisto/python3:3.11.10.115186*.
7 changes: 7 additions & 0 deletions Packs/Infoblox/ReleaseNotes/1_1_4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

#### Integrations

##### Infoblox

- Persisting Session with Cookies: Added logic to persist the session using cookies, enabling reusability of authentication tokens across requests. This prevents the need to log in on every API call, improving efficiency and reducing redundant login operations.
- Updated the Docker image to: *demisto/python3:3.11.10.116949*.
2 changes: 1 addition & 1 deletion Packs/Infoblox/pack_metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "Infoblox NIOS",
"description": "Infoblox is a comprehensive solution that consolidates DNS, DHCP, and IP address management into a single platform. It is designed to simplify network management by automating these critical functions and providing a centralized console for managing them.",
"support": "xsoar",
"currentVersion": "1.1.3",
"currentVersion": "1.1.4",
"author": "Cortex XSOAR",
"url": "https://www.paloaltonetworks.com/cortex",
"email": "",
Expand Down
Loading