Skip to content

Commit ec18fe5

Browse files
committed
update
1 parent aabd364 commit ec18fe5

File tree

4 files changed

+81
-83
lines changed

4 files changed

+81
-83
lines changed

scripts/aws/ec2.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,11 @@ def get_meta_url(cls) -> str:
4848
return f"http://{cls.AWS_METADATA}/latest/dynamic/instance-identity/document"
4949

5050

51-
class EC2(ConfidentialCompute):
51+
class EC2EntryPoint(ConfidentialCompute):
5252

5353
def __init__(self):
5454
self.configs: AWSConfidentialComputeConfig = {}
5555

56-
5756
def __get_aws_token(self) -> str:
5857
"""Fetches a temporary AWS EC2 metadata token."""
5958
try:
@@ -85,7 +84,7 @@ def __validate_aws_specific_config(self):
8584
if min_capacity.get(key) > int(self.configs.get(key, 10**9)):
8685
raise ValueError(f"{key} value ({self.configs.get(key, 0)}) needs to be higher than the minimum required ({min_capacity.get(key)}).")
8786

88-
def _set_secret(self, secret_identifier: str) -> None:
87+
def _set_confidential_config(self, secret_identifier: str) -> None:
8988
"""Fetches a secret value from AWS Secrets Manager and adds defaults"""
9089

9190
def add_defaults(configs: Dict[str, any]) -> None:
@@ -209,7 +208,7 @@ def __run_nitro_enclave(self):
209208
def run_compute(self) -> None:
210209
"""Main execution flow for confidential compute."""
211210
secret_manager_key = self.__get_secret_name_from_userdata()
212-
self._set_secret(secret_manager_key)
211+
self._set_confidential_config(secret_manager_key)
213212
print(f"Fetched configs from {secret_manager_key}")
214213
if not self.configs.get("skip_validations"):
215214
self.validate_configuration()
@@ -245,13 +244,13 @@ def __kill_auxiliaries(self) -> None:
245244
parser.add_argument("-o", "--operation", choices=["stop", "start"], default="start", help="Operation to perform.")
246245
args = parser.parse_args()
247246
try:
248-
ec2 = EC2()
247+
ec2 = EC2EntryPoint()
249248
if args.operation == "stop":
250249
ec2.cleanup()
251250
else:
252251
ec2.run_compute()
253252
except ConfidentialComputeStartupException as e:
254253
print("Failed starting up Confidential Compute. Please checks the logs for errors and retry \n", e)
255254
except Exception as e:
256-
print("Unexpected failure while starting up Confidential Compute. Please contact UID support team with this log \n ", e)
255+
print("Unexpected failure while starting up Confidential Compute. Please contact UID support team with this log \n ", e)
257256

scripts/azure-cc/azureEntryPoint.py

Lines changed: 52 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,9 @@
1010
import logging
1111

1212
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
13-
from confidential_compute import ConfidentialCompute, ConfidentialComputeConfig, MissingConfig, ConfidentialComputeStartupException
14-
from azure.identity import DefaultAzureCredential, CredentialUnavailableError
13+
from confidential_compute import ConfidentialCompute, MissingConfig, SecretAccessException, AuxiliariesException, ConfidentialComputeStartupException
14+
from azure.identity import DefaultAzureCredential
1515
from azure.keyvault.secrets import SecretClient
16-
from azure.core.exceptions import ResourceNotFoundError, HttpResponseError
1716

1817
class AzureEntryPoint(ConfidentialCompute):
1918

@@ -29,41 +28,14 @@ def __init__(self):
2928
super().__init__()
3029

