Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions packages/kumo-adls/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,13 @@ for validation, ownership, and Studio adoption follow-ups.

## Authentication and resources

Without an identity, requests use Azure's ambient credential chain. An explicit
`ADLSIdentity(tenant_id=..., client_id=..., cloud=...)` uses workload federation
with `AZURE_FEDERATED_TOKEN_FILE`. Secrets, storage keys, and SAS tokens are not
connector arguments. The identity cloud must match the public, US Government,
`ADLSIdentity()` selects Azure's ambient credential chain; connectors use this
identity when none is supplied. Its Azure cloud is inferred from the storage
endpoint unless explicitly constrained. Supplying tenant and client IDs to
`ADLSIdentity` selects workload federation with `AZURE_FEDERATED_TOKEN_FILE`.
Secrets, storage keys, and SAS tokens are not connector arguments. The identity cloud must match the public, US Government,
or China URI endpoint. Native writes require the process's `AZURE_TENANT_ID`
and `AZURE_CLIENT_ID` to match an explicit identity and
and `AZURE_CLIENT_ID` to match the workload identity and
`AZURE_FEDERATED_TOKEN_FILE` to name its projected token. Other per-connector
identities remain read-only. Native writes also require `AZURE_AUTHORITY_HOST`
to match the cloud (public is the default). Unsupported configurations fail
Expand Down
18 changes: 16 additions & 2 deletions packages/kumo-adls/docs/implementation.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ A native filesystem is reused within one sink access, with thread-safe first
construction; it is not cached across accesses or identities. The provider
accepts pyarrow 16 through 24; CI runs its suite at both ends of that range.

Without an explicit identity, writes use Arrow's C++ ambient credential chain;
reads use Python Azure Identity. These chains can select different ambient
Explicit ambient principals use Arrow's C++ ambient credential chain for writes
and Python Azure Identity for reads. These chains can select different ambient
credentials. Explicit workload writes require process `AZURE_TENANT_ID` and
`AZURE_CLIENT_ID` to equal the selected identity, plus
`AZURE_FEDERATED_TOKEN_FILE`. They select only Arrow's workload credential,
Expand Down Expand Up @@ -189,3 +189,17 @@ Follow-ups:
credential-bound functions and validate them individually. Existing SDK
writer helpers are not the Studio default. SAS generation, multipart upload,
and atomic promotion are separate work; native engine output is unchanged.

### Explicit ambient configuration

Engine connectors normalize an omitted identity to `ADLSIdentity()`. Its
`ADLSAmbientIdentityConfig` is local to provider connections and leaves the hosted
`ADLSIdentityConfig` workload contract unchanged. Ambient SDK credentials derive
the Azure authority from the selected storage endpoint. An optional cloud
constraint rejects mismatching endpoints. Standalone identity probing uses the
constraint or public Azure when no target endpoint is available.

