2021-12-25 16:29:10 -08:00
|
|
|
# Copyright 2021 Collate
|
|
|
|
# Licensed 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.
|
2022-10-11 17:15:02 +02:00
|
|
|
"""
|
|
|
|
Module containing AWS Client
|
|
|
|
"""
|
2023-01-02 13:52:27 +01:00
|
|
|
from enum import Enum
|
2025-01-03 10:51:15 +01:00
|
|
|
from functools import partial
|
|
|
|
from typing import Any, Callable, Dict, Optional, Type, TypeVar
|
2021-12-25 16:29:10 -08:00
|
|
|
|
2022-08-19 16:15:40 +02:00
|
|
|
import boto3
|
2021-12-25 16:29:10 -08:00
|
|
|
from boto3 import Session
|
2025-01-03 10:51:15 +01:00
|
|
|
from botocore.credentials import RefreshableCredentials
|
|
|
|
from botocore.session import get_session
|
|
|
|
from pydantic import BaseModel, Field
|
2021-12-25 16:29:10 -08:00
|
|
|
|
2023-03-08 15:43:33 +05:30
|
|
|
from metadata.generated.schema.security.credentials.awsCredentials import AWSCredentials
|
|
|
|
from metadata.ingestion.models.custom_pydantic import CustomSecretStr
|
2022-08-19 16:15:40 +02:00
|
|
|
from metadata.utils.logger import utils_logger
|
|
|
|
|
|
|
|
logger = utils_logger()
|
2022-04-22 11:30:59 +05:30
|
|
|
|
|
|
|
|
2023-01-02 13:52:27 +01:00
|
|
|
class AWSServices(Enum):
|
2023-03-26 10:35:34 +01:00
|
|
|
S3 = "s3"
|
|
|
|
CLOUDWATCH = "cloudwatch"
|
2023-01-02 13:52:27 +01:00
|
|
|
DYNAMO_DB = "dynamodb"
|
|
|
|
GLUE = "glue"
|
|
|
|
SAGEMAKER = "sagemaker"
|
|
|
|
KINESIS = "kinesis"
|
|
|
|
QUICKSIGHT = "quicksight"
|
2023-04-03 16:51:55 +05:30
|
|
|
ATHENA = "athena"
|
2023-06-16 13:18:12 +05:30
|
|
|
RDS = "rds"
|
2024-01-16 14:24:31 +05:30
|
|
|
LAKE_FORMATION = "lakeformation"
|
2023-01-02 13:52:27 +01:00
|
|
|
|
|
|
|
|
2023-03-08 15:43:33 +05:30
|
|
|
class AWSAssumeRoleException(Exception):
|
|
|
|
"""
|
|
|
|
Exception class to handle assume role related issues
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
class AWSAssumeRoleCredentialWrapper(BaseModel):
|
2025-01-03 10:51:15 +01:00
|
|
|
accessKeyId: str = Field(alias="access_key")
|
|
|
|
secretAccessKey: CustomSecretStr = Field(alias="secret_key")
|
|
|
|
sessionToken: Optional[str] = Field(default=None, alias="token")
|
|
|
|
expiryTime: Optional[str] = Field(alias="expiry_time")
|
|
|
|
|
|
|
|
|
|
|
|
AWSAssumeRoleCredentialFormat = TypeVar(
|
|
|
|
"AWSAssumeRoleCredentialFormat", AWSAssumeRoleCredentialWrapper, Dict
|
|
|
|
)
|
2023-03-08 15:43:33 +05:30
|
|
|
|
|
|
|
|
2021-12-25 16:29:10 -08:00
|
|
|
class AWSClient:
|
|
|
|
"""
|
2022-04-22 11:25:05 +02:00
|
|
|
AWSClient creates a boto3 Session client based on AWSCredentials.
|
2021-12-25 16:29:10 -08:00
|
|
|
"""
|
|
|
|
|
2022-11-11 09:59:15 +01:00
|
|
|
def __init__(self, config: "AWSCredentials"):
|
2022-11-14 13:48:50 +01:00
|
|
|
self.config = (
|
|
|
|
config
|
|
|
|
if isinstance(config, AWSCredentials)
|
2024-06-05 21:18:37 +02:00
|
|
|
else (AWSCredentials.model_validate(config) if config else config)
|
2022-11-14 13:48:50 +01:00
|
|
|
)
|
2021-12-25 16:29:10 -08:00
|
|
|
|
2023-03-08 15:43:33 +05:30
|
|
|
@staticmethod
|
|
|
|
def get_assume_role_config(
|
|
|
|
config: AWSCredentials,
|
2025-01-03 10:51:15 +01:00
|
|
|
return_type: Type[
|
|
|
|
AWSAssumeRoleCredentialFormat
|
|
|
|
] = AWSAssumeRoleCredentialWrapper,
|
|
|
|
) -> Optional[AWSAssumeRoleCredentialFormat]:
|
2023-03-08 15:43:33 +05:30
|
|
|
"""
|
|
|
|
Get temporary credentials from assumed role
|
|
|
|
"""
|
|
|
|
session = AWSClient._get_session(
|
|
|
|
config.awsAccessKeyId,
|
|
|
|
config.awsSecretAccessKey,
|
|
|
|
config.awsSessionToken,
|
|
|
|
config.awsRegion,
|
|
|
|
config.profileName,
|
|
|
|
)
|
|
|
|
sts_client = session.client("sts")
|
|
|
|
if config.assumeRoleSourceIdentity:
|
|
|
|
resp = sts_client.assume_role(
|
|
|
|
RoleArn=config.assumeRoleArn,
|
|
|
|
RoleSessionName=config.assumeRoleSessionName,
|
|
|
|
SourceIdentity=config.assumeRoleSourceIdentity,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
resp = sts_client.assume_role(
|
|
|
|
RoleArn=config.assumeRoleArn,
|
|
|
|
RoleSessionName=config.assumeRoleSessionName,
|
2021-12-25 16:29:10 -08:00
|
|
|
)
|
2023-03-08 15:43:33 +05:30
|
|
|
|
|
|
|
if resp:
|
|
|
|
credentials = resp.get("Credentials", {})
|
2025-01-03 10:51:15 +01:00
|
|
|
creds_wrapper = AWSAssumeRoleCredentialWrapper(
|
2023-03-08 15:43:33 +05:30
|
|
|
accessKeyId=credentials.get("AccessKeyId"),
|
|
|
|
secretAccessKey=credentials.get("SecretAccessKey"),
|
|
|
|
sessionToken=credentials.get("SessionToken"),
|
2025-01-03 10:51:15 +01:00
|
|
|
expiryTime=credentials.get("Expiration").isformat(),
|
2021-12-25 16:29:10 -08:00
|
|
|
)
|
2025-01-03 10:51:15 +01:00
|
|
|
if return_type == Dict:
|
|
|
|
return creds_wrapper.model_dump(by_alias=True)
|
|
|
|
return creds_wrapper
|
|
|
|
|
2023-03-08 15:43:33 +05:30
|
|
|
return None
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _get_session(
|
2023-05-19 09:43:11 +02:00
|
|
|
aws_access_key_id: Optional[str],
|
|
|
|
aws_secret_access_key: Optional[CustomSecretStr],
|
|
|
|
aws_session_token: Optional[str],
|
|
|
|
aws_region: str,
|
2023-03-08 15:43:33 +05:30
|
|
|
profile=None,
|
2025-01-03 10:51:15 +01:00
|
|
|
refresh_using: Optional[Callable] = None,
|
2023-03-08 15:43:33 +05:30
|
|
|
) -> Session:
|
2023-05-19 09:43:11 +02:00
|
|
|
"""
|
|
|
|
The only required param for boto3 is the region.
|
|
|
|
The rest of credentials will have fallback strategies based on
|
|
|
|
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#configuring-credentials
|
|
|
|
"""
|
2025-01-03 10:51:15 +01:00
|
|
|
if refresh_using:
|
|
|
|
refreshable_creds = RefreshableCredentials.create_from_metadata(
|
|
|
|
metadata=refresh_using(),
|
|
|
|
refresh_using=refresh_using,
|
|
|
|
method="sts-assume-role",
|
|
|
|
)
|
|
|
|
session = get_session()
|
|
|
|
session._credentials = refreshable_creds # pylint: disable=protected-access
|
|
|
|
return Session(
|
|
|
|
botocore_session=session, region_name=aws_region, profile_name=profile
|
|
|
|
)
|
|
|
|
|
2023-03-08 15:43:33 +05:30
|
|
|
return Session(
|
|
|
|
aws_access_key_id=aws_access_key_id,
|
|
|
|
aws_secret_access_key=aws_secret_access_key.get_secret_value()
|
|
|
|
if aws_secret_access_key
|
|
|
|
else None,
|
|
|
|
aws_session_token=aws_session_token,
|
|
|
|
region_name=aws_region,
|
|
|
|
profile_name=profile,
|
|
|
|
)
|
|
|
|
|
|
|
|
def create_session(self) -> Session:
|
|
|
|
if self.config.assumeRoleArn:
|
2025-01-03 10:51:15 +01:00
|
|
|
return AWSClient._get_session(
|
|
|
|
None,
|
|
|
|
None,
|
|
|
|
None,
|
|
|
|
self.config.awsRegion,
|
|
|
|
self.config.profileName,
|
|
|
|
refresh_using=partial(
|
|
|
|
AWSClient.get_assume_role_config, self.config, Dict
|
|
|
|
),
|
|
|
|
)
|
2023-03-08 15:43:33 +05:30
|
|
|
|
|
|
|
return AWSClient._get_session(
|
|
|
|
self.config.awsAccessKeyId,
|
|
|
|
self.config.awsSecretAccessKey,
|
|
|
|
self.config.awsSessionToken,
|
|
|
|
self.config.awsRegion,
|
|
|
|
self.config.profileName,
|
|
|
|
)
|
2021-12-25 16:29:10 -08:00
|
|
|
|
|
|
|
def get_client(self, service_name: str) -> Any:
|
2022-08-19 16:15:40 +02:00
|
|
|
# initialize the client depending on the AWSCredentials passed
|
|
|
|
if self.config is not None:
|
2024-12-04 09:32:25 +01:00
|
|
|
logger.debug(f"Getting AWS client for service [{service_name}]")
|
2023-03-08 15:43:33 +05:30
|
|
|
session = self.create_session()
|
2022-12-15 13:00:32 +05:30
|
|
|
if self.config.endPointURL is not None:
|
|
|
|
return session.client(
|
2024-06-05 21:18:37 +02:00
|
|
|
service_name=service_name, endpoint_url=str(self.config.endPointURL)
|
2022-12-15 13:00:32 +05:30
|
|
|
)
|
2022-08-19 16:15:40 +02:00
|
|
|
return session.client(service_name=service_name)
|
2022-10-11 17:15:02 +02:00
|
|
|
|
2024-12-04 09:32:25 +01:00
|
|
|
logger.debug(f"Getting AWS default client for service [{service_name}]")
|
2022-10-11 17:15:02 +02:00
|
|
|
# initialized with the credentials loaded from running machine
|
|
|
|
return boto3.client(service_name=service_name)
|
2022-02-08 00:22:11 +05:30
|
|
|
|
|
|
|
def get_resource(self, service_name: str) -> Any:
|
2023-03-08 15:43:33 +05:30
|
|
|
session = self.create_session()
|
2022-12-15 13:00:32 +05:30
|
|
|
if self.config.endPointURL is not None:
|
|
|
|
return session.resource(
|
2024-06-05 21:18:37 +02:00
|
|
|
service_name=service_name, endpoint_url=str(self.config.endPointURL)
|
2022-12-15 13:00:32 +05:30
|
|
|
)
|
2022-02-08 00:22:11 +05:30
|
|
|
return session.resource(service_name=service_name)
|
2022-04-22 11:30:59 +05:30
|
|
|
|
2023-06-16 13:18:12 +05:30
|
|
|
def get_rds_client(self):
|
|
|
|
return self.get_client(AWSServices.RDS.value)
|
|
|
|
|
2023-03-26 10:35:34 +01:00
|
|
|
def get_s3_client(self):
|
|
|
|
return self.get_client(AWSServices.S3.value)
|
|
|
|
|
|
|
|
def get_cloudwatch_client(self):
|
|
|
|
return self.get_client(AWSServices.CLOUDWATCH.value)
|
|
|
|
|
2023-01-02 13:52:27 +01:00
|
|
|
def get_dynamo_client(self):
|
|
|
|
return self.get_resource(AWSServices.DYNAMO_DB.value)
|
2022-06-27 15:08:41 +05:30
|
|
|
|
2023-01-02 13:52:27 +01:00
|
|
|
def get_glue_client(self):
|
|
|
|
return self.get_client(AWSServices.GLUE.value)
|
2022-11-02 16:12:45 +05:30
|
|
|
|
2023-01-02 13:52:27 +01:00
|
|
|
def get_sagemaker_client(self):
|
|
|
|
return self.get_client(AWSServices.SAGEMAKER.value)
|
2022-11-03 22:49:20 +05:30
|
|
|
|
2023-01-02 13:52:27 +01:00
|
|
|
def get_kinesis_client(self):
|
|
|
|
return self.get_client(AWSServices.KINESIS.value)
|
2022-11-08 06:24:49 -08:00
|
|
|
|
2023-01-02 13:52:27 +01:00
|
|
|
def get_quicksight_client(self):
|
|
|
|
return self.get_client(AWSServices.QUICKSIGHT.value)
|
2023-04-03 16:51:55 +05:30
|
|
|
|
|
|
|
def get_athena_client(self):
|
|
|
|
return self.get_client(AWSServices.ATHENA.value)
|
2024-01-16 14:24:31 +05:30
|
|
|
|
|
|
|
def get_lake_formation_client(self):
|
|
|
|
return self.get_client(AWSServices.LAKE_FORMATION.value)
|