3130
def __check_env_variables(self):
31+
# Check essential env variables
3232
if AzureEntryPoint.kv_name is None:
3333
raise MissingConfig(self.__class__.__name__, ["VAULT_NAME"])
3434
if AzureEntryPoint.secret_name is None:
3535
raise MissingConfig(self.__class__.__name__, ["OPERATOR_KEY_SECRET_NAME"])
3636
if AzureEntryPoint.env_name is None:
3737
raise MissingConfig(self.__class__.__name__, ["DEPLOYMENT_ENVIRONMENT"])
38-
logging.info("Env variables validation success")
39-
40-
def __set_environment(self):
41-
self.configs["environment"] = AzureEntryPoint.env_name
42-
43-
def _set_secret(self, secret_identifier: str = None):
44-
try:
45-
credential = DefaultAzureCredential()
46-
kv_URL = f"https://{AzureEntryPoint.kv_name}.vault.azure.net"
47-
secret_client = SecretClient(vault_url=kv_URL, credential=credential)
48-
secret = secret_client.get_secret(AzureEntryPoint.secret_name)
49-
# print(f"Secret Value: {secret.value}")
50-
self.configs["api_token"] = secret.value
51-
52-
except CredentialUnavailableError as auth_error:
53-
logging.error(f"Read operator key, authentication error: {auth_error}")
54-
raise
55-
56-
except ResourceNotFoundError as not_found_error:
57-
logging.error(f"Read operator key, secret not found: {AzureEntryPoint.secret_name}. Error: {not_found_error}")
58-
raise
59-
60-
except HttpResponseError as http_error:
61-
logging.error(f"Read operator key, HTTP error occurred: {http_error}")
62-
raise
63-
64-
except Exception as e:
65-
logging.error(f"Read operator key, an unexpected error occurred: {e}")
66-
raise
38+
logging.info("Environment variables validation success")
6739

6840
def __create_final_config(self):
6941
TARGET_CONFIG = f"/app/conf/{AzureEntryPoint.env_name}-uid2-config.json"
@@ -93,13 +65,37 @@ def __create_final_config(self):
9365

9466
with open(AzureEntryPoint.FINAL_CONFIG, "r") as file:
9567
logging.info(file.read())
96-
97-
def __set_baseurls(self):
68+
69+
def __set_base_urls(self):
9870
with open(AzureEntryPoint.FINAL_CONFIG, "r") as file:
9971
jdata = json.load(file)
10072
self.configs["core_base_url"] = jdata["core_attest_url"]
10173
self.configs["optout_base_url"] = jdata["optout_api_uri"]
10274

75+
def __set_api_token(self):
76+
try:
77+
credential = DefaultAzureCredential()
78+
kv_URL = f"https://{AzureEntryPoint.kv_name}.vault.azure.net"
79+
secret_client = SecretClient(vault_url=kv_URL, credential=credential)
80+
secret = secret_client.get_secret(AzureEntryPoint.secret_name)
81+
# print(f"Secret Value: {secret.value}")
82+
self.configs["api_token"] = secret.value
83+
84+
except Exception as e:
85+
errormsg = f"Read operator key, an unexpected error occurred: {e}"
86+
logging.error(errormsg)
87+
raise SecretAccessException(self.__class__.__name__, errormsg)
88+
89+
def _set_confidential_config(self, secret_identifier: str = None):
90+
self.configs["skip_validations"] = os.getenv("SKIP_VALIDATIONS", "false").lower() == "true"
91+
self.configs["debug_mode"] = os.getenv("DEBUG_MODE", "false").lower() == "true"
92+
self.configs["environment"] = AzureEntryPoint.env_name
93+
94+
# set self.configs["api_token"]
95+
self.__set_api_token()
96+
# set base urls from final config file
97+
self.__set_base_urls()
98+
10399
def __run_operator(self):
104100

105101
# Start the operator
@@ -119,46 +115,46 @@ def __run_operator(self):
119115
logging.info("-- starting java operator application")
120116
self.run_command(java_command, separate_process=False)
121117

122-
def __wait_for_sidecar(self):
118+
def _setup_auxiliaries(self):
123119
logging.info("Waiting for sidecar ...")
124120

125-
url = "http://169.254.169.254/ping"
121+
MAX_RETRIES = 15
122+
PING_URL = "http://169.254.169.254/ping"
126123
delay = 1
127-
max_retries = 15
128124

