shunping commented on code in PR #39636: URL: https://github.com/apache/beam/pull/39636#discussion_r3736332623
########## sdks/python/apache_beam/utils/secret.py: ########## @@ -0,0 +1,493 @@ +# +# 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 apache_beam.utils.annotations import deprecated + +__all__ = [ + 'Secret', + 'RawSecret', + 'GcpSecret', + 'GcpHsmGeneratedSecret', + 'generate_secret_bytes', +] + +_LOGGER = logging.getLogger(__name__) + + +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): + """A secret management class used for handling sensitive data. + + This class provides a generic interface for secret management. Implementations + of this class should handle fetching secrets from a secret management system. + """ + 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. + + The secret string should be formatted like: + 'type:<secret_type>;<secret_param>:<value>' + + For example, 'type:GcpSecret;version_name:my_secret/versions/latest' + would return a GcpSecret initialized with 'my_secret/versions/latest'. + + Deprecated: Use :meth:`from_option_string` instead. Review Comment: I think when it comes to a constructor, `from_option_string` or `from_option` is more pythonic than `parse_secret_option`. Also it is consistent with the new `from_spec` function. -- 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]
