|
| 1 | +import requests |
| 2 | +from tenacity import retry, retry_if_not_exception_type, stop, wait |
| 3 | + |
| 4 | +from horizon.config import ApiKeyLevel, sidecar_config, MOCK_API_KEY |
| 5 | +from opal_common.logger import logger |
| 6 | + |
| 7 | +from horizon.startup.exceptions import NoRetryException |
| 8 | +from horizon.startup.blocking_request import BlockingRequest |
| 9 | +from horizon.system.consts import GUNICORN_EXIT_APP |
| 10 | + |
| 11 | + |
| 12 | +class EnvApiKeyFetcher: |
| 13 | + |
| 14 | + DEFAULT_RETRY_CONFIG = { |
| 15 | + "retry": retry_if_not_exception_type(NoRetryException), |
| 16 | + "wait": wait.wait_random_exponential(max=10), |
| 17 | + "stop": stop.stop_after_attempt(10), |
| 18 | + "reraise": True, |
| 19 | + } |
| 20 | + |
| 21 | + def __init__( |
| 22 | + self, |
| 23 | + backend_url: str = sidecar_config.CONTROL_PLANE, |
| 24 | + retry_config=None, |
| 25 | + ): |
| 26 | + self._backend_url = backend_url |
| 27 | + self._retry_config = retry_config or self.DEFAULT_RETRY_CONFIG |
| 28 | + self.api_key_level = self._get_api_key_level() |
| 29 | + |
| 30 | + @staticmethod |
| 31 | + def _get_api_key_level() -> ApiKeyLevel: |
| 32 | + if sidecar_config.API_KEY != MOCK_API_KEY: |
| 33 | + if sidecar_config.ORG_API_KEY or sidecar_config.PROJECT_API_KEY: |
| 34 | + logger.warning( |
| 35 | + "PDP_API_KEY is set, but PDP_ORG_API_KEY or PDP_PROJECT_API_KEY are also set and will be ignored." |
| 36 | + ) |
| 37 | + return ApiKeyLevel.ENVIRONMENT |
| 38 | + |
| 39 | + if sidecar_config.PROJECT_API_KEY: |
| 40 | + if sidecar_config.ORG_API_KEY: |
| 41 | + logger.warning( |
| 42 | + "PDP_PROJECT_API_KEY is set, but PDP_ORG_API_KEY is also set and will be ignored." |
| 43 | + ) |
| 44 | + if not sidecar_config.ACTIVE_ENV: |
| 45 | + logger.error( |
| 46 | + "PDP_PROJECT_API_KEY is set, but PDP_ACTIVE_ENV is not. Please set it with Environment ID or Key." |
| 47 | + ) |
| 48 | + raise |
| 49 | + return ApiKeyLevel.PROJECT |
| 50 | + |
| 51 | + if sidecar_config.ORG_API_KEY: |
| 52 | + if not sidecar_config.ACTIVE_ENV or not sidecar_config.ACTIVE_PROJECT: |
| 53 | + logger.error( |
| 54 | + "PDP_ORG_API_KEY is set, but PDP_ACTIVE_ENV or PDP_ACTIVE_PROJECT are not. Please set them with Environment ID/Key and Project ID/Key." |
| 55 | + ) |
| 56 | + raise |
| 57 | + return ApiKeyLevel.ORGANIZATION |
| 58 | + |
| 59 | + logger.critical( |
| 60 | + "No API key specified. Please specify one with the PDP_API_KEY environment variable." |
| 61 | + ) |
| 62 | + raise |
| 63 | + |
| 64 | + def get_env_api_key_by_level(self) -> str: |
| 65 | + api_key_level = self.api_key_level |
| 66 | + api_key = sidecar_config.ORG_API_KEY |
| 67 | + active_project_id = sidecar_config.ACTIVE_PROJECT |
| 68 | + active_env_id = sidecar_config.ACTIVE_ENV |
| 69 | + |
| 70 | + if api_key_level == ApiKeyLevel.ENVIRONMENT: |
| 71 | + return sidecar_config.API_KEY |
| 72 | + if api_key_level == ApiKeyLevel.PROJECT: |
| 73 | + api_key = sidecar_config.PROJECT_API_KEY |
| 74 | + active_project_id = get_scope(sidecar_config.ORG_API_KEY).get("project_id") |
| 75 | + if not active_project_id: |
| 76 | + logger.error( |
| 77 | + "PDP_PROJECT_API_KEY is set, but failed to get Project ID from provided Organization API Key." |
| 78 | + ) |
| 79 | + raise |
| 80 | + return self._fetch_env_key(api_key, active_project_id, active_env_id) |
| 81 | + |
| 82 | + def _fetch_env_key( |
| 83 | + self, api_key: str, active_project_key: str, active_env_key: str |
| 84 | + ) -> str: |
| 85 | + """ |
| 86 | + fetches the active environment's API Key by identifying with the provided Project/Organization API Key. |
| 87 | + """ |
| 88 | + api_key_url = ( |
| 89 | + f"{self._backend_url}/v2/api-key/{active_project_key}/{active_env_key}" |
| 90 | + ) |
| 91 | + logger.info( |
| 92 | + "Fetching Environment API Key from control plane: {url}", url=api_key_url |
| 93 | + ) |
| 94 | + fetch_with_retry = retry(**self._retry_config)( |
| 95 | + lambda: BlockingRequest( |
| 96 | + token=api_key, |
| 97 | + ).get(url=api_key_url) |
| 98 | + ) |
| 99 | + try: |
| 100 | + secret = fetch_with_retry().get("secret") |
| 101 | + if secret is None: |
| 102 | + logger.error("No secret found in response from control plane") |
| 103 | + raise |
| 104 | + return secret |
| 105 | + |
| 106 | + except requests.RequestException as e: |
| 107 | + logger.warning(f"Failed to get Environment API Key: {e}") |
| 108 | + raise |
| 109 | + |
| 110 | + def fetch_scope(self, api_key: str) -> dict | None: |
| 111 | + """ |
| 112 | + fetches the provided Project/Organization Scope. |
| 113 | + """ |
| 114 | + api_key_url = f"{self._backend_url}/v2/api-key/scope" |
| 115 | + logger.info("Fetching Scope from control plane: {url}", url=api_key_url) |
| 116 | + fetch_with_retry = retry(**self._retry_config)( |
| 117 | + lambda: BlockingRequest( |
| 118 | + token=api_key, |
| 119 | + ).get(url=api_key_url) |
| 120 | + ) |
| 121 | + try: |
| 122 | + return fetch_with_retry() |
| 123 | + except requests.RequestException: |
| 124 | + logger.warning("Failed to get scope from provided API Key") |
| 125 | + return |
| 126 | + |
| 127 | + |
| 128 | +_env_api_key: str | None = None |
| 129 | + |
| 130 | + |
| 131 | +def get_env_api_key() -> str: |
| 132 | + global _env_api_key |
| 133 | + if not _env_api_key: |
| 134 | + try: |
| 135 | + _env_api_key = EnvApiKeyFetcher().get_env_api_key_by_level() |
| 136 | + except Exception as e: |
| 137 | + logger.error(f"Failed to get Environment API Key: {e}") |
| 138 | + raise SystemExit(GUNICORN_EXIT_APP) |
| 139 | + return _env_api_key |
| 140 | + |
| 141 | + |
| 142 | +def get_scope(api_key: str) -> dict: |
| 143 | + if scope := EnvApiKeyFetcher().fetch_scope(api_key) is None: |
| 144 | + logger.warning("Failed to get scope from provided API Key") |
| 145 | + raise |
| 146 | + return scope |
0 commit comments