129-
while True:
125+
for attempt in range(1, MAX_RETRIES + 1):
130126
try:
131-
response = requests.get(url, timeout=5)
127+
response = requests.get(PING_URL, timeout=5)
132128
if response.status_code in [200, 204]:
133-
logging.info("Sidecar started")
129+
logging.info("Sidecar started successfully.")
134130
return
135131
else:
136-
error_msg = f"Unexpected status code: {response.status_code}, response: {response.text}"
137-
raise Exception(error_msg)
132+
logging.warning(
133+
f"Attempt {attempt}: Unexpected status code {response.status_code}. Response: {response.text}"
134+
)
138135
except Exception as e:
139-
if delay > max_retries:
140-
logging.error(f"Sidecar failed to start after {delay} retries with error {e}", exc_info=True)
141-
sys.exit(1)
142-
logging.info(f"Sidecar not started. Retrying in {delay} seconds... {e}")
143-
time.sleep(delay)
144-
delay += 1
136+
logging.info(f"Attempt {attempt}: Error during request - {e}")
137+
138+
if attempt == MAX_RETRIES:
139+
logging.error(
140+
f"Sidecar failed to start after {MAX_RETRIES} attempts. Exiting."
141+
)
142+
raise AuxiliariesException(self.__class__.__name__)
143+
144+
logging.info(f"Retrying in {delay} seconds... (Attempt {attempt}/{MAX_RETRIES})")
145+
time.sleep(delay)
146+
delay += 1
145147

146148
def run_compute(self) -> None:
147149
"""Main execution flow for confidential compute."""
148150
self.__check_env_variables()
149-
self._set_secret()
150-
self.__set_environment()
151151
self.__create_final_config()
152-
self.__set_baseurls()
152+
self._set_confidential_config()
153153
if not self.configs.get("skip_validations"):
154154
self.validate_configuration()
155-
self.__wait_for_sidecar()
155+
self._setup_auxiliaries()
156156
self.__run_operator()
157157

158-
def _setup_auxiliaries(self) -> None:
159-
""" Sets up auxiliary processes required for confidential computing. """
160-
pass
161-
162158
def _validate_auxiliaries(self) -> None:
163159
""" Validates auxiliary services are running."""
164160
pass

scripts/confidential_compute.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ class ConfidentialComputeConfig(TypedDict):
1818
class ConfidentialComputeStartupException(Exception):
1919
def __init__(self, error_name, provider, extra_message=None):
2020
urls = {
21-
"EC2": "https://unifiedid.com/docs/guides/operator-guide-aws-marketplace#uid2-operator-error-codes",
22-
"Azure": "https://unifiedid.com/docs/guides/operator-guide-azure-enclave#uid2-operator-error-codes",
23-
"GCPEntrypoint": "https://unifiedid.com/docs/guides/operator-private-gcp-confidential-space#uid2-operator-error-codes",
21+
"EC2EntryPoint": "https://unifiedid.com/docs/guides/operator-guide-aws-marketplace#uid2-operator-error-codes",
22+
"AzureEntryPoint": "https://unifiedid.com/docs/guides/operator-guide-azure-enclave#uid2-operator-error-codes",
23+
"GCPEntryPoint": "https://unifiedid.com/docs/guides/operator-private-gcp-confidential-space#uid2-operator-error-codes",
2424
}
2525
url = urls.get(provider)
2626
super().__init__(f"{error_name}\n" + (extra_message if extra_message else "") + f"\nVisit {url} for more details")
@@ -48,7 +48,15 @@ def __init__(self, cls):
4848
class UID2ServicesUnreachable(ConfidentialComputeStartupException):
4949
def __init__(self, cls, ip=None):
5050
super().__init__(error_name=f"E06: {self.__class__.__name__}", provider=cls, extra_message=ip)
51-
51+
52+
class SecretAccessException(ConfidentialComputeStartupException):
53+
def __init__(self, cls, inner_message):
54+
super().__init__(error_name=f"E07: {self.__class__.__name__}", provider=cls, extra_message=inner_message)
55+
56+
class AuxiliariesException(ConfidentialComputeStartupException):
57+
def __init__(self, cls, inner_message = None):
58+
super().__init__(error_name=f"E07: {self.__class__.__name__}", provider=cls, extra_message=inner_message)
59+
5260
class ConfidentialCompute(ABC):
5361

