github-advanced-security[bot] commented on code in PR #39636: URL: https://github.com/apache/beam/pull/39636#discussion_r3722346145
########## sdks/python/apache_beam/utils/secret.py: ########## @@ -0,0 +1,460 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Interface and implementations for Secret providers in Apache Beam.""" + +import abc +import json +import logging +import os +import warnings +from typing import Any, Dict, Optional, Union + +from google.cloud import secretmanager + +from apache_beam.utils.annotations import deprecated + +__all__ = [ + 'Secret', + 'RawSecret', + 'GcpSecret', + 'GcpHsmGeneratedSecret', + 'generate_secret_bytes', +] + + +def generate_secret_bytes() -> bytes: + """Generates a new secret key using Fernet.""" + from cryptography.fernet import Fernet + return Fernet.generate_key() + + +class Secret(abc.ABC): + """Abstract base interface for Secrets in Apache Beam.""" + def __init__(self): + self._cached_secret_bytes: Optional[bytes] = None + + def get(self, cacheSecret: bool = False) -> str: + """Retrieve secret value as string. + + Args: + cacheSecret: If True, caches secret value in memory after first fetch. + + Returns: + The retrieved secret value as string. + """ + return self.get_bytes(cacheSecret=cacheSecret).decode("utf-8") + + def get_bytes(self, cacheSecret: bool = False) -> bytes: + """Retrieve secret value as bytes. + + Args: + cacheSecret: If True, caches secret value in memory after first fetch. + + Returns: + The retrieved secret value as bytes. + """ + if cacheSecret and getattr(self, '_cached_secret_bytes', None) is not None: + return self._cached_secret_bytes + + secret_val_bytes = self.get_secret_bytes() + + if cacheSecret: + self._cached_secret_bytes = secret_val_bytes + + return secret_val_bytes + + @abc.abstractmethod + def get_secret_bytes(self) -> bytes: + """Retrieve secret value as bytes from the underlying secret provider. + + Returns: + The retrieved secret value as bytes. + """ + raise NotImplementedError + + @staticmethod + @deprecated(since='2.77.0', current='generate_secret_bytes') + def generate_secret_bytes() -> bytes: + """Generates a new secret key. + + Deprecated: Use global :func:`generate_secret_bytes` instead. + """ + return generate_secret_bytes() + + @classmethod + @deprecated(since='2.77.0', current='from_option_string') + def parse_secret_option(cls, secret: str) -> 'Secret': + """Parses a secret string and returns the appropriate secret type. + + Deprecated: Use :meth:`from_option_string` instead. + """ + return cls.from_option_string(secret) + + def __getstate__(self): + """Strip cached secrets before pickling for pipeline submission/transmission.""" + state = self.__dict__.copy() + state['_cached_secret_bytes'] = None + return state + + @classmethod + def from_spec( + cls, + spec: Union[str, Dict[str, str]], + secret_manager: Optional[str] = None, + secret_type: Optional[str] = None) -> 'Secret': + """Return a Secret instance based on secret_manager provider and secret specification. + + Args: + spec: Secret string (raw secret or JSON specification string). + secret_manager: Provider type string (e.g. 'GoogleCloudSecretManager'). + secret_type: Provider type string (e.g. 'gcpsecret'). + + Returns: + An instance of Secret. + """ + sm_manager = secret_manager.strip( + ) if secret_manager and secret_manager.strip() else None + sm_type = secret_type.strip( + ) if secret_type and secret_type.strip() else None + + if sm_manager and sm_type: + raise ValueError( + f"Cannot specify both 'secret_manager' ('{secret_manager}') and 'secret_type' ('{secret_type}'). " + "Please specify only one.") + + if isinstance(spec, str): + spec_dict = None + try: + spec_dict = json.loads(spec) + if not isinstance(spec_dict, dict): + spec_dict = None + except Exception: + pass + elif isinstance(spec, dict): + spec_dict = spec + else: + spec_dict = None + + provider_str = sm_manager or sm_type + if provider_str: + secret_cls = _SECRET_CLASSES.get(provider_str.lower()) + if secret_cls: + if isinstance(spec_dict, dict) and hasattr(secret_cls, 'from_dict'): + return secret_cls.from_dict(spec_dict) + elif isinstance(spec_dict, dict): + return secret_cls(**spec_dict) + else: + return secret_cls(spec) + else: + raise ValueError( + f"Unsupported secret provider: '{provider_str}'. Currently supported options: 'GoogleCloudSecretManager', 'gcpsecret'." + ) + + # If secret_manager is not set or empty, check if spec is a JSON specification dict + if spec_dict is not None: + msg = ( + "The 'spec' parameter appears to be a JSON specification, but " + "'secret_manager' is not set. Defaulting to Raw.") + logging.warning(msg) + warnings.warn(msg, UserWarning) + + return RawSecret(spec) + + @classmethod + def from_option_string(cls, option: str) -> 'Secret': + param_map = {} + for param in option.split(';'): + parts = param.split(':') + if len(parts) == 2: + param_map[parts[0]] = parts[1] + + if 'type' not in param_map: + raise ValueError('Secret string must contain a valid type parameter') + + secret_manager = param_map.pop('type') + return cls.from_spec(json.dumps(param_map), secret_manager) + + +class RawSecret(Secret): + """Secret implementation wrapping a raw secret string or bytes directly.""" + def __init__(self, secret: Union[str, bytes]): + super().__init__() + if isinstance(secret, str): + self._secret = secret.encode("utf-8") + else: + self._secret = secret + + def get_secret_bytes(self) -> bytes: + return self._secret + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RawSecret): + return False + return self._secret == other._secret + + +class GcpSecret(Secret): + """Secret implementation using Google Cloud Secret Manager.""" + def __init__(self, version_name: str): + super().__init__() + self._version_name = version_name + + @classmethod + def from_dict(cls, spec_dict: Dict[str, str]) -> 'GcpSecret': + """Initialize GcpSecret from a dictionary specification.""" + allowed_keys = {'version_name', 'name', 'project', 'version'} + invalid_keys = set(spec_dict.keys()) - allowed_keys + if invalid_keys: + raise ValueError( + f"Invalid secret parameter {', '.join(sorted(invalid_keys))}") + version_name = cls._parse_version_name(spec_dict) + return cls(version_name) + + @classmethod + def _parse_version_name(cls, spec_dict: Dict[str, str]) -> str: + if "version_name" in spec_dict: + return spec_dict["version_name"] + + secret_id = spec_dict.get("name") + if not secret_id: + raise ValueError("Secret name ('name') must be specified in secret spec.") + + # Resolve project ID from spec, environment variables, or Application Default Credentials + project_id = ( + spec_dict.get("project") or os.environ.get("GOOGLE_CLOUD_PROJECT") or + os.environ.get("GCP_PROJECT")) + + if not project_id: + try: + import google.auth + _, project_id = google.auth.default() + except Exception: + pass + + version_id = spec_dict.get("version", "latest") + + if not project_id: + raise ValueError( + f"Could not resolve GCP project ID for secret '{secret_id}'. " + "Please specify 'project' in the secret spec, set GOOGLE_CLOUD_PROJECT environment variable, " + "or configure Application Default Credentials.") + + return f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GcpSecret): + return False + return self._version_name == other._version_name + + def get_secret_bytes(self) -> bytes: + """Get the secret value as bytes from GCP Secret Manager. + + Returns: + The secret bytes. + """ + try: + client = secretmanager.SecretManagerServiceClient() + response = client.access_secret_version( + request={"name": self._version_name}) + secret_val_bytes = response.payload.data + logging.info( + "Successfully fetched secret from GCP Secret Manager (version_name '%s')", + self._version_name) + return secret_val_bytes + except Exception as e: + raise RuntimeError( + f'Failed to retrieve secret bytes for secret ' + f'{self._version_name} with exception {e}') + + +class GcpHsmGeneratedSecret(Secret): + """Secret manager implementation that generates a secret using a GCP HSM key + and stores it in Google Cloud Secret Manager. If the secret already exists, + it will be retrieved. + """ + def __init__( + self, + project_id: str, + location_id: str, + key_ring_id: str, + key_id: str, + job_name: str): + """Initializes a GcpHsmGeneratedSecret object. + + Args: + project_id: The GCP project ID. + location_id: The GCP location ID for the HSM key. + key_ring_id: The ID of the KMS key ring. + key_id: The ID of the KMS key. + job_name: The name of the job, used to generate a unique secret name. + """ + super().__init__() + self._project_id = project_id + self._location_id = location_id + self._key_ring_id = key_ring_id + self._key_id = key_id + self._job_name = job_name + self._secret_version_name = f'HsmGeneratedSecret_{job_name}' + + @classmethod + def from_dict(cls, spec_dict: Dict[str, str]) -> 'GcpHsmGeneratedSecret': + """Initialize GcpHsmGeneratedSecret from a dictionary specification.""" + allowed_keys = { + 'project_id', 'location_id', 'key_ring_id', 'key_id', 'job_name' + } + missing = allowed_keys - set(spec_dict.keys()) + if missing: + raise ValueError( + f"Missing required parameter(s) for GcpHsmGeneratedSecret: {sorted(list(missing))}") + invalid_keys = set(spec_dict.keys()) - allowed_keys + if invalid_keys: + raise ValueError( + f"Invalid secret parameter {', '.join(sorted(invalid_keys))}") + return cls( + project_id=spec_dict['project_id'], + location_id=spec_dict['location_id'], + key_ring_id=spec_dict['key_ring_id'], + key_id=spec_dict['key_id'], + job_name=spec_dict['job_name'], + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GcpHsmGeneratedSecret): + return False + return ( + self._project_id == other._project_id and + self._location_id == other._location_id and + self._key_ring_id == other._key_ring_id and + self._key_id == other._key_id and self._job_name == other._job_name) + + def get_secret_bytes(self) -> bytes: + """Retrieves the secret bytes from GCP Secret Manager, creating it if needed. + + Returns: + The secret bytes. + """ + from google.api_core import exceptions as api_exceptions + from google.cloud import secretmanager + + client = secretmanager.SecretManagerServiceClient() + + project_path = f"projects/{self._project_id}" + secret_path = f"{project_path}/secrets/{self._secret_version_name}" + secret_version_path = f"{secret_path}/versions/1" + + try: + try: + response = client.access_secret_version( + request={"name": secret_version_path}) + return response.payload.data + except api_exceptions.NotFound: + pass + + try: + client.create_secret( + request={ + "parent": project_path, + "secret_id": self._secret_version_name, + "secret": { + "replication": { + "automatic": {} + } + }, + }) + except api_exceptions.AlreadyExists: + pass + + new_key = self.generate_dek() + try: + # Try one more time in case it was created while we were generating the DEK. + response = client.access_secret_version( + request={"name": secret_version_path}) + return response.payload.data + except api_exceptions.NotFound: + logging.info( + "Secret version %s not found. Creating new secret and version.", + secret_version_path) Review Comment: ## CodeQL / Clear-text logging of sensitive information This expression logs [sensitive data (secret)](1) as clear text. [Show more details](https://github.com/apache/beam/security/code-scanning/1905) ########## sdks/python/apache_beam/utils/secret.py: ########## @@ -0,0 +1,460 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Interface and implementations for Secret providers in Apache Beam.""" + +import abc +import json +import logging +import os +import warnings +from typing import Any, Dict, Optional, Union + +from google.cloud import secretmanager + +from apache_beam.utils.annotations import deprecated + +__all__ = [ + 'Secret', + 'RawSecret', + 'GcpSecret', + 'GcpHsmGeneratedSecret', + 'generate_secret_bytes', +] + + +def generate_secret_bytes() -> bytes: + """Generates a new secret key using Fernet.""" + from cryptography.fernet import Fernet + return Fernet.generate_key() + + +class Secret(abc.ABC): + """Abstract base interface for Secrets in Apache Beam.""" + def __init__(self): + self._cached_secret_bytes: Optional[bytes] = None + + def get(self, cacheSecret: bool = False) -> str: + """Retrieve secret value as string. + + Args: + cacheSecret: If True, caches secret value in memory after first fetch. + + Returns: + The retrieved secret value as string. + """ + return self.get_bytes(cacheSecret=cacheSecret).decode("utf-8") + + def get_bytes(self, cacheSecret: bool = False) -> bytes: + """Retrieve secret value as bytes. + + Args: + cacheSecret: If True, caches secret value in memory after first fetch. + + Returns: + The retrieved secret value as bytes. + """ + if cacheSecret and getattr(self, '_cached_secret_bytes', None) is not None: + return self._cached_secret_bytes + + secret_val_bytes = self.get_secret_bytes() + + if cacheSecret: + self._cached_secret_bytes = secret_val_bytes + + return secret_val_bytes + + @abc.abstractmethod + def get_secret_bytes(self) -> bytes: + """Retrieve secret value as bytes from the underlying secret provider. + + Returns: + The retrieved secret value as bytes. + """ + raise NotImplementedError + + @staticmethod + @deprecated(since='2.77.0', current='generate_secret_bytes') + def generate_secret_bytes() -> bytes: + """Generates a new secret key. + + Deprecated: Use global :func:`generate_secret_bytes` instead. + """ + return generate_secret_bytes() + + @classmethod + @deprecated(since='2.77.0', current='from_option_string') + def parse_secret_option(cls, secret: str) -> 'Secret': + """Parses a secret string and returns the appropriate secret type. + + Deprecated: Use :meth:`from_option_string` instead. + """ + return cls.from_option_string(secret) + + def __getstate__(self): + """Strip cached secrets before pickling for pipeline submission/transmission.""" + state = self.__dict__.copy() + state['_cached_secret_bytes'] = None + return state + + @classmethod + def from_spec( + cls, + spec: Union[str, Dict[str, str]], + secret_manager: Optional[str] = None, + secret_type: Optional[str] = None) -> 'Secret': + """Return a Secret instance based on secret_manager provider and secret specification. + + Args: + spec: Secret string (raw secret or JSON specification string). + secret_manager: Provider type string (e.g. 'GoogleCloudSecretManager'). + secret_type: Provider type string (e.g. 'gcpsecret'). + + Returns: + An instance of Secret. + """ + sm_manager = secret_manager.strip( + ) if secret_manager and secret_manager.strip() else None + sm_type = secret_type.strip( + ) if secret_type and secret_type.strip() else None + + if sm_manager and sm_type: + raise ValueError( + f"Cannot specify both 'secret_manager' ('{secret_manager}') and 'secret_type' ('{secret_type}'). " + "Please specify only one.") + + if isinstance(spec, str): + spec_dict = None + try: + spec_dict = json.loads(spec) + if not isinstance(spec_dict, dict): + spec_dict = None + except Exception: + pass + elif isinstance(spec, dict): + spec_dict = spec + else: + spec_dict = None + + provider_str = sm_manager or sm_type + if provider_str: + secret_cls = _SECRET_CLASSES.get(provider_str.lower()) + if secret_cls: + if isinstance(spec_dict, dict) and hasattr(secret_cls, 'from_dict'): + return secret_cls.from_dict(spec_dict) + elif isinstance(spec_dict, dict): + return secret_cls(**spec_dict) + else: + return secret_cls(spec) + else: + raise ValueError( + f"Unsupported secret provider: '{provider_str}'. Currently supported options: 'GoogleCloudSecretManager', 'gcpsecret'." + ) + + # If secret_manager is not set or empty, check if spec is a JSON specification dict + if spec_dict is not None: + msg = ( + "The 'spec' parameter appears to be a JSON specification, but " + "'secret_manager' is not set. Defaulting to Raw.") + logging.warning(msg) + warnings.warn(msg, UserWarning) + + return RawSecret(spec) + + @classmethod + def from_option_string(cls, option: str) -> 'Secret': + param_map = {} + for param in option.split(';'): + parts = param.split(':') + if len(parts) == 2: + param_map[parts[0]] = parts[1] + + if 'type' not in param_map: + raise ValueError('Secret string must contain a valid type parameter') + + secret_manager = param_map.pop('type') + return cls.from_spec(json.dumps(param_map), secret_manager) + + +class RawSecret(Secret): + """Secret implementation wrapping a raw secret string or bytes directly.""" + def __init__(self, secret: Union[str, bytes]): + super().__init__() + if isinstance(secret, str): + self._secret = secret.encode("utf-8") + else: + self._secret = secret + + def get_secret_bytes(self) -> bytes: + return self._secret + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RawSecret): + return False + return self._secret == other._secret + + +class GcpSecret(Secret): + """Secret implementation using Google Cloud Secret Manager.""" + def __init__(self, version_name: str): + super().__init__() + self._version_name = version_name + + @classmethod + def from_dict(cls, spec_dict: Dict[str, str]) -> 'GcpSecret': + """Initialize GcpSecret from a dictionary specification.""" + allowed_keys = {'version_name', 'name', 'project', 'version'} + invalid_keys = set(spec_dict.keys()) - allowed_keys + if invalid_keys: + raise ValueError( + f"Invalid secret parameter {', '.join(sorted(invalid_keys))}") + version_name = cls._parse_version_name(spec_dict) + return cls(version_name) + + @classmethod + def _parse_version_name(cls, spec_dict: Dict[str, str]) -> str: + if "version_name" in spec_dict: + return spec_dict["version_name"] + + secret_id = spec_dict.get("name") + if not secret_id: + raise ValueError("Secret name ('name') must be specified in secret spec.") + + # Resolve project ID from spec, environment variables, or Application Default Credentials + project_id = ( + spec_dict.get("project") or os.environ.get("GOOGLE_CLOUD_PROJECT") or + os.environ.get("GCP_PROJECT")) + + if not project_id: + try: + import google.auth + _, project_id = google.auth.default() + except Exception: + pass + + version_id = spec_dict.get("version", "latest") + + if not project_id: + raise ValueError( + f"Could not resolve GCP project ID for secret '{secret_id}'. " + "Please specify 'project' in the secret spec, set GOOGLE_CLOUD_PROJECT environment variable, " + "or configure Application Default Credentials.") + + return f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, GcpSecret): + return False + return self._version_name == other._version_name + + def get_secret_bytes(self) -> bytes: + """Get the secret value as bytes from GCP Secret Manager. + + Returns: + The secret bytes. + """ + try: + client = secretmanager.SecretManagerServiceClient() + response = client.access_secret_version( + request={"name": self._version_name}) + secret_val_bytes = response.payload.data + logging.info( + "Successfully fetched secret from GCP Secret Manager (version_name '%s')", + self._version_name) Review Comment: ## CodeQL / Clear-text logging of sensitive information This expression logs [sensitive data (secret)](1) as clear text. [Show more details](https://github.com/apache/beam/security/code-scanning/1904) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