Provider backends and SDK-session helpers require an explicit `Principal` for
both ambient and workload authentication. Workload native writes continue to
require matching process identity settings; ambient native writes use Arrow's
ambient chain and retain the endpoint/authority checks.
6 changes: 3 additions & 3 deletions packages/kumo-adls/src/kumo_adls/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
ObjectStoreRoot,
ObjectStoreSessions,
)
from kumo_core.sources.principals import IdentityRef
from kumo_core.sources.principals import Principal
from kumo_core.sources.types import ReadMode
from kumoapi.adls import (
normalize_adls_root_uri,
Expand Down Expand Up @@ -95,7 +95,7 @@ def _source_access(self, connector, bucket, region):
del region
_, host = bucket.split('@', 1)
account, suffix = host.split('.', 1)
client = session_for(self._principal(connector), account, suffix)
client = session_for(self._identity, account, suffix)
return source_access(client, account, suffix)

def _over(self, connector, bucket, root, region):
Expand Down Expand Up @@ -140,7 +140,7 @@ class ADLSSourceBackend(ADLSSessions, ObjectStoreSourceBackend):
uri_source = ADLSURISource
source_table = ADLSSourceTable

def __init__(self, identity: Optional[IdentityRef] = None,
def __init__(self, identity: Principal,
storage_namespace: Optional[str] = None,
mode: Optional[ReadMode] = None):
super().__init__(identity, storage_namespace)
Expand Down
25 changes: 14 additions & 11 deletions packages/kumo-adls/src/kumo_adls/native_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,34 @@
import threading
from urllib.parse import urlencode, urlsplit

from kumo_core.sources.principals import Principal
from kumoapi.adls import (
normalize_adls_endpoint_suffix,
normalize_adls_filesystem,
normalize_adls_storage_account,
)
from kumoapi.data_source import ADLSIdentityConfig
from kumoapi.data_source import ADLSAmbientIdentityConfig, ADLSIdentityConfig
from pyarrow.fs import AzureFileSystem, FileSystem, FSSpecHandler

from .clouds import CLOUDS


def validate_output_configuration(principal, account, suffix, container):
def validate_output_configuration(
principal: Principal, account: str, suffix: str,
container: str) -> tuple[str, str, str]:
"""Validate native output locally, without constructing storage clients."""
account = normalize_adls_storage_account(account)
suffix = normalize_adls_endpoint_suffix(suffix)
container = normalize_adls_filesystem(container)
cloud, (_, _, authority) = next((cloud, values)
for cloud, values in CLOUDS.items()
if values[0] == suffix)
if principal is not None:
config = principal.config
if not isinstance(config, ADLSIdentityConfig):
raise ValueError('The selected identity is not an ADLS identity')
if config.cloud != cloud:
raise ValueError(
'ADLS endpoint does not match the selected identity cloud')
config = principal.config
if not isinstance(config, (ADLSIdentityConfig, ADLSAmbientIdentityConfig)):
raise ValueError('The selected identity is not an ADLS identity')
if config.cloud is not None and config.cloud != cloud:
raise ValueError('ADLS endpoint does not match the selected identity cloud')
if isinstance(config, ADLSIdentityConfig):
if (os.environ.get('AZURE_TENANT_ID') != config.tenant_id
or os.environ.get('AZURE_CLIENT_ID') != config.client_id or
not os.environ.get('AZURE_FEDERATED_TOKEN_FILE', '').strip()):
Expand All @@ -54,14 +56,15 @@ def validate_output_configuration(principal, account, suffix, container):
return account, suffix, container


def filesystem_for(principal, account, suffix, container):
def filesystem_for(principal: Principal, account: str, suffix: str,
container: str) -> FileSystem:
"""Bind native output without changing or substituting an identity."""
account, suffix, container = validate_output_configuration(
principal, account, suffix, container)
options = dict(
blob_storage_authority='.' + suffix.replace('dfs.', 'blob.', 1),
dfs_storage_authority='.' + suffix)
if principal is None:
if isinstance(principal.config, ADLSAmbientIdentityConfig):
return AzureFileSystem(account_name=account, **options)

# Arrow's workload credential reads environment configuration at creation;
Expand Down
65 changes: 51 additions & 14 deletions packages/kumo-adls/src/kumo_adls/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,47 +4,84 @@

import atexit
import threading
from typing import TypeAlias

from azure.identity import DefaultAzureCredential, WorkloadIdentityCredential
from azure.storage.filedatalake import DataLakeServiceClient
from kumo_core.sources.principals import Principal
from kumoapi.data_source import ADLSIdentityConfig
from kumoapi.data_source import (
ADLSAmbientIdentityConfig,
ADLSIdentityConfig,
AzureCloud,
)

from .client import create_client
from .clouds import CLOUDS
from .errors import translated

_AzureCredential: TypeAlias = DefaultAzureCredential | WorkloadIdentityCredential

def credential_for(principal: Principal | None, endpoint_suffix: str):

def credential_for(
principal: Principal, endpoint_suffix: str,
) -> tuple[_AzureCredential, str]:
"""Resolve credentials for the endpoint's Azure cloud.

Args:
principal: Explicit ambient or workload identity configuration.
endpoint_suffix: Azure Data Lake endpoint suffix identifying the cloud.

Returns:
An owned Azure credential and the storage audience.

Raises:
ValueError: The endpoint is unsupported or conflicts with the identity.
"""
cloud = next(
(cloud
for cloud, values in CLOUDS.items() if values[0] == endpoint_suffix),
None)
if cloud is None:
raise ValueError('Unsupported ADLS endpoint suffix')
_, audience, authority = CLOUDS[cloud]
if principal is None:
return DefaultAzureCredential(authority=authority), audience
config = principal.config
if not isinstance(config, ADLSIdentityConfig):
if not isinstance(config, (ADLSIdentityConfig, ADLSAmbientIdentityConfig)):
raise ValueError('The selected identity is not an ADLS identity')
if config.cloud != cloud:
if config.cloud is not None and config.cloud != cloud:
raise ValueError(
'ADLS endpoint does not match the selected identity cloud')
# Explicit identities must never fall back to another ambient principal.
if isinstance(config, ADLSAmbientIdentityConfig):
return DefaultAzureCredential(authority=authority), audience
# Workload identities must never fall back to another ambient principal.
return WorkloadIdentityCredential(tenant_id=config.tenant_id,
client_id=config.client_id,
authority=authority), audience


_LOCK = threading.RLock()
_SESSIONS = {}
_SESSIONS: dict[tuple[str, str, str, str],
tuple[DataLakeServiceClient, _AzureCredential]] = {}


def session_for(
principal: Principal, account: str, suffix: str
) -> DataLakeServiceClient:
"""Return a cached client bound to an explicit principal and storage account.

Args:
principal: Ambient or workload authentication configuration.
account: Azure storage account name.
suffix: Data Lake endpoint suffix selecting the Azure cloud.

Returns:
The session cache's storage client.

def session_for(principal: Principal | None, account: str, suffix: str):
Raises:
ValueError: The identity and endpoint configuration are incompatible.
"""
# Config participates in the key so a rotated identity cannot reuse a
# client signed as its predecessor. Tokens refresh inside Azure Identity.
key = (principal.name if principal else None,
repr(principal.config) if principal else None, account, suffix)
key = (principal.name, repr(principal.config), account, suffix)
with _LOCK:
if key not in _SESSIONS:
with translated():
Expand Down Expand Up @@ -82,10 +119,10 @@ def close(identity_name: str | None = None) -> None:
def probe(principal: Principal) -> None:
"""Validate token acquisition; this does not attest storage permissions."""
config = principal.config
if not isinstance(config, ADLSIdentityConfig):
if not isinstance(config, (ADLSIdentityConfig, ADLSAmbientIdentityConfig)):
raise ValueError('The selected identity is not an ADLS identity')
cloud = AzureCloud.PUBLIC if config.cloud is None else config.cloud
with translated():
credential, audience = credential_for(principal,
CLOUDS[config.cloud][0])
credential, audience = credential_for(principal, CLOUDS[cloud][0])
with credential:
credential.get_token(f'{audience}/.default')
4 changes: 2 additions & 2 deletions packages/kumo-adls/src/kumo_adls/sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def preflight_write_files(self, connector, table_name,
bucket, path, region = self._resolved(connector, table_name)
container, host = bucket.split('@', 1)
account, suffix = host.split('.', 1)
validate_output_configuration(self._principal(connector), account,
validate_output_configuration(self._identity, account,
suffix, container)
if write_mode is None and table_name.endswith('/'):
self._require_empty_destination(
Expand All @@ -53,7 +53,7 @@ def _filesystem(self, connector, bucket, region):
account, suffix = host.split('.', 1)
# Model reads use this filesystem too; bind output credentials
# only when a native output stream is actually requested.
native = partial(filesystem_for, self._principal(connector),
native = partial(filesystem_for, self._identity,
account, suffix, container)
return PyFileSystem(
NativeOutputHandler(filesystem.handler.fs,
Expand Down
6 changes: 4 additions & 2 deletions packages/kumo-adls/tests/live/test_live_filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from kumo_adls.session import session_for
from kumoapi.adls import normalize_adls_root_uri
from pyarrow.fs import FileType, FSSpecHandler, PyFileSystem
from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL

ROOT = os.environ.get('KUMO_ADLS_LIVE_ROOT')
if not ROOT:
Expand All @@ -27,8 +28,9 @@ def live_directory():
parsed = urlsplit(normalize_adls_root_uri(ROOT))
_, host = parsed.netloc.split('@', 1)
account, suffix = host.split('.', 1)
filesystem = ADLSFileSystem(session_for(None, account, suffix), account,
suffix)
filesystem = ADLSFileSystem(
session_for(AMBIENT_PRINCIPAL, account, suffix), account, suffix
)
path = parsed.netloc + unquote(parsed.path).rstrip('/')
return filesystem, path

Expand Down
Loading
Loading