5462
def __init__(self):
@@ -112,9 +120,9 @@ def validate_connectivity() -> None:
112120
logging.info("Completed static validation of confidential compute config values")
113121

114122
@abstractmethod
115-
def _set_secret(self, secret_identifier: str) -> None:
123+
def _set_confidential_config(self, secret_identifier: str) -> None:
116124
"""
117-
Fetches the secret from a secret store.
125+
Set ConfidentialComputeConfig
118126
"""
119127
pass
120128

scripts/gcp-oidc/gcp.py

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,25 @@
55
from typing import Dict
66
import sys
77
from google.cloud import secretmanager
8-
from google.auth import default
9-
from google.auth.exceptions import DefaultCredentialsError
10-
from google.api_core.exceptions import PermissionDenied, NotFound
118

129
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
13-
from confidential_compute import ConfidentialCompute, ConfidentialComputeConfig, MissingConfig, ConfigNotFound, MissingInstanceProfile, ConfidentialComputeStartupException
10+
from confidential_compute import ConfidentialCompute, ConfidentialComputeConfig, MissingConfig, SecretAccessException, ConfidentialComputeStartupException
1411

15-
class GCPEntrypoint(ConfidentialCompute):
12+
class GCPEntryPoint(ConfidentialCompute):
1613

1714
def __init__(self):
1815
super().__init__()
1916

20-
def _get_secret(self, secret_identifier=None) -> ConfidentialComputeConfig:
17+
def _set_confidential_config(self, secret_identifier=None) -> None:
18+
2119
keys_mapping = {
2220
"core_base_url": "CORE_BASE_URL",
2321
"optout_base_url": "OPTOUT_BASE_URL",
2422
"environment": "DEPLOYMENT_ENVIRONMENT",
2523
"skip_validations": "SKIP_VALIDATIONS",
2624
"debug_mode": "DEBUG_MODE",
2725
}
28-
config: ConfidentialComputeConfig = {
26+
self.config = {
2927
key: (os.environ[env_var].lower() == "true" if key in ["skip_validations", "debug_mode"] else os.environ[env_var])
3028
for key, env_var in keys_mapping.items() if env_var in os.environ
3129
}
@@ -37,12 +35,9 @@ def _get_secret(self, secret_identifier=None) -> ConfidentialComputeConfig:
3735
secret_version_name = f"{os.getenv("API_TOKEN_SECRET_NAME")}"
3836
response = client.access_secret_version(name=secret_version_name)
3937
secret_value = response.payload.data.decode("UTF-8")
40-
except (PermissionDenied, DefaultCredentialsError) as e:
41-
raise MissingInstanceProfile(self.__class__.__name__, str(e))
42-
except NotFound:
43-
raise ConfigNotFound(self.__class__.__name__, f"Secret Manager {os.getenv("API_TOKEN_SECRET_NAME")}")
44-
config["api_token"] = secret_value
45-
return config
38+
except Exception as e:
39+
raise SecretAccessException(self.__class__.__name__, str(e))
40+
self.config["api_token"] = secret_value
4641

4742
def __populate_operator_config(self, destination):
4843
target_config = f"/app/conf/{self.configs["environment"].lower()}-config.json"
@@ -63,7 +58,7 @@ def _validate_auxiliaries(self) -> None:
6358
pass
6459

6560
def run_compute(self) -> None:
66-
self.configs = self._get_secret('read_from_env_vars')
61+
self._set_confidential_config()
6762
print(f"Fetched configs")
6863
if not self.configs.get("skip_validations"):
6964
self.validate_configuration()
@@ -86,7 +81,7 @@ def run_compute(self) -> None:
8681

8782
if __name__ == "__main__":
8883
try:
89-
gcp = GCP()
84+
gcp = GCPEntryPoint()
9085
gcp.run_compute()
9186
except ConfidentialComputeStartupException as e:
9287
print("Failed starting up Confidential Compute. Please checks the logs for errors and retry \n", e)

0 commit comments

Comments
 (0)