Skip to content

Commit c819327

Browse files
committed
SLK-103546 - Fix PR Comments
* return status, data from http response instead of object * do not log response data for token api * fix response status and data parsing
1 parent 4a28ad8 commit c819327

File tree

3 files changed

+92
-132
lines changed

3 files changed

+92
-132
lines changed

modules/single/modules/lambda/functions/create_cspm_key.py

Lines changed: 31 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,15 @@ def http_request(url, headers, method, body=None):
4848

4949
http = urllib3.PoolManager(cert_reqs='CERT_NONE')
5050

51-
try:
52-
response = http.request(method, url, body=body, headers=headers)
53-
response_data = response.data.decode('utf-8') if response.data else ''
51+
response = http.request(method, url, body=body, headers=headers)
52+
response_data = response.data.decode('utf-8') if response.data else ''
53+
54+
# Don't log response body for /v2/tokens endpoint to avoid exposing bearer tokens
55+
if '/v2/tokens' in url and response.status == 200:
56+
print(f"HTTP response: {response.status} {response.reason}")
57+
else:
5458
print(f"HTTP response: {response.status} {response.reason} - {response_data}")
55-
return response
56-
except Exception as e:
57-
print('Failed to send http request; {}'.format(e))
58-
return None
59+
return response.status, response_data
5960

6061

6162
def get_bearer_token(cspm_base_url, api_key, aqua_secret, tstmp):
@@ -75,32 +76,22 @@ def get_bearer_token(cspm_base_url, api_key, aqua_secret, tstmp):
7576
"Content-Type": "application/json"
7677
}
7778

78-
response = http_request(tokens_url, headers, method, body)
79-
if response is None:
80-
raise Exception("Failed to get Bearer token: HTTP request failed")
81-
82-
if response.status not in [200, 201]:
83-
raise Exception(f"Failed to get Bearer token: {response.data.decode('utf-8')}")
84-
85-
json_object = json.loads(response.data.decode('utf-8'))
86-
if json_object.get('status') != 200:
87-
error_msg = json_object.get('message', 'Unknown error')
88-
raise Exception(f"Tokens API failed: {error_msg}")
79+
status, data = http_request(tokens_url, headers, method, body)
80+
if status not in [200, 201]:
81+
raise Exception(f"Failed to get Bearer token: {data}")
8982

83+
json_object = json.loads(data)
9084
return json_object['data']
9185

9286

9387
def cspm_request_with_fallback(cspm_base_url, path, headers, method, body, api_key, aqua_secret, tstmp):
9488
"""Make CSPM request with automatic token authentication fallback"""
9589
url = cspm_base_url + path
96-
response = http_request(url, headers, method, body if body else '')
97-
98-
if response is None:
99-
raise ValueError("HTTP request failed")
90+
original_status, original_data = http_request(url, headers, method, body if body else '')
10091

10192
# Attempt fallback for 401/403 errors
102-
if response.status in [401, 403]:
103-
print(f"Token fallback: API key authentication failed with status {response.status}, attempting Bearer token fallback")
93+
if original_status in [401, 403]:
94+
print(f"Token fallback: API key authentication failed with status {original_status}, attempting Bearer token fallback")
10495
try:
10596
bearer_token = get_bearer_token(cspm_base_url, api_key, aqua_secret, tstmp)
10697

@@ -110,27 +101,29 @@ def cspm_request_with_fallback(cspm_base_url, path, headers, method, body, api_k
110101
"Content-Type": "application/json"
111102
}
112103

113-
response = http_request(url, fallback_headers, method, body if body else '')
114-
if response and response.status in [200, 201]:
104+
fallback_status, fallback_data = http_request(url, fallback_headers, method, body if body else '')
105+
if fallback_status in [200, 201]:
115106
print("Token fallback: Bearer token authentication succeeded")
116-
elif response:
117-
print(f"Token fallback: Bearer token authentication failed with status {response.status}")
107+
return fallback_status, fallback_data
108+
else:
109+
print(f"Token fallback: Bearer token authentication failed with status {fallback_status}")
118110
except Exception as e:
119111
print(f"Token fallback failed: {e}")
120112
# Return original response if fallback fails
121113

122-
return response
114+
return original_status, original_data
123115

124116

125117
def get_cspm_key_id(aqua_api_key, aqua_secret, cspm_url, role_arn):
126118
tstmp = str(int(time.time() * 1000))
127119
sig = get_signature(aqua_secret, tstmp, "/v2/keys", "GET", '')
128120
headers = {"X-API-Key": aqua_api_key, "X-Signature": sig, "X-Timestamp": tstmp}
129121

