rambleraptor commented on code in PR #3751: URL: https://github.com/apache/iceberg-python/pull/3751#discussion_r4393559666
########## pyiceberg/catalog/rest/credential_provider.py: ########## @@ -0,0 +1,179 @@ +# 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. +from __future__ import annotations + +import threading +from collections.abc import Callable +from dataclasses import dataclass, field +from time import time +from typing import TYPE_CHECKING +from urllib.parse import urlparse + +from pyiceberg.catalog.rest.scan_planning import StorageCredential +from pyiceberg.io import ( + GCS_TOKEN, + GCS_TOKEN_EXPIRES_AT_MS, + S3_ACCESS_KEY_ID, + S3_SECRET_ACCESS_KEY, + S3_SESSION_TOKEN, + S3_SESSION_TOKEN_EXPIRES_AT_MS, +) +from pyiceberg.typedef import Properties + +if TYPE_CHECKING: + from pyiceberg.catalog.rest import LoadCredentialsResponse + +REFRESH_CREDENTIALS_ENABLED = "client.refresh-credentials-enabled" +_REFRESH_MARGIN_MS = 300_000 + + +@dataclass(frozen=True) +class _CredentialPolicy: + required_properties: tuple[str, ...] + expiration_properties: tuple[str, ...] + + def expiration_ms(self, config: Properties) -> int | None: + for key in self.expiration_properties: + if key in config: + try: + return int(config[key]) + except (TypeError, ValueError, OverflowError): + raise ValueError(f"Invalid expiration property: {key}") from None + return None + + def normalize(self, config: Properties) -> Properties: + properties = dict(config) + if (expiration := self.expiration_ms(properties)) is not None: + for key in self.required_properties: + if not properties.get(key): + raise ValueError(f"Missing vended credential property: {key}") Review Comment: This is being called on every credential, even if refresh is off. It doesn't appear that this happens in Java. Even if it did, this would potentially break users who are using credentials currently with refresh off. We should make sure that this only works for refresh, since the property acts as a feature flag for us automatically. ########## mkdocs/docs/configuration.md: ########## @@ -419,6 +419,48 @@ catalog: When server-side planning returns `storage-credentials` on a completed plan, PyIceberg applies them to the scan-scoped FileIO (layered on top of the existing table/load-time IO properties) so planned data and delete files can be read using the creds vended by the server. +#### Vended credential refresh + +Enable automatic refresh for long-running reads and writes that use temporary storage credentials from a REST catalog: + +```yaml +catalog: + default: + type: rest + uri: https://rest-catalog.example/ + client.refresh-credentials-enabled: true + header.X-Iceberg-Access-Delegation: vended-credentials +``` + +`client.refresh-credentials-enabled` defaults to `false`. Both `PyArrowFileIO` and `FsspecFileIO` support refresh for S3 and GCS. +The catalog must advertise its table credentials endpoint (`GET /v1/{prefix}/namespaces/{namespace}/tables/{table}/credentials`) +in its configuration response. Enabling refresh when vended credentials are present but that endpoint is unsupported raises an error while loading the table. + +| Storage | URI schemes | Required temporary credential properties | Expiration property | +| --- | --- | --- | --- | +| S3 | `s3`, `s3a`, `s3n` | `s3.access-key-id`, `s3.secret-access-key`, `s3.session-token` | `s3.session-token-expires-at-ms` | +| GCS | `gs`, `gcs` | `gcs.oauth2.token` | `gcs.oauth2.token-expires-at` | + +Expiration values are integer milliseconds since the Unix epoch. GCS also accepts the `gcs.oauth2.token_expires_at` spelling; +the canonical `gcs.oauth2.token-expires-at` takes precedence when both are supplied. +Credentials without an expiration are not automatically refreshed; the selected backend's credential requirements still apply. + +The client selects the longest matching prefix in `storage-credentials` for each file location. +If a table response has no `storage-credentials`, temporary credentials in its legacy `config` are also eligible for refresh. +Refreshed credentials take precedence over baseline configuration without retaining overrides from a previous credential snapshot. + +Refresh occurs on demand, starting up to five minutes before expiration. For shorter lifetimes, the margin is bounded to half +the remaining lifetime when credentials are received, so a fresh short-lived token is reused between refreshes. +Concurrent accesses share a successful refresh. Catalog errors propagate, and missing, incomplete, or already-expired refresh results are rejected. + +Refresh applies to metadata, manifests, data and delete files, staged writes, and scan-scoped credentials. +Retained file handles resolve current credentials when opened or created again. An already-open native stream keeps its original credentials; +its lifetime should fit within the credential lifetime. External engines that manage their own storage clients must manage their own credential refresh. + +FileIO instances remain pickleable with refresh enabled. Deserialization performs no network requests; catalog access and authentication Review Comment: I'm not sure if we need to keep this last paragraph. This seems like a code behavior and not super useful for users. ########## pyiceberg/catalog/rest/credential_provider.py: ########## @@ -0,0 +1,179 @@ +# 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. +from __future__ import annotations + +import threading +from collections.abc import Callable +from dataclasses import dataclass, field +from time import time +from typing import TYPE_CHECKING +from urllib.parse import urlparse + +from pyiceberg.catalog.rest.scan_planning import StorageCredential +from pyiceberg.io import ( + GCS_TOKEN, + GCS_TOKEN_EXPIRES_AT_MS, + S3_ACCESS_KEY_ID, + S3_SECRET_ACCESS_KEY, + S3_SESSION_TOKEN, + S3_SESSION_TOKEN_EXPIRES_AT_MS, +) +from pyiceberg.typedef import Properties + +if TYPE_CHECKING: + from pyiceberg.catalog.rest import LoadCredentialsResponse + +REFRESH_CREDENTIALS_ENABLED = "client.refresh-credentials-enabled" +_REFRESH_MARGIN_MS = 300_000 + + +@dataclass(frozen=True) +class _CredentialPolicy: + required_properties: tuple[str, ...] + expiration_properties: tuple[str, ...] + + def expiration_ms(self, config: Properties) -> int | None: + for key in self.expiration_properties: + if key in config: + try: + return int(config[key]) + except (TypeError, ValueError, OverflowError): + raise ValueError(f"Invalid expiration property: {key}") from None + return None + + def normalize(self, config: Properties) -> Properties: + properties = dict(config) + if (expiration := self.expiration_ms(properties)) is not None: + for key in self.required_properties: + if not properties.get(key): + raise ValueError(f"Missing vended credential property: {key}") + for key in self.expiration_properties: + properties.pop(key, None) + properties[self.expiration_properties[0]] = str(expiration) + return properties + + +_S3_POLICY = _CredentialPolicy((S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_SESSION_TOKEN), (S3_SESSION_TOKEN_EXPIRES_AT_MS,)) +_GCS_POLICY = _CredentialPolicy((GCS_TOKEN,), (GCS_TOKEN_EXPIRES_AT_MS, "gcs.oauth2.token_expires_at")) +_POLICIES_BY_SCHEME = { + "s3": _S3_POLICY, + "s3a": _S3_POLICY, + "s3n": _S3_POLICY, + "gs": _GCS_POLICY, + "gcs": _GCS_POLICY, +} + + +def is_s3_credential_expired(config: Properties, threshold_seconds: int = 300) -> bool: + """Return whether an S3 credential expires within the given threshold.""" + expiration = _S3_POLICY.expiration_ms(config) + return expiration is not None and expiration - time() * 1000 <= threshold_seconds * 1000 + + +def resolve_storage_credentials(storage_credentials: list[StorageCredential], location: str | None) -> Properties: + """Return credential properties for the longest matching storage prefix.""" + if location is None: + return {} + match = max( + (cred for cred in storage_credentials if location.startswith(cred.prefix)), key=lambda c: len(c.prefix), default=None + ) + if match is None: + return {} + policy = _POLICIES_BY_SCHEME.get(urlparse(location).scheme) + return policy.normalize(match.config) if policy is not None else dict(match.config) + + +def _credentials_from_config(config: Properties, location: str) -> list[StorageCredential]: + scheme = urlparse(location).scheme + policy = _POLICIES_BY_SCHEME.get(scheme) + if policy is None or policy.expiration_ms(config) is None: + return [] + keys = (*policy.required_properties, *policy.expiration_properties) + properties = {key: config[key] for key in keys if key in config} + return [StorageCredential(prefix=f"{scheme}://", config=properties)] + + +@dataclass(frozen=True) +class _CredentialState: + prefix: str + config: Properties = field(repr=False) + expiration_ms: int | None + refresh_at_ms: int | None + + +def _credential_states(credentials: list[StorageCredential], received_at_ms: int) -> tuple[_CredentialState, ...]: + states = [] + for credential in credentials: + policy = _POLICIES_BY_SCHEME.get(urlparse(credential.prefix).scheme) + config = policy.normalize(credential.config) if policy is not None else dict(credential.config) + expiration = policy.expiration_ms(config) if policy is not None else None + refresh_at = None + if expiration is not None: + refresh_at = expiration - min(_REFRESH_MARGIN_MS, max(0, expiration - received_at_ms) // 2) + states.append(_CredentialState(credential.prefix, config, expiration, refresh_at)) + return tuple(states) + + +def _matching_state(states: tuple[_CredentialState, ...], location: str) -> _CredentialState | None: + return max((state for state in states if location.startswith(state.prefix)), key=lambda s: len(s.prefix), default=None) + + +class CredentialsProvider: + """Resolve and refresh prefix-scoped storage credentials for a REST table.""" + + def __init__( + self, + storage_credentials: list[StorageCredential], + refresh_fn: Callable[[], LoadCredentialsResponse], + ) -> None: + self._states = _credential_states(storage_credentials, int(time() * 1000)) + self._refresh_fn = refresh_fn + self._lock = threading.Lock() + + def __getstate__(self) -> dict[str, object]: + """Serialize absolute refresh deadlines without the process-local lock.""" + return {key: value for key, value in self.__dict__.items() if key != "_lock"} + + def __setstate__(self, state: dict[str, object]) -> None: + """Restore credential state and create a new lock.""" + self.__dict__.update(state) + self._lock = threading.Lock() + + def properties_for(self, location: str) -> Properties: + """Return the current properties for a location, refreshing when due.""" + match = _matching_state(self._states, location) + if match is None: + return {} + if match.refresh_at_ms is not None and time() * 1000 >= match.refresh_at_ms: + with self._lock: + match = _matching_state(self._states, location) + if match is None: + raise ValueError("No vended credentials for the requested location after refresh") + if match.refresh_at_ms is not None and time() * 1000 >= match.refresh_at_ms: + response = self._refresh_fn() + now_ms = int(time() * 1000) + states = _credential_states(response.storage_credentials, now_ms) + refreshed = _matching_state(states, location) + if refreshed is None: Review Comment: If the refresh fails, this will immediately throw a ValueError. Here's the rough idea of how Java handles this: - Credential due for refresh, but hasn't expired yet - Refreshing threw an error of some kind - If the old credential is still valid, we should use it and not immediately surface the failed refresh to the user In this situation, we should suppress the exception, log a warning, and use the old credential. ########## pyiceberg/table/__init__.py: ########## @@ -2476,7 +2476,13 @@ def _plan_files_server_side(self) -> Iterable[FileScanTask]: result = self.catalog._plan_scan_result(self.table_identifier, request) location = result.tasks[0].file.file_path if result.tasks else None - plan_io = self.catalog._file_io_from_plan(self.io.properties, result.storage_credentials, location) + plan_io = self.catalog._file_io_from_plan( + self.io.properties, + result.storage_credentials, + location, + identifier=self.table_identifier, + existing_io=self.io, Review Comment: Can you plumb through the plan_id as well? We'll want that to eventually get over to the load_credentials endpoint -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
