|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# |
| 17 | +from datetime import datetime |
| 18 | + |
| 19 | +from pydantic import Field |
| 20 | +from requests import HTTPError, Session |
| 21 | + |
| 22 | +from pyiceberg.catalog import URI |
| 23 | +from pyiceberg.catalog.rest.response import _handle_non_200_response |
| 24 | +from pyiceberg.catalog.rest.scan_planning import StorageCredential |
| 25 | +from pyiceberg.exceptions import ValidationError, ValidationException |
| 26 | +from pyiceberg.io import ( |
| 27 | + AWS_ACCESS_KEY_ID, |
| 28 | + AWS_SECRET_ACCESS_KEY, |
| 29 | + AWS_SESSION_TOKEN, |
| 30 | + S3_ACCESS_KEY_ID, |
| 31 | + S3_SECRET_ACCESS_KEY, |
| 32 | + S3_SESSION_TOKEN, |
| 33 | +) |
| 34 | +from pyiceberg.typedef import IcebergBaseModel, Properties |
| 35 | +from pyiceberg.utils.properties import get_first_property_value |
| 36 | + |
| 37 | +S3_SESSION_TOKEN_EXPIRES_AT_MS = "s3.session-token-expires-at-ms" |
| 38 | +CREDENTIALS_ENDPOINT = "client.refresh-credentials-endpoint" |
| 39 | +REFRESH_CREDENTIALS_ENABLED = "client.refresh-credentials-enabled" |
| 40 | + |
| 41 | + |
| 42 | +class LoadCredentialsResponse(IcebergBaseModel): |
| 43 | + credentials: list[StorageCredential] = Field(alias="storage-credentials") |
| 44 | + |
| 45 | + |
| 46 | +class VendedCredentialsProvider: |
| 47 | + _session: Session |
| 48 | + _properties: Properties |
| 49 | + |
| 50 | + def __init__(self, session: Session, properties: Properties): |
| 51 | + self._session = session |
| 52 | + self._properties = properties |
| 53 | + |
| 54 | + def _extract_s3_credentials_from(self, props: Properties) -> tuple[str | None, str | None, str | None, str | None]: |
| 55 | + """Extract only S3 credentials from properties.""" |
| 56 | + access_key = get_first_property_value(props, S3_ACCESS_KEY_ID, AWS_ACCESS_KEY_ID) |
| 57 | + secret_key = get_first_property_value(props, S3_SECRET_ACCESS_KEY, AWS_SECRET_ACCESS_KEY) |
| 58 | + session_token = get_first_property_value(props, S3_SESSION_TOKEN, AWS_SESSION_TOKEN) |
| 59 | + expiry = get_first_property_value(props, S3_SESSION_TOKEN_EXPIRES_AT_MS) |
| 60 | + |
| 61 | + return access_key, secret_key, session_token, expiry |
| 62 | + |
| 63 | + def _to_credentials_property_map( |
| 64 | + self, access_key: str | None, secret_key: str | None, session_token: str | None, expiry: str | None |
| 65 | + ) -> Properties: |
| 66 | + return { |
| 67 | + S3_ACCESS_KEY_ID: access_key, |
| 68 | + S3_SECRET_ACCESS_KEY: secret_key, |
| 69 | + S3_SESSION_TOKEN: session_token, |
| 70 | + S3_SESSION_TOKEN_EXPIRES_AT_MS: expiry, |
| 71 | + } |
| 72 | + |
| 73 | + def needs_refresh(self) -> bool: |
| 74 | + """Return True if the S3 session token expires within 300s.""" |
| 75 | + expiry = get_first_property_value(self._properties, S3_SESSION_TOKEN_EXPIRES_AT_MS) |
| 76 | + if expiry is None: |
| 77 | + return False |
| 78 | + expires_at = datetime.fromtimestamp(int(expiry) / 1000) |
| 79 | + seconds_remaining = (expires_at - datetime.now()).total_seconds() |
| 80 | + return seconds_remaining < 300 |
| 81 | + |
| 82 | + def _build_refresh_endpoint(self) -> str: |
| 83 | + """Build credential refresh endpoint from properties.""" |
| 84 | + catalog_uri = get_first_property_value(self._properties, URI) |
| 85 | + credentials_path = get_first_property_value(self._properties, CREDENTIALS_ENDPOINT) |
| 86 | + |
| 87 | + if catalog_uri is None: |
| 88 | + raise ValidationException("Invalid catalog endpoint: None") |
| 89 | + |
| 90 | + if credentials_path is None: |
| 91 | + raise ValidationException("Invalid credentials endpoint: None") |
| 92 | + |
| 93 | + return str(catalog_uri).rstrip("/") + "/" + str(credentials_path).lstrip("/") |
| 94 | + |
| 95 | + def _get_new_credentials(self) -> LoadCredentialsResponse | None: |
| 96 | + try: |
| 97 | + http_response = self._session.get(self._build_refresh_endpoint()) |
| 98 | + http_response.raise_for_status() |
| 99 | + return LoadCredentialsResponse.model_validate_json(http_response.text) |
| 100 | + except HTTPError as exc: |
| 101 | + _handle_non_200_response(exc, {}) |
| 102 | + return None |
| 103 | + |
| 104 | + def get_credentials(self) -> Properties: |
| 105 | + """Retrieve current S3 credentials, refreshing from the endpoint if near expiry.""" |
| 106 | + access_key, secret_key, session_token, expiry = self._extract_s3_credentials_from(self._properties) |
| 107 | + |
| 108 | + if not self.needs_refresh(): |
| 109 | + return self._to_credentials_property_map(access_key, secret_key, session_token, expiry) |
| 110 | + |
| 111 | + creds = self._get_new_credentials() |
| 112 | + |
| 113 | + if creds is None: |
| 114 | + raise ValidationError("Load credential response is None") |
| 115 | + if not creds.credentials: |
| 116 | + raise ValueError("Invalid S3 Credentials: empty") |
| 117 | + if len(creds.credentials) > 1: |
| 118 | + raise ValueError("Invalid S3 Credentials: only one S3 credential should exists") |
| 119 | + |
| 120 | + updated_creds = self._extract_s3_credentials_from(creds.credentials[0].config) |
| 121 | + updated_map = self._to_credentials_property_map(*updated_creds) |
| 122 | + |
| 123 | + # Update internal properties with new credentials |
| 124 | + self._properties = {**self._properties, **updated_map} |
| 125 | + |
| 126 | + return updated_map |
0 commit comments