130-
response = cspm_request_with_fallback(cspm_url, "/v2/keys", headers, "GET", '', aqua_api_key, aqua_secret, tstmp)
131-
json_object = json.loads(response.data)
132-
if response.status not in (200, 201):
133-
raise ValueError(f"Failed to get cspm key id for {role_arn}: {response.message}")
122+
status, data = cspm_request_with_fallback(cspm_url, "/v2/keys", headers, "GET", '', aqua_api_key, aqua_secret, tstmp)
123+
if status not in (200, 201):
124+
raise ValueError(f"Failed to get cspm key id for {role_arn}: {data}")
125+
126+
json_object = json.loads(data)
134127

135128
for key in json_object['data']:
136129
if key['role_arn'] == role_arn:
@@ -161,13 +154,13 @@ def create_cspm_key(cspm_url, aqua_api_key, aqua_secret, role_arn, external_id,
161154
"X-Timestamp": tstmp
162155
}
163156

164-
response = cspm_request_with_fallback(cspm_url, '/v2/keys', headers, "POST", jsonbody, aqua_api_key, aqua_secret, tstmp)
165-
if response.status not in (200, 201):
166-
raise Exception("Failed to create cspm key id", response.data.decode("utf-8"))
157+
status, data = cspm_request_with_fallback(cspm_url, '/v2/keys', headers, "POST", jsonbody, aqua_api_key, aqua_secret, tstmp)
158+
if status not in (200, 201):
159+
raise Exception("Failed to create cspm key id", data)
167160

168-
print(f'CSPM response: {response.data.decode("utf-8")}')
161+
print(f'CSPM response: {data}')
169162
is_already_cspm_client = False
170-
if response.status == 200:
163+
if status == 200:
171164
is_already_cspm_client = True
172165

173166
return is_already_cspm_client

modules/single/modules/lambda/functions/generate_external_id.py

Lines changed: 28 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,15 @@ def http_request(url, headers, method, body=None):
3737

3838
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED')
3939

40-
try:
41-
response = http.request(method, url, body=body, headers=headers)
42-
response_data = response.data.decode('utf-8') if response.data else ''
40+
response = http.request(method, url, body=body, headers=headers)
41+
response_data = response.data.decode('utf-8') if response.data else ''
42+
43+
# Don't log response body for /v2/tokens endpoint to avoid exposing bearer tokens
44+
if '/v2/tokens' in url and response.status == 200:
45+
print(f"HTTP response: {response.status} {response.reason}")
46+
else:
4347
print(f"HTTP response: {response.status} {response.reason} - {response_data}")
44-
return response
45-
except Exception as e:
46-
print('Failed to send http request; {}'.format(e))
47-
return None
48+
return response.status, response_data
4849

4950

5051
def get_bearer_token(cspm_base_url, api_key, aqua_secret, tstmp):
@@ -64,30 +65,22 @@ def get_bearer_token(cspm_base_url, api_key, aqua_secret, tstmp):
6465
"Content-Type": "application/json"
6566
}
6667

67-
response = http_request(tokens_url, headers, method, body)
68-
69-
if response.status not in [200, 201]:
70-
raise Exception(f"Failed to get Bearer token: {response.data.decode('utf-8')}")
71-
72-
json_object = json.loads(response.data.decode('utf-8'))
73-
if json_object.get('status') != 200:
74-
error_msg = json_object.get('message', 'Unknown error')
75-
raise Exception(f"Tokens API failed: {error_msg}")
68+
status, data = http_request(tokens_url, headers, method, body)
69+
if status not in [200, 201]:
70+
raise Exception(f"Failed to get Bearer token: {data}")
7671

72+
json_object = json.loads(data)
7773
return json_object['data']
7874

7975

8076
def cspm_request_with_fallback(cspm_base_url, path, headers, method, body, api_key, aqua_secret, tstmp):
8177
"""Make CSPM request with automatic token authentication fallback"""
8278
url = cspm_base_url + path
83-
response = http_request(url, headers, method, body if body else '')
84-
85-
if response is None:
86-
raise ValueError("HTTP request failed")
79+
original_status, original_data = http_request(url, headers, method, body if body else '')
8780

8881
# Attempt fallback for 401/403 errors
89-
if response.status in [401, 403]:
90-
print(f"Token fallback: API key authentication failed with status {response.status}, attempting Bearer token fallback")
82+
if original_status in [401, 403]:
83+
print(f"Token fallback: API key authentication failed with status {original_status}, attempting Bearer token fallback")
9184
try:
9285
bearer_token = get_bearer_token(cspm_base_url, api_key, aqua_secret, tstmp)
9386

@@ -97,23 +90,17 @@ def cspm_request_with_fallback(cspm_base_url, path, headers, method, body, api_k
9790
"Content-Type": "application/json"
9891
}
9992

100-
response = http_request(url, fallback_headers, method, body if body else '')
101-
if response and response.status in [200, 201]:
93+
fallback_status, fallback_data = http_request(url, fallback_headers, method, body if body else '')
94+
if fallback_status in [200, 201]:
10295
print("Token fallback: Bearer token authentication succeeded")
103-
elif response:
104-
print(f"Token fallback: Bearer token authentication failed with status {response.status}")
96+
return fallback_status, fallback_data
97+
else:
98+
print(f"Token fallback: Bearer token authentication failed with status {fallback_status}")
10599
except Exception as e:
106100
print(f"Token fallback failed: {e}")
107-
# Continue with original response if fallback fails
101+
# Return original response if fallback fails
108102

109-
# Parse response to match existing http_request behavior
110-
try:
111-
data = json.loads(response.data.decode('utf-8'))
112-
except Exception as e:
113-
print("warning: {}".format(e))
114-
data = {}
115-
116-
return data
103+
return original_status, original_data
117104

118105

119106
def generate_external_id(cspm_url, ac_url, aqua_api_key, aqua_secret, aws_account_id):
@@ -125,8 +112,12 @@ def generate_external_id(cspm_url, ac_url, aqua_api_key, aqua_secret, aws_accoun
125112
sig = get_signature(aqua_secret, tstmp, path, method, '')
126113
headers = {"X-API-Key": aqua_api_key, "X-Signature": sig, "X-Timestamp": tstmp}
127114

128-
response = cspm_request_with_fallback(cspm_url, path, headers, method, '', aqua_api_key, aqua_secret, tstmp)
129-
if response.get('status', 0) != 200 and response.get('status', 0) != 201 or not response.get('data'):
115+
status, data = cspm_request_with_fallback(cspm_url, path, headers, method, '', aqua_api_key, aqua_secret, tstmp)
116+
if status not in [200, 201]:
117+
raise Exception("failed to generate external id; {}".format(data))
118+
119+
response = json.loads(data)
120+
if not response.get('data'):
130121
raise Exception("failed to generate external id; {}".format(response.get('message', 'Internal server error')))
131122

132123
return response['data'][0]['generated_id']

modules/single/modules/trigger/trigger-aws.py

Lines changed: 33 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -57,25 +57,21 @@ def http_request(url, headers, method, body=None):
5757

5858
log(f"HTTP request: {method} {url}")
5959

60-
try:
61-
conn = http.client.HTTPSConnection(hostname, context=ssl._create_unverified_context())
62-
conn.request(method, path, body=body, headers=headers)
60+
conn = http.client.HTTPSConnection(hostname, context=ssl._create_unverified_context())
61+
conn.request(method, path, body=body, headers=headers)
6362

64-
response = conn.getresponse()
65-
response_data = response.read().decode("utf-8")
63+
response = conn.getresponse()
64+
response_data = response.read().decode("utf-8")
6665

67-
conn.close()
66+
conn.close()
6867

68+
# Don't log response body for /v2/tokens endpoint to avoid exposing bearer tokens
69+
if '/v2/tokens' in url and response.status == 200:
70+
log(f"HTTP response: {response.status} {response.reason}")
71+
else:
6972
log(f"HTTP response: {response.status} {response.reason} - {response_data}")
7073

71-
return {
72-
"status": response.status,
73-
"reason": response.reason,
74-
"data": response_data
75-
}
76-
except Exception as e:
77-
log(f"Failed to send HTTP request: {e}")
78-
return None
74+
return response.status, response_data
7975

8076

8177
def get_bearer_token(cspm_base_url, api_key, aqua_secret, tstmp):
@@ -95,51 +91,42 @@ def get_bearer_token(cspm_base_url, api_key, aqua_secret, tstmp):
9591
"Content-Type": "application/json"
9692
}
9793

98-
response = http_request(tokens_url, headers, method, body)
99-
if response is None:
100-
raise Exception("Failed to get Bearer token: HTTP request failed")
101-
102-
if response["status"] not in [200, 201]:
103-
raise Exception(f"Failed to get Bearer token: {response['data']}")
104-
105-
json_object = json.loads(response["data"].strip())
106-
if json_object.get('status') != 200:
107-
error_msg = json_object.get('message', 'Unknown error')
108-
raise Exception(f"Tokens API failed: {error_msg}")
94+
status, data = http_request(tokens_url, headers, method, body)
95+
if status not in [200, 201]:
96+
raise Exception(f"Failed to get Bearer token: {data}")
10997

98+
json_object = json.loads(data.strip())
11099
return json_object['data']
111100

112101

113102
def cspm_request_with_fallback(cspm_base_url, path, headers, method, body, api_key, aqua_secret, tstmp):
114103
"""Make CSPM request with automatic token authentication fallback"""
115104
url = cspm_base_url + path
116-
response = http_request(url, headers, method, body)
117-
118-
if response is None:
119-
raise ValueError("HTTP request failed")
105+
original_status, original_data = http_request(url, headers, method, body)
120106

