Newer
Older
import os
import logging
import urllib3
import requests
import json
import warnings
import jwt
from OpenSSL import crypto
from jwt.exceptions import InvalidTokenError
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
from requests.exceptions import RequestsDependencyWarning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
warnings.filterwarnings("ignore", category=RequestsDependencyWarning)
# noqa: E501
# Basic configuration of the logger functionality
log_path = 'logs/sdk_logs.log'
log_dir = os.path.dirname(log_path)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
logging.basicConfig(
level=logging.NOTSET, # Minimum severity level to log
# Log message format
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_path), # Log to a file
logging.StreamHandler() # Also display in the console
]
)
class capif_logging_feature:
def __init__(self, config_file: str):
"""
Initializes the CAPIFProvider connector with the parameters specified in the configuration file.
"""
# Load configuration from file if necessary
config_file = os.path.abspath(config_file)
self.config_path = os.path.dirname(config_file)+"/"
config = self.__load_config_file(config_file)
debug_mode = os.getenv('DEBUG_MODE', config.get('debug_mode', 'False')).strip().lower()
if debug_mode == "false":
debug_mode = False
else:
debug_mode = True
# Initialize logger for this class
self.logger = logging.getLogger(self.__class__.__name__)
if debug_mode:
self.logger.setLevel(logging.DEBUG)
else:
self.logger.setLevel(logging.WARNING)
# Set logging level for urllib based on debug_mode
urllib_logger = logging.getLogger("urllib3")
if not debug_mode:
urllib_logger.setLevel(logging.WARNING)
else:
urllib_logger.setLevel(logging.DEBUG)
try:
# Retrieve provider configuration from JSON or environment variables
provider_config = config.get('provider', {})
provider_general_folder = os.path.abspath(
os.getenv('PROVIDER_FOLDER', provider_config.get('provider_folder', '')).strip())
capif_host = os.getenv('CAPIF_HOST', config.get('capif_host', '')).strip()
capif_register_host = os.getenv('REGISTER_HOST', config.get('register_host', '')).strip()
capif_https_port = str(os.getenv('CAPIF_HTTPS_PORT', config.get('capif_https_port', '')).strip())
capif_register_port = str(os.getenv('CAPIF_REGISTER_PORT', config.get('capif_register_port', '')).strip())
capif_provider_username = os.getenv('CAPIF_USERNAME', config.get('capif_username', '')).strip()
capif_provider_password = os.getenv('CAPIF_PASSWORD', config.get('capif_password', '')).strip()
# Get CSR (Certificate Signing Request) details from config or environment variables
cert_generation = provider_config.get('cert_generation', {})
csr_common_name = os.getenv('PROVIDER_CSR_COMMON_NAME', cert_generation.get('csr_common_name', '')).strip()
csr_organizational_unit = os.getenv('PROVIDER_CSR_ORGANIZATIONAL_UNIT', cert_generation.get('csr_organizational_unit', '')).strip()
csr_organization = os.getenv('PROVIDER_CSR_ORGANIZATION', cert_generation.get('csr_organization', '')).strip()
csr_locality = os.getenv('PROVIDER_CSR_LOCALITY', cert_generation.get('csr_locality', '')).strip()
csr_state_or_province_name = os.getenv('PROVIDER_CSR_STATE_OR_PROVINCE_NAME', cert_generation.get('csr_state_or_province_name', '')).strip()
csr_country_name = os.getenv('PROVIDER_CSR_COUNTRY_NAME', cert_generation.get('csr_country_name', '')).strip()
csr_email_address = os.getenv('PROVIDER_CSR_EMAIL_ADDRESS', cert_generation.get('csr_email_address', '')).strip()
# Retrieve provider specific values (APFs, AEFs)
supported_features = os.getenv('PROVIDER_SUPPORTED_FEATURES', provider_config.get('supported_features', '')).strip()
if not supported_features:
supported_features = "0"
apfs = os.getenv('PROVIDER_APFS', provider_config.get('apfs', '')).strip()
aefs = os.getenv('PROVIDER_AEFS', provider_config.get('aefs', '')).strip()
api_description_path = os.path.abspath(os.getenv('PROVIDER_API_DESCRIPTION_PATH', provider_config.get('api_description_path', '')).strip())
log = os.getenv('PROVIDER_LOG', provider_config.get('log', ''))
# Check required fields and log warnings/errors
if not capif_host:
self.logger.warning("CAPIF_HOST is not provided; defaulting to an empty string")
if not capif_provider_username:
self.logger.error("CAPIF_PROVIDER_USERNAME is required but not provided")
raise ValueError("CAPIF_PROVIDER_USERNAME is required")
# Setup the folder to store provider files (e.g., certificates)
self.provider_folder = os.path.join(provider_general_folder, capif_provider_username)
os.makedirs(self.provider_folder, exist_ok=True)
# Set attributes for provider credentials and configuration
self.capif_host = capif_host.strip()
self.capif_provider_username = capif_provider_username
self.capif_provider_password = capif_provider_password
self.capif_register_host = capif_register_host
self.capif_register_port = capif_register_port
self.csr_common_name = csr_common_name
self.csr_organizational_unit = csr_organizational_unit
self.csr_organization = csr_organization
self.csr_locality = csr_locality
self.csr_state_or_province_name = csr_state_or_province_name
self.csr_country_name = csr_country_name
self.csr_email_address = csr_email_address
self.supported_features = supported_features
self.aefs = int(aefs)
self.apfs = int(apfs)
# Get publish request details from config or environment variables
publish_req_config = provider_config.get('publish_req', {})
self.publish_req = {
"service_api_id": os.getenv('PUBLISH_REQ_SERVICE_API_ID', publish_req_config.get('service_api_id', '')).strip(),
"publisher_apf_id": os.getenv('PUBLISH_REQ_PUBLISHER_APF_ID', publish_req_config.get('publisher_apf_id', '')).strip(),
"publisher_aefs_ids": os.getenv('PUBLISH_REQ_PUBLISHER_AEFS_IDS', publish_req_config.get('publisher_aefs_ids', ''))
}
# Set the path for the API description file
self.api_description_path = api_description_path
# Set the CAPIF HTTPS port and construct CAPIF URLs
self.capif_https_port = str(capif_https_port)
self.provider_capif_ids = {}
path_prov_funcs = os.path.join(self.provider_folder, "provider_capif_ids.json")
if os.path.exists(path_prov_funcs):
self.provider_capif_ids = self.__load_provider_api_details()
path_published = os.path.join(self.provider_folder, "provider_service_ids.json")
if os.path.exists(path_published):
self.provider_service_ids = self.__load_config_file(path_published)
# Construct the CAPIF HTTPS URL
if len(self.capif_https_port) == 0 or int(self.capif_https_port) == 443:
self.capif_https_url = f"https://{capif_host.strip()}/"
else:
self.capif_https_url = f"https://{capif_host.strip()}:{self.capif_https_port.strip()}/"
# Construct the CAPIF register URL
if len(capif_register_port) == 0:
self.capif_register_url = f"https://{capif_register_host.strip()}:8084/"
else:
self.capif_register_url = f"https://{capif_register_host.strip()}:{capif_register_port.strip()}/"
self.__search_aef_and_api_by_name(log)
self.log = log
# Log initialization success message
self.logger.info("capif_logging_feature initialized with the capif_sdk_config.json parameters")
except Exception as e:
# Catch and log any exceptions that occur during initialization
self.logger.error(f"Error during initialization: {e}")
raise
def __search_aef_and_api_by_name(self, log):
"""
Searches for an AEF and API by name and updates self.api_id with the corresponding ID.
Args:
log (dict): A record containing API information, including "apiName".
Raises:
KeyError: If "apiName" is not present in the log.
ValueError: If no ID is associated with the given name.
"""
# Validate that the log contains the "apiName" field
if "apiName" not in log:
raise KeyError("The provided log does not contain 'apiName'.")
# Retrieve the API name
name = log["apiName"]
# Search for the corresponding API ID
self.api_id = self.provider_service_ids.get(name)
# Validate that a valid ID was found
if not self.api_id:
raise ValueError(f"No ID was found for the API '{name}'.")
def create_logs(self, aefId, jwt, supp_features="0"):
path = self.capif_https_url + f"/api-invocation-logs/v1/{aefId}/logs"
log_entry = {
"apiId": self.api_id,
"apiName": self.log["apiName"],
"apiVersion": self.log["apiVersion"],
"resourceName": self.log["resourceName"],
"uri": self.log["uri"],
"protocol": self.log["protocol"],
"operation": self.log["operation"],
"result": self.log["result"]
}
payload = {
"aefId": f"{aefId}",
"apiInvokerId": f"{api_invoker_id}",
"logs": [log_entry],
JorgeEcheva26
committed
"supportedFeatures": f"{supp_features}"
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
}
provider_details = self.__load_provider_api_details()
AEF_api_prov_func_id = aefId
aef_number = None
for key, value in provider_details.items():
if value == AEF_api_prov_func_id and key.startswith("AEF-"):
aef_inter = key.split("-")[1]
# Obtain the aef number
aef_number = aef_inter.split("_")[0]
break
if aef_number is None:
self.logger.error(
f"No matching AEF found for publisher_aef_id: {AEF_api_prov_func_id}")
raise ValueError("Invalid publisher_aef_id")
cert = (
os.path.join(self.provider_folder, f"aef-{aef_number}.crt"),
os.path.join(self.provider_folder,
f"AEF-{aef_number}_private_key.key"),
)
try:
response = requests.post(
url=path,
json=payload,
headers={"Content-Type": "application/json"},
cert=cert,
verify=os.path.join(self.provider_folder, "ca.crt")
)
response.raise_for_status()
return response.status_code, response.json()
except Exception as e:
self.logger.error("Unexpected error: %s", e)
return None, {"error": f"Unexpected error: {e}"}
def __load_provider_api_details(self) -> dict:
"""
Loads NEF API details from the CAPIF provider details JSON file.
:return: A dictionary containing NEF API details.
:raises FileNotFoundError: If the CAPIF provider details file is not found.
:raises json.JSONDecodeError: If there is an error decoding the JSON file.
"""
file_path = os.path.join(self.provider_folder,
"provider_capif_ids.json")
try:
with open(file_path, "r") as file:
return json.load(file)
except FileNotFoundError:
self.logger.error(f"File not found: {file_path}")
raise
except json.JSONDecodeError as e:
self.logger.error(
f"Error decoding JSON from file {file_path}: {e}")
raise
except Exception as e:
self.logger.error(
f"Unexpected error while loading NEF API details: {e}")
raise
def __load_config_file(self, config_file: str):
"""Carga el archivo de configuración."""
try:
with open(config_file, 'r') as file:
return json.load(file)
except FileNotFoundError:
self.logger.warning(
f"Configuration file {config_file} not found. Using defaults or environment variables.")
return {}
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def _decrypt_jwt(self, jwt_token):
"""
Decrypts the given JWT using the provided certificate.
:param jwt_token: The JWT to decrypt.
:return: The payload of the JWT if it is valid.
:raises: InvalidTokenError if the JWT is invalid or cannot be decrypted.
"""
try:
# Path to the certificate
path = os.path.join(self.provider_folder, "capif_cert_server.pem")
# Ensure the certificate file exists
if not os.path.exists(path):
raise FileNotFoundError(f"Certificate file not found at {path}")
# Load the public key from the certificate
with open(path, "r") as cert_file:
cert = cert_file.read()
# Decode the JWT using the public key
crtObj = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
pubKeyObject = crtObj.get_pubkey()
pubKeyString = crypto.dump_publickey(crypto.FILETYPE_PEM, pubKeyObject)
payload = jwt.decode(jwt_token, pubKeyString, algorithms=["RS256"])
for key, value in payload.items():
if key == "sub":
return value
except InvalidTokenError as e:
raise InvalidTokenError(f"Invalid JWT token: {e}")
except Exception as e:
raise Exception(f"An error occurred while decrypting the JWT: {e}")