Skip to content

Commit 669dcb6

Browse files
authored
Add Infinity Portal Application mismatch detection and fix request trace headers #10
2 parents e8fce43 + 66d67f7 commit 669dcb6

File tree

5 files changed

+56
-11
lines changed

5 files changed

+56
-11
lines changed

.flake8

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[flake8]
2+
max-line-length = 150
3+
exclude = .git,__pycache__,venv
4+
5+
per-file-ignores =
6+
# imported but unused
7+
__init__.py: F401

chkp_harmony_endpoint_management_sdk/core/session_manager.py

Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import json
22
import threading
33
import time
4-
from typing import Dict, Optional, Any, Callable
4+
from typing import Any
55
from unitsnet_py import Duration
66
from chkp_harmony_endpoint_management_sdk.classes import harmony_endpoint_saas_options
77
from chkp_harmony_endpoint_management_sdk.classes.harmony_endpoint_saas_options import HarmonyEndpointSaaSOptions
@@ -18,6 +18,7 @@
1818
import uuid
1919
from enum import Enum
2020
from urllib.parse import urlparse
21+
import jwt
2122
import requests
2223

2324
class WorkMode(Enum):
@@ -32,6 +33,8 @@ class WorkMode(Enum):
3233

3334
SOURCE_HEADER = 'harmony-endpoint-py-sdk'
3435

36+
VERIFY_CONTENT = False
37+
3538
class SessionManager:
3639
def __init__(self):
3740
self.__session_operations: SessionOperations = None
@@ -47,7 +50,7 @@ def __init__(self):
4750
The CI token expiration
4851
"""
4952

50-
self.__on_premise_portal_auth = OnPremisePortalAuth = None
53+
self.__on_premise_portal_auth: OnPremisePortalAuth = None
5154
"""
5255
The CI token expiration
5356
"""
@@ -189,9 +192,10 @@ def __perform_ci_login(self):
189192
if not response_json['success']:
190193
error_logger(f'Failed to login to CI GW for session "{self.__session_id}" url "{auth_url}", error payload: {response_json}')
191194
raise response_json
192-
logger(f'Preforming CI login to session id "{self.__session_id}" succeeded');
195+
logger(f'Preforming CI login to session id "{self.__session_id}" succeeded')
193196

194197
self.__infinity_portal_token = response_json['data']['token']
198+
self.__assert_token_is_for_correct_application(self.__infinity_portal_token)
195199
self.__next_ci_expiration = Duration.from_seconds(time.time()) + Duration.from_seconds(response_json['data']['expiresIn'])
196200
except Exception as e:
197201
error_logger(f'Failed to login to CI GW for session "{self.__session_id}" url "{auth_url}", error: {e}')
@@ -367,9 +371,42 @@ def __validate_premise_params(self, on_premise_portal_auth: OnPremisePortalAuth)
367371
message=message,
368372
error_scope=HarmonyErrorScope.INVALID_PARAMS,
369373
)
370-
374+
375+
def __assert_token_is_for_correct_application(self, bearer_token: str) -> None:
376+
if not bearer_token:
377+
error_logger('No bearer token was given. Ignoring. Requests may fail')
378+
return
379+
380+
try:
381+
# Token verification is NOT required here - this is just to determine whether
382+
# the Infinity Portal bearer is for the 'Endpoint' application
383+
decoded_token = jwt.decode(bearer_token, verify=VERIFY_CONTENT)
384+
if not decoded_token:
385+
error_logger('Bearer decoding yielded nothing. Ignoring. Requests may fail')
386+
return
387+
388+
app_id = decoded_token['appId']
389+
if not app_id:
390+
error_logger('An Application ID claim was not present in the bearer token. Ignoring. Requests may fail')
391+
return
392+
393+
endpoint_app_id = '12345678-8888-1234-1234-123456789123'
394+
if app_id != endpoint_app_id:
395+
error_logger(f"Target application is incorrect - expected '{endpoint_app_id}' but got '{app_id}'. Raising an error")
396+
raise HarmonyApiException(
397+
message=(
398+
"The provided API key must be for the 'Endpoint' service. Please refer to the documentation at "
399+
'https://app.swaggerhub.com/apis/Check-Point/web-mgmt-external-api-production for more details'
400+
),
401+
error_scope=HarmonyErrorScope.INVALID_PARAMS,
402+
)
403+
404+
except jwt.InvalidTokenError:
405+
error_logger('The given token could not be decoded. Ignoring. Requests may fail')
406+
return
407+
371408
def connect_cloud(self, infinity_portal_auth: InfinityPortalAuth, session_operations: SessionOperations):
372-
self.__work_mode = WorkMode.CLOUD
409+
self.__work_mode = WorkMode.CLOUD
373410
self.__sdk_connection_state = SDKConnectionState.CONNECTING
374411
self.__validate_cloud_params(infinity_portal_auth)
375412
self.__session_operations = session_operations
@@ -383,9 +420,8 @@ def connect_cloud(self, infinity_portal_auth: InfinityPortalAuth, session_operat
383420

384421
self.__activate_keep_alive()
385422

386-
387423
def connect_saas(self, infinity_portal_auth: InfinityPortalAuth, harmony_endpoint_saas_options: HarmonyEndpointSaaSOptions, session_operations: SessionOperations):
388-
self.__work_mode = WorkMode.SAAS
424+
self.__work_mode = WorkMode.SAAS
389425
self.__sdk_connection_state = SDKConnectionState.CONNECTING
390426
self.__validate_cloud_params(infinity_portal_auth)
391427
self.__harmony_endpoint_saas_options = harmony_endpoint_saas_options

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,6 @@ python-dateutil==2.8.2
88
python-dotenv==1.0.0
99
requests==2.31.0
1010
typing-extensions==4.8.0
11+
pyjwt==2.8.0
1112
unitsnet-py>=0.1.82
1213
urllib3==2.0.7

sdk_generator/templates/endpoint.handlebars

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ class BaseApi(api_client.Api):
349349
if prefix_separator_iterator is None:
350350
prefix_separator_iterator = parameter.get_prefix_separator_iterator()
351351

352-
serialized_data = parameter.serialize('{{operationId}}', prefix_separator_iterator)
352+
serialized_data = parameter.serialize('{{operationIdOriginal}}', prefix_separator_iterator)
353353
for serialized_value in serialized_data.values():
354354
used_path += serialized_value
355355

@@ -407,8 +407,8 @@ class BaseApi(api_client.Api):
407407
host = self._get_host_oapg('{{operationId}}', _servers, host_index)
408408
{{/if}}
409409

410-
_headers.add("x-mgmt-session-id", session_id)
411-
_headers.add("x-mgmt-request-id", request_id)
410+
_headers.add("x-mgmt-data-session-id", session_id)
411+
_headers.add("x-mgmt-data-request-id", request_id)
412412

413413
source_header = self.api_client.configuration.api_key['session']['source_header']
414414
if source_header:

setup.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,14 @@
1919
'python-dotenv==1.0.0',
2020
'requests==2.31.0',
2121
'typing-extensions==4.8.0',
22+
'pyjwt==2.8.0',
2223
'unitsnet-py>=0.1.82',
2324
'urllib3==2.0.7',
2425
]
2526

2627
setup_kwargs = {
2728
'name': "chkp-harmony-endpoint-management-sdk",
28-
'version': '1.1.35',
29+
'version': '1.1.37',
2930
'keywords': 'python, harmony, endpoint, sdk, checkpoint',
3031
'license': 'MIT',
3132
'description': 'Harmony Endpoint Official Python SDK',

0 commit comments

Comments
 (0)