121107
# Attempt fallback for 401/403 errors
122-
if response["status"] in [401, 403]:
123-
log(f"Token fallback: API key authentication failed with status {response['status']}, attempting Bearer token fallback")
108+
if original_status in [401, 403]:
109+
log(f"Token fallback: API key authentication failed with status {original_status}, attempting Bearer token fallback")
124110
try:
125111
bearer_token = get_bearer_token(cspm_base_url, api_key, aqua_secret, tstmp)
126-
112+
127113
fallback_headers = {
128114
"Authorization": f"Bearer {bearer_token}",
129115
"X-Timestamp": tstmp,
130116
"Content-Type": "application/json"
131117
}
132-
133-
response = http_request(url, fallback_headers, method, body)
134-
if response["status"] in [200, 201]:
118+
119+
fallback_status, fallback_data = http_request(url, fallback_headers, method, body)
120+
if fallback_status in [200, 201]:
135121
log("Token fallback: Bearer token authentication succeeded")
122+
return fallback_status, fallback_data
136123
else:
137-
log(f"Token fallback: Bearer token authentication failed with status {response['status']}")
124+
log(f"Token fallback: Bearer token authentication failed with status {fallback_status}")
138125
except Exception as e:
139126
log(f"Token fallback failed: {e}")
140127
# Return original response if fallback fails
141128

142-
return response
129+
return original_status, original_data
143130

144131

145132
def get_cspm_key_id(aqua_api_key, aqua_secret, cspm_url, role_arn):
@@ -152,15 +139,12 @@ def get_cspm_key_id(aqua_api_key, aqua_secret, cspm_url, role_arn):
152139
"X-Timestamp": tstmp
153140
}
154141

155-
response = cspm_request_with_fallback(cspm_url, "/v2/keys", headers, "GET", '', aqua_api_key, aqua_secret, tstmp)
142+
status, data = cspm_request_with_fallback(cspm_url, "/v2/keys", headers, "GET", '', aqua_api_key, aqua_secret, tstmp)
156143

157-
if response is None:
158-
raise ValueError(f"HTTP request failed while getting CSPM key ID for {role_arn}")
144+
if status not in [200, 201]:
145+
raise ValueError(f"Failed to get CSPM key ID: {data}")
159146

160-
if response["status"] not in [200, 201]:
161-
raise ValueError(f"Failed to get CSPM key ID: {response['data']}")
162-
163-
json_object = json.loads(response["data"].strip())
147+
json_object = json.loads(data.strip())
164148
for key in json_object['data']:
165149
if key['role_arn'] == role_arn:
166150
return key['id']
@@ -213,12 +197,8 @@ def trigger_discovery():
213197
"X-Timestamp": tstmp
214198
}
215199

216-
response = http_request(url=f"{ac_url}/discover/{cloud}", headers=headers, method="POST", body=body)
217-
218-
if response is None:
219-
raise ValueError("Discovery request failed")
220-
221-
return response
200+
status, data = http_request(url=f"{ac_url}/discover/{cloud}", headers=headers, method="POST", body=body)
201+
return {"status": status, "data": data}
222202

223203

224204
def update_credentials():
@@ -233,7 +213,7 @@ def update_credentials():
233213

234214
cspm_headers = {"X-API-Key": aqua_api_key, "X-Signature": cspm_sig, "X-Timestamp": tstmp}
235215

236-
cspm_response = cspm_request_with_fallback(cspm_url, f"/v2/keys/{cspm_key_id}", cspm_headers, "PUT", cspm_body, aqua_api_key, aqua_secret, tstmp)
216+
cspm_status, cspm_data = cspm_request_with_fallback(cspm_url, f"/v2/keys/{cspm_key_id}", cspm_headers, "PUT", cspm_body, aqua_api_key, aqua_secret, tstmp)
237217

238218
ac_body = json.dumps({
239219
"cloud_account_id": aws_account_id,
@@ -250,12 +230,8 @@ def update_credentials():
250230

251231
ac_headers = {"X-API-Key": aqua_api_key, "X-Authenticate-Api-Key-Signature": ac_sig, "X-Tokens-Signature": tokens_signature, "X-Timestamp": tstmp}
252232

253-
ac_response = http_request(ac_url + f"/discover/update-credentials/{cloud}", ac_headers, "PUT", ac_body)
254-
255-
if ac_response is None:
256-
raise ValueError("Update credentials request failed")
257-
258-
return cspm_response
233+
ac_status, ac_data = http_request(ac_url + f"/discover/update-credentials/{cloud}", ac_headers, "PUT", ac_body)
234+
return {"status": cspm_status, "data": cspm_data}
259235

260236

261237
def main():

0 commit comments

Comments
 (0)