---------------------------------------------------------------------- This is the API documentation for the dazapiz library. ---------------------------------------------------------------------- ## Refresh tokens and credentials Find the `az login` refresh token, or sign in for one, and redeem it. refresh_token_from_az_cli(*, username: 'str | None' = None, tenant_id: 'str | None' = None, config_dir: 'str | os.PathLike[str] | None' = None) -> 'RefreshTokenInfo' The refresh token of the account the Azure CLI is signed in as. Reads the Azure CLI's files without running `az`, so it also works where only the config directory is present (a mounted `~/.azure`): 1. The config directory is `config_dir`, else `$AZURE_CONFIG_DIR`, else `~/.azure`. 2. `azureProfile.json` gives the current account: the default subscription's user and tenant. `username` and `tenant_id` override them; with both given the profile is not read. 3. `msal_token_cache.json` is loaded into `msal.SerializableTokenCache`, which is only read, never written. The refresh token is the newest one issued to `AZURE_CLI_CLIENT_ID` for that user's `home_account_id`. Refresh tokens carry no tenant, so the tenant comes from the profile. 4. When the username is several cache accounts (the same name in two clouds, or two home accounts), the one in the subscription's cloud (`environmentName`) and signed in to its tenant is taken. Where the profile cannot tell them apart (both overrides given, a custom cloud, a tenant none of them signed in to), the newest token wins. An encrypted cache (`msal_token_cache.bin`, from `az config set core.encrypt_token_cache=true`) is not read. Parameters ---------- username The account to look up, matched case-insensitively; default the default subscription's user. tenant_id The tenant the token is for; default the default subscription's tenant, or, with `username`, that user's default (else first) subscription's tenant. config_dir The Azure CLI's config directory; default `$AZURE_CONFIG_DIR`, else `~/.azure`. `~` is expanded. Returns ------- RefreshTokenInfo The token, `AZURE_CLI_CLIENT_ID`, the tenant and the username. Pass it to `spark_storage_conf(refresh_token=...)` or `RefreshTokenCredential`. Raises ------ RefreshTokenNotFoundError No profile, no default subscription, no cache or no matching token. The message names the file and the username, never a token. UnsupportedPlatformError On Windows, where the Azure CLI signs in through the Windows broker and encrypts its cache. Notes ----- Uses `msal.SerializableTokenCache` to read and search the cache; the lookup (which file, which entry) is what dazapiz adds. Nothing is redeemed here: the token is returned as found, and may have expired if the CLI has not been used for a long time (run `az login` again). Examples -------- ```python from dazapiz import refresh_token_from_az_cli info = refresh_token_from_az_cli() info.username, info.tenant_id ``` RefreshTokenInfo(token: 'str', client_id: 'str', tenant_id: 'str', username: 'str | None' = None) -> None A refresh token with the client ID and tenant it belongs to. What `refresh_token_from_az_cli()` and every credential's `get_refresh_token()` return, and what `spark_storage_conf()` and `RefreshTokenCredential` take. It is itself a `SupportsRefreshToken`. Frozen; `repr()` and `str()` never show `token`. Parameters ---------- token The refresh token. A secret. client_id The client (application) ID the token was issued to, which must redeem it. tenant_id The tenant to redeem it in: a GUID, a domain, `"organizations"` or `"common"`. username The signed-in user, when known. Raises ------ TypeError A field is not a string (`username` may be `None`). ValueError `token`, `client_id` or `tenant_id` is empty. Examples -------- ```python from dazapiz import AZURE_CLI_CLIENT_ID, RefreshTokenInfo info = RefreshTokenInfo(token=token, client_id=AZURE_CLI_CLIENT_ID, tenant_id="contoso.com") info # RefreshTokenInfo(token='', client_id='04b07795-...', ...) ``` SupportsRefreshToken(*args, **kwargs) Anything that can hand over a refresh token with its client ID and tenant. A runtime-checkable protocol with one method, `get_refresh_token()`, returning a `RefreshTokenInfo`. `RefreshTokenInfo` itself, `RefreshTokenCredential`, `DeviceCodeCredential` and `InteractiveBrowserCredential` implement it; `spark_storage_conf()` and `RefreshTokenCredential` accept any of them where a refresh token is expected. `azure-identity` credentials do not: they keep refresh tokens private. Examples -------- ```python from dazapiz import RefreshTokenInfo, SupportsRefreshToken class FromVault: def get_refresh_token(self) -> RefreshTokenInfo: return RefreshTokenInfo(token=read_secret(), client_id=CLIENT, tenant_id=TENANT) isinstance(FromVault(), SupportsRefreshToken) # True ``` AZURE_CLI_CLIENT_ID str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. RefreshTokenCredential(refresh_token: 'str | SupportsRefreshToken | None' = None, *, authority_host: 'str | None' = None) -> 'None' A `TokenCredential` that redeems a refresh token for access tokens. Use it wherever the Azure SDK, `ApiClient` or `dazapiz.duckdb.set_credential_secret()` takes a credential, to act as the user an `az login` (or any other sign-in) refresh token belongs to. Access tokens are kept in memory, per tenant and scope set, until five minutes before they expire. When Entra rotates the refresh token, the new one is kept and returned by `get_refresh_token()`. Thread-safe. Parameters ---------- refresh_token A refresh token string, a `SupportsRefreshToken` (such as `refresh_token_from_az_cli()`), or `None` for `$AZURE_REFRESH_TOKEN`. A string is redeemed with `$AZURE_CLIENT_ID`, else `AZURE_CLI_CLIENT_ID`, in `$AZURE_TENANT_ID`, else `"common"`; a `SupportsRefreshToken` brings its own client ID and tenant. authority_host The Entra authority host, with or without `https://`; default `$AZURE_AUTHORITY_HOST`, else the public cloud (`login.microsoftonline.com`). Raises ------ RefreshTokenNotFoundError `refresh_token` is `None` and `$AZURE_REFRESH_TOKEN` is unset. TypeError `refresh_token` is of another type. ValueError `refresh_token` is an empty string. Notes ----- Wraps `msal.PublicClientApplication.acquire_token_by_refresh_token()`, one MSAL app per tenant. `azure-identity` has no credential that takes a refresh token. `repr()` shows the client ID, tenant and username, never a token. Examples -------- ```python from azure.storage.filedatalake import DataLakeServiceClient from dazapiz import RefreshTokenCredential, refresh_token_from_az_cli credential = RefreshTokenCredential(refresh_token_from_az_cli()) lake = DataLakeServiceClient("https://myaccount.dfs.core.windows.net", credential) ``` DeviceCodeCredential(*args: 'Any', allow_unencrypted_storage: 'bool' = False, **kwargs: 'Any') -> 'None' `azure.identity.DeviceCodeCredential` with a persisted cache and `get_refresh_token()`. Signs in with a device code: it prints a URL and a code, and the user signs in from any browser, on any machine. Use it where no browser can reach the machine running Python. As a `SupportsRefreshToken`, it can be passed to `spark_storage_conf(refresh_token=...)`. Parameters ---------- *args Passed to `azure.identity.DeviceCodeCredential` (`client_id`, which defaults to the Azure CLI's). allow_unencrypted_storage Fall back to a plain file where the platform's secret store is unusable (a headless Linux machine). Pass it inside your own `cache_persistence_options` instead when you give those. **kwargs Passed to `azure.identity.DeviceCodeCredential`: `tenant_id`, `authority`, `timeout`, `prompt_callback`, `authentication_record` and the rest. Raises ------ ValueError `allow_unencrypted_storage=True` together with `cache_persistence_options`. Notes ----- Everything but the cache default and `get_refresh_token()` is `azure-identity`'s. Tokens are cached in the platform store under the name `"dazapiz"` unless `cache_persistence_options` is given, so a later session with the same `authentication_record` signs in silently. Examples -------- ```python from dazapiz import DeviceCodeCredential, spark_storage_conf credential = DeviceCodeCredential(tenant_id="contoso.com") conf = spark_storage_conf(refresh_token=credential) # prompts once ``` InteractiveBrowserCredential(*, allow_unencrypted_storage: 'bool' = False, **kwargs: 'Any') -> 'None' `azure.identity.InteractiveBrowserCredential` with a persisted cache and `get_refresh_token()`. It also signs in through a callback page, as httr2 does. With no `redirect_uri` or a localhost one, the parent's local listener and system browser sign in. Any other `redirect_uri` (a page the user's browser can load, such as a code-server URL) prints MSAL's authorize URL and reads back what the callback page shows: the callback URL, base64 JSON with `code` and `state`, or the code and then the state, as `httr2::req_oauth_auth_code()` does. That needs an interactive session. Caching is as `DeviceCodeCredential`. Parameters ---------- allow_unencrypted_storage Fall back to a plain file where the platform's secret store is unusable, as for `DeviceCodeCredential`. **kwargs Passed to `azure.identity.InteractiveBrowserCredential`: `tenant_id`, `client_id`, `redirect_uri`, `login_hint`, `authority`, `authentication_record` and the rest. A `redirect_uri` whose host is not `localhost` or `127.0.0.1` is kept by dazapiz for the pasted-code flow and not passed on. Raises ------ ValueError `allow_unencrypted_storage=True` together with `cache_persistence_options`, or (from the parent) a localhost `redirect_uri` without a port. Notes ----- Everything but the cache default, `get_refresh_token()` and the pasted-code flow is `azure-identity`'s. The pasted-code flow uses the parent's MSAL app: `initiate_auth_code_flow()` builds the PKCE pair, state and nonce, and `acquire_token_by_auth_code_flow()` checks the state and redeems the code, so the tokens land in the same cache. Signing in raises `azure.identity.CredentialUnavailableError` in a session that is not interactive (no TTY, no notebook kernel), and `azure.core.exceptions.ClientAuthenticationError` for a pasted reply with an error, no code, no state, or a state that does not match. The app registration must list the redirect URI as a public client ("Mobile and desktop applications"), since no client secret is sent. Examples -------- ```python from dazapiz import InteractiveBrowserCredential credential = InteractiveBrowserCredential( tenant_id="11111111-2222-3333-4444-555555555555", client_id="aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", redirect_uri="https://your-domain.example/azure-callback", ) token = credential.get_token("User.Read").token # prompts once, then silent ``` ## Spark Hadoop ABFS configuration for PySpark. spark_storage_conf(auth_type: 'AuthType' = 'refresh_token', *, storage_account: 'str | None' = None, tenant_id: 'str | None' = None, client_id: 'str | None' = None, client_secret: 'str | None' = None, refresh_token: 'str | SupportsRefreshToken | None' = None, account_key: 'str | None' = None, token_file: 'str | None' = None, authority_host: 'str | None' = None, prefix: 'str | None' = 'spark.hadoop') -> 'SparkStorageConf' Build the Hadoop `fs.azure.*` keys that let Spark read ADLS Gen2. A port of `azr::azure_spark_storage_conf()`: with arguments passed explicitly the keys and values are azr's, key for key. With the default `prefix="spark.hadoop"` the result goes to `SparkSession.builder.config(map=...)` or a cluster's Spark config; `prefix=None` gives the raw `fs.azure.*` keys for `core-site.xml` or `hadoopConfiguration().set()`. Arguments another `auth_type` uses are ignored, as in azr. An empty environment variable counts as unset. Parameters ---------- auth_type How Hadoop authenticates: - `"refresh_token"`: a delegated user (`RefreshTokenBasedTokenProvider`). Uses `refresh_token`; `client_id` and `tenant_id`, when passed, win over the token's own. - `"client_secret"`: a service principal (`ClientCredsTokenProvider`). `client_id`, `tenant_id` and `client_secret` default to `$AZURE_CLIENT_ID`, `$AZURE_TENANT_ID` and `$AZURE_CLIENT_SECRET`. - `"workload_identity"`: Kubernetes workload identity (`WorkloadIdentityTokenProvider`), with `client_id`, `tenant_id` and `token_file` from `$AZURE_CLIENT_ID`, `$AZURE_TENANT_ID` and `$AZURE_FEDERATED_TOKEN_FILE`, which the AKS webhook sets. Needs Hadoop 3.4.1+ (Spark 4.x, Databricks 14.3+ LTS, Synapse 3.4+). - `"managed_identity"`: IMDS (`MsiTokenProvider`). `client_id` (else `$AZURE_CLIENT_ID`) selects a user-assigned identity; without one the key is left out and Hadoop uses the system-assigned identity. `tenant_id` defaults to `$AZURE_TENANT_ID`, else `"common"`. - `"shared_key"`: the storage account key; needs `storage_account` and `account_key`. storage_account Scope every key to this account's DFS host. A short name is expanded with the DFS suffix of the cloud `authority_host` names (public, US Government or China); a name with a dot is used as is. Default: keys for every account. tenant_id The tenant (GUID or domain) whose token endpoint Hadoop calls. client_id The client (application) ID: the token's client for `"refresh_token"`, the service principal or identity otherwise. client_secret The service principal's secret, for `"client_secret"`. refresh_token For `"refresh_token"`: a string, a `SupportsRefreshToken` such as `refresh_token_from_az_cli()`, or `None` for `$AZURE_REFRESH_TOKEN`. A `SupportsRefreshToken` supplies its own client ID and tenant; a string takes `$AZURE_CLIENT_ID`, else `AZURE_CLI_CLIENT_ID`, and `$AZURE_TENANT_ID`, else `"common"`. account_key The storage account key, for `"shared_key"`. token_file The federated token file, for `"workload_identity"`. authority_host The Entra authority host; default `$AZURE_AUTHORITY_HOST`, else `login.microsoftonline.com`. May carry a scheme and trailing slash. prefix Prepended to every key with a dot; `None` for the raw Hadoop keys. Returns ------- SparkStorageConf A `dict[str, str]` whose `repr` and `str` redact the secrets. Raises ------ ValueError An unknown `auth_type`, an empty argument, a tenant ID that is not valid, or a value `auth_type` needs that is neither passed nor in its environment variable. TypeError An argument is not a string. RefreshTokenNotFoundError `auth_type="refresh_token"` with no `refresh_token` and no `$AZURE_REFRESH_TOKEN`. Notes ----- Neither PySpark nor the Azure SDK builds these keys; Hadoop's ABFS driver redeems the token itself. Two details carried over from azr: `RefreshTokenBasedTokenProvider` reads `oauth2.refresh.token.endpoint`, not `oauth2.client.endpoint`, and the MSI authority needs its trailing `/`. Examples -------- ```python from pyspark.sql import SparkSession from dazapiz import refresh_token_from_az_cli, spark_storage_conf conf = spark_storage_conf(refresh_token=refresh_token_from_az_cli()) spark = SparkSession.builder.config(map=conf).getOrCreate() spark.read.parquet("abfss://data@myaccount.dfs.core.windows.net/sales/") ``` A service principal, for one account only: ```python conf = spark_storage_conf("client_secret", storage_account="myaccount") ``` SparkStorageConf The `fs.azure.*` keys of `spark_storage_conf()`, as a plain `dict[str, str]`. The dict holds the real values, to pass to `SparkSession.builder.config(map=conf)` or `spark.conf.set()`; `repr()` and `str()` show `` for the client secret, refresh token and account key, so printing one in a notebook does not leak them. `copy()` and `|` keep the type, and so the redaction. Examples -------- ```python conf = spark_storage_conf(refresh_token=refresh_token_from_az_cli()) conf # SparkStorageConf({..., 'spark.hadoop.fs.azure.account.oauth2.refresh.token': '', ...}) for key, value in conf.items(): spark.conf.set(key, value) ``` ## REST client A small httpx client for one Azure-protected REST API, and its credentials. ApiClient(host_url: 'str | None' = None, credential: 'TokenCredential | None' = None, scope: 'str | None' = None, *, timeout: 'float' = 60, connect_timeout: 'float' = 30, max_tries: 'int' = 5, verbose: 'bool' = False, response_handler: 'Callable[[Any], Any] | None' = None, transport: 'httpx.BaseTransport | None' = None, sleep: 'Callable[[float], None] | None' = None) -> 'None' A client for one REST API, meant to be subclassed once per API. The class attributes say where the API is and where its credentials come from; `__init__` arguments override them per instance. The credential is the `credential` argument, else `app_credential()` with the class's variable names and `mode` when `client_id_env` and `client_secret_env` are set, else none (requests go unauthenticated). Wraps one `httpx.Client`; also a context manager, typed as the subclass. Parameters ---------- host_url The API's base URL; default the class's `host_url`. credential Any `TokenCredential`, such as `DefaultAzureCredential()` or `RefreshTokenCredential`; default chosen as above. scope The token scope; default the class's `scope`, else `f"{host_url}/.default"`. timeout Seconds for the whole request. connect_timeout Seconds to connect. max_tries Attempts per request, the first included, for 429, 503 and connection failures. verbose Log each request and response on the `dazapiz.http` logger at `INFO`, in azr's coloured format through `rich`: method and URL, status, time and size, and the JSON request body and failed response body, abbreviated. Headers are never logged. response_handler Called with every non-empty parsed body; `fetch()` returns what it returns. `fetch(parse=...)` replaces it for one call. transport The `httpx` transport requests go through; default httpx's own. For tests: an `httpx.MockTransport` answers requests without a server. sleep Called with each retry wait, in seconds; default `time.sleep`. For tests: `sleep=waits.append` records the waits and does not wait. Attributes ---------- host_url : str or None Class attribute: the API's base URL. scope : str or None Class attribute: the token scope. client_id_env : str or None Class attribute: the variable holding the API's service principal client ID, for `app_credential()`. client_secret_env : str or None Class attribute: the variable holding its client secret. tenant_id_env : str Class attribute: the variable holding its tenant; `"AZURE_TENANT_ID"`. mode : str or None Class attribute: `app_credential()`'s mode. credential : TokenCredential or None The credential the client uses, read-only (see `credential`). Raises ------ ValueError No `host_url`, or `max_tries` below 1; and what `app_credential()` raises. Notes ----- Tokens come from `credential.get_token(scope)` through an `httpx.Auth` that keeps each token until five minutes before it expires. A 401 is not replayed (`get_token()` cannot be forced to refresh); the token is dropped, so the next request asks the credential again. A port of `azr::api_client` without its service and resource layers. Examples -------- ```python from dazapiz import ApiClient class AppApiClient(ApiClient): host_url = "https://app-api.example.com" scope = "api://00000000-0000-0000-0000-000000000000/.default" client_id_env = "APP_API_CLIENT_ID" client_secret_env = "APP_API_SECRET" def get_item(self, item_id: str) -> dict: return self.fetch("/items/{item_id}", item_id=item_id) with AppApiClient() as client: item = client.get_item("42") ``` app_credential(client_id_env: 'str', client_secret_env: 'str', *, tenant_id_env: 'str' = 'AZURE_TENANT_ID', mode: 'str | None' = None) -> 'TokenCredential' The credential an API's client uses, chosen from the environment now. `client_id_env`, `client_secret_env` and `tenant_id_env` name the variables that hold this API's service principal, so it can live in variables of its own (`APP_API_CLIENT_ID`, ...) rather than the machine's `AZURE_CLIENT_ID`. The mode is `mode`, else `$AZURE_TOKEN_CREDENTIALS`, else automatic, matched case-insensitively: | Mode | Credential | | --- | --- | | `"prod"` | `ClientSecretCredential` from the named variables when they are set, else `WorkloadIdentityCredential()` when `$AZURE_FEDERATED_TOKEN_FILE` is set, else `ManagedIdentityCredential()` (user-assigned with `client_id=$AZURE_CLIENT_ID` when that is set) | | `"dev"` | `ChainedTokenCredential(AzureCliCredential(), azure.identity.DeviceCodeCredential())`, the device code only in an interactive session (a TTY or a notebook kernel), with no persisted token cache, so it also prompts where no secret store is usable | | `"client_secret"`, `"workload_identity"`, `"managed_identity"`, `"azure_cli"`, `"device_code"` (or the azure-identity class name) | that credential alone | | automatic | the named service principal when its client ID and secret variables are set, otherwise `"dev"` | Parameters ---------- client_id_env The variable holding the service principal's client ID. client_secret_env The variable holding its client secret. tenant_id_env The variable holding its tenant ID. mode One of the modes above; default `$AZURE_TOKEN_CREDENTIALS`, else automatic. A value of `$AZURE_TOKEN_CREDENTIALS` that `DefaultAzureCredential` takes but dazapiz does not build (`AzureDeveloperCliCredential`, `AzurePowerShellCredential`, `VisualStudioCodeCredential`, `InteractiveBrowserCredential`) means automatic, with a warning. Returns ------- azure.core.credentials.TokenCredential An azure-identity credential, unchanged; no token is fetched here. Raises ------ ValueError An unknown mode; a client ID without its secret, or the reverse (naming the missing variable); a service principal with no tenant; or `"client_secret"` with neither variable set. Notes ----- Every credential is an `azure-identity` class, built and returned as is; the choice is what dazapiz adds. Variables are read once, now; an empty variable counts as unset. The mode and credential class chosen (never a value) are logged on the `dazapiz.http` logger at `INFO`. Examples -------- ```python from dazapiz import app_credential credential = app_credential("APP_API_CLIENT_ID", "APP_API_SECRET") token = credential.get_token("api://my-api/.default") ``` ## az CLI Log the Azure CLI in and out, and read its current account. az_login(tenant_id: 'str | None' = None, *, force: 'bool' = False, timeout: 'float | None' = None) -> 'dict[str, Any]' Log the Azure CLI in with a device code, unless it already is. Unless `force`, returns the current account without prompting when the CLI is logged in (into `tenant_id`, if given). Otherwise runs `az login --use-device-code [--tenant ] --output json`, prints the device code and URL as soon as `az` streams them on stderr, copies the code to the clipboard when a clipboard tool is found, waits for `az` to finish and returns the account it made the default. Prints the device code and the account name, nothing else from the login. Parameters ---------- tenant_id Log in to this tenant (GUID or domain); an account logged in to another tenant counts as not logged in. A domain matches the account's `tenantDefaultDomain`. force Log in again even when the CLI already is. timeout Seconds to wait for the whole login, the `az account show` checks included; `None`, the default, waits. Returns ------- dict The account `az` made the default, as `az_account_show()` returns it. Raises ------ AzCliNonInteractiveError Nobody can answer the prompt: no TTY and no notebook kernel. AzCliTimeoutError `timeout` seconds passed first; `az` is killed. AzCliNotFoundError There is no `az` on PATH. AzCliError `az login` failed. TypeError `tenant_id` is not a string. ValueError `tenant_id` is not a valid tenant ID. Notes ----- Runs `az login` (`azr::az_cli_login()`); the sign-in itself is the Azure CLI's. Afterwards `refresh_token_from_az_cli()` finds the new refresh token. Examples -------- ```python from dazapiz import az_login az_login() # To sign in, open https://microsoft.com/devicelogin and enter the code ... ``` az_logout(timeout: 'float | None' = 10) -> 'None' Log the Azure CLI out, by `az logout`. Parameters ---------- timeout Seconds to wait for `az`; `None` waits as long as it takes. Raises ------ AzCliNotLoggedInError No account is logged in. AzCliNotFoundError There is no `az` on PATH. AzCliTimeoutError `az` did not finish within `timeout` seconds. AzCliError Any other failure. Notes ----- Runs `az logout` (ported from `azr`'s `az_cli_*()` helpers), which removes the signed-in account and its tokens from the CLI's cache. Examples -------- ```python from dazapiz import az_logout az_logout() # Logged out of the Azure CLI. ``` az_is_login(timeout: 'float | None' = 10) -> 'bool' Whether the Azure CLI is logged in, by `az account show`. Parameters ---------- timeout Seconds to wait for `az`; `None` waits as long as it takes. Returns ------- bool `True` when `az account show` succeeds; `False` on any `AzCliError`, including no `az` on PATH and a timeout, as `azr::az_cli_is_login()` returns `FALSE` on any error. Notes ----- Runs `az account show` through `az_account_show()`, as `azr::az_cli_is_login()` does. Examples -------- ```python from dazapiz import az_is_login, az_login if not az_is_login(): az_login() ``` az_account_show(timeout: 'float | None' = 10) -> 'dict[str, Any]' The Azure CLI's current account, from `az account show --output json`. Parameters ---------- timeout Seconds to wait for `az`; `None` waits as long as it takes. Returns ------- dict The account as `az` prints it: `id` (the subscription), `name`, `tenantId`, `user` (with `name` and `type`) and the rest. Raises ------ AzCliNotLoggedInError The CLI is not logged in. AzCliNotFoundError There is no `az` on PATH. AzCliTimeoutError `az` did not finish within `timeout` seconds. AzCliError Any other failure, with what `az` wrote to stderr. Notes ----- Runs the `az` that `shutil.which("az")` finds, as a plain subprocess (ported from `azr`'s `az_cli_*()` helpers). For tokens from the CLI, use `azure.identity.AzureCliCredential`, which dazapiz does not wrap. Examples -------- ```python from dazapiz import az_account_show account = az_account_show() account["user"]["name"], account["tenantId"] ``` ## DuckDB Azure secrets and settings for DuckDB, in `dazapiz.duckdb` (needs `dazapiz[duckdb]`). ## Testing Test doubles for code built on dazapiz, in `dazapiz.testing`. ## Errors Everything dazapiz raises derives from `DazapizError`. DazapizError Base class of every error dazapiz raises. Catch it to handle any dazapiz failure. Errors from the Azure SDK itself, such as `azure.core.exceptions.ClientAuthenticationError` from a credential, are not wrapped and do not derive from it. Examples -------- ```python from dazapiz import DazapizError, refresh_token_from_az_cli try: info = refresh_token_from_az_cli() except DazapizError as err: print(f"No az login token: {err}") ``` RefreshTokenNotFoundError No refresh token was found where one was looked for. Raised by `refresh_token_from_az_cli()` (no profile, no default subscription, no token cache or no matching token), by the interactive credentials' `get_refresh_token()` (nothing in the persisted cache), and wherever a refresh token defaults to `$AZURE_REFRESH_TOKEN` and that is unset. The message names the file and the username looked for, never a token. UnsupportedPlatformError The operation is not available on this operating system. `refresh_token_from_az_cli()` raises it on Windows, where the Azure CLI keeps its tokens in the Windows broker. AzCliError An `az` command failed; the message carries what `az` wrote to stderr. The base class of the `az` CLI helpers' errors: `az_account_show()`, `az_login()` and `az_logout()` raise it, or one of its subclasses. AzCliNotFoundError No `az` on PATH. The message links the Azure CLI's installation instructions. AzCliNotLoggedInError The Azure CLI is not logged in. Log in with `az_login()`, or `az login` in a terminal. AzCliNonInteractiveError `az_login()` was called where nobody can answer the device-code prompt. A session is interactive when standard input is a TTY or a notebook kernel is running; a batch job, a pipe or a scheduled run is not. AzCliTimeoutError An `az` command did not finish within its timeout and was killed. Also a `TimeoutError`. The whole process tree `az` started is killed. ApiError(message: 'str', *, request: 'Request', response: 'Response') -> 'None' An `ApiClient` request ended in a non-2xx response, after any retries. Also an `httpx.HTTPStatusError`, so code written for `httpx` catches it. The message carries the method, URL, status and response body, never a request header. `request` and `response` are the `httpx` objects. Examples -------- ```python try: client.fetch("/items/{item_id}", item_id="42") except ApiError as err: if err.response.status_code != 404: raise ``` ResponseParseError(message: 'str', *, request: 'httpx.Request', response: 'httpx.Response') -> 'None' A successful response's body could not be parsed or was rejected by `parse=`. `ApiClient.fetch()` raises it when its `parse` callable raises on a 2xx response's body, and when a body whose content type says JSON or XML does not parse. It is not an `ApiError`: the request itself succeeded. The message names the method, the URL and the exception's type, never the body or a header: a validation error can quote the body. The original exception (such as pydantic's `ValidationError`) is `__cause__`. Parameters ---------- message The error message. request The request that was sent. response The successful response whose body failed. Attributes ---------- request : httpx.Request The request that was sent. response : httpx.Response The response whose body failed. ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## Guide ### Get started `dazapiz` carries your `az login` into Spark, DuckDB and any Azure REST API, on top of `azure-identity` and `msal`. This page takes one login all the way to a Spark session that reads Azure Data Lake Storage Gen2. None of the code on these pages runs when the site is built: it needs an Azure account. ## Install ```sh pip install dazapiz # Spark configuration, credentials, REST client, az helpers pip install "dazapiz[duckdb]" # also the DuckDB secrets in dazapiz.duckdb ``` PySpark is never a dependency: `dazapiz` builds a plain `dict` of Spark settings, for whichever Spark you already have. ## Log in once `az_login()` runs `az login --use-device-code` and prints the code to enter at . It does nothing when the Azure CLI is already logged in, so it is safe at the top of a notebook. ```python from dazapiz import az_login az_login() ``` ``` To sign in, open https://microsoft.com/devicelogin and enter the code ABCD1234. Logged in to the Azure CLI as you@example.com. ``` `az_is_login()`, `az_account_show()` and `az_logout()` do the rest of what you would type at a terminal. They need the Azure CLI (`az`) on `PATH`. ## Find the refresh token `refresh_token_from_az_cli()` reads the refresh token the Azure CLI keeps in `~/.azure/msal_token_cache.json`, for the account and tenant of its default subscription, without running `az`: ```python from dazapiz import refresh_token_from_az_cli info = refresh_token_from_az_cli() info ``` ``` RefreshTokenInfo(token='', client_id='04b07795-8ddb-461a-bbee-02f9e1bf7b46', tenant_id='...', username='you@example.com') ``` The token never prints. It belongs to the Azure CLI's own client ID, which `info` carries along, so whatever redeems it uses the right one. On Windows, where the Azure CLI keeps its tokens in the Windows broker, it raises `UnsupportedPlatformError`; sign in with `DeviceCodeCredential` instead (see [Browser-hosted sign-in](browser-sign-in.qmd)). ## Spark `spark_storage_conf()` turns the token into the Hadoop ABFS settings that let Spark read and write ADLS Gen2 as you: ```python from pyspark.sql import SparkSession from dazapiz import refresh_token_from_az_cli, spark_storage_conf conf = spark_storage_conf(refresh_token=refresh_token_from_az_cli()) spark = SparkSession.builder.config(map=conf).getOrCreate() df = spark.read.parquet("abfss://data@myaccount.dfs.core.windows.net/sales/") ``` The keys start with `spark.hadoop.` so that `SparkSession.builder` passes them to Hadoop; `prefix=None` gives the bare `fs.azure.*` keys for `core-site.xml` or `spark.sparkContext._jsc.hadoopConfiguration().set()`. `storage_account="myaccount"` scopes every key to one account. Printing the result shows `` in place of the token. ## Other ways to authenticate `auth_type` picks the Hadoop token provider; values not passed come from the standard `AZURE_*` variables: | `auth_type` | Who | Reads | | --- | --- | --- | | `"refresh_token"` (default) | you, from a sign-in | `refresh_token`, else `$AZURE_REFRESH_TOKEN` | | `"client_secret"` | a service principal | `$AZURE_CLIENT_ID`, `$AZURE_TENANT_ID`, `$AZURE_CLIENT_SECRET` | | `"workload_identity"` | an AKS workload | `$AZURE_CLIENT_ID`, `$AZURE_TENANT_ID`, `$AZURE_FEDERATED_TOKEN_FILE` | | `"managed_identity"` | the VM or cluster's identity | `$AZURE_CLIENT_ID` for a user-assigned one | | `"shared_key"` | the storage account key | `storage_account`, `account_key` | ```python conf = spark_storage_conf("client_secret", storage_account="myaccount") ``` The refresh token can also come from somewhere else: `spark_storage_conf(refresh_token=...)` takes a string, or anything with a `get_refresh_token()` method, such as `DeviceCodeCredential()` or `InteractiveBrowserCredential()`. ## The same login elsewhere - `RefreshTokenCredential(refresh_token_from_az_cli())` is a `TokenCredential`: pass it to any Azure SDK client. - [DuckDB](duckdb.qmd) registers it as an Azure secret. - [REST client](rest-client.qmd) builds a typed client for one API. ### REST client `ApiClient` is a small `httpx` client for one REST API behind Entra ID. You subclass it once per API: the class says where the API is and where its credentials come from, and its methods call `fetch()`. ## A client for one API ```python from dazapiz import ApiClient class AppApiClient(ApiClient): host_url = "https://app-api.example.com" scope = "api://00000000-0000-0000-0000-000000000000/.default" client_id_env = "APP_API_CLIENT_ID" # this API's service principal client_secret_env = "APP_API_SECRET" # tenant_id_env = "APP_API_TENANT" # only if not AZURE_TENANT_ID def get_item(self, item_id: str) -> dict: return self.fetch("/items/{item_id}", item_id=item_id) with AppApiClient() as client: item = client.get_item("42") ``` `fetch(path, method="GET", *, query, json, headers, content_type, parse, **path_params)` fills the `{name}` placeholders from keyword arguments, URL-encoded, sends the request and returns the parsed body: JSON as Python objects, XML as an `ElementTree.Element`, anything else as text, an empty body as `None`. A non-2xx response raises `ApiError`, which is also an `httpx.HTTPStatusError`. `scope` defaults to `f"{host_url}/.default"`, and `__init__` arguments (`host_url`, `credential`, `scope`, timeouts) override the class attributes per instance. ## Where the credential comes from `credential=` wins: any `TokenCredential`, such as `DefaultAzureCredential()` or `RefreshTokenCredential(refresh_token_from_az_cli())`. Otherwise, when the class names `client_id_env` and `client_secret_env`, `app_credential()` chooses one when the client is created, by `mode` (the class attribute), else `$AZURE_TOKEN_CREDENTIALS`, else automatically: | Mode | Credential | | --- | --- | | automatic | the API's service principal when both of its variables are set, else `"dev"` | | `"dev"` | `AzureCliCredential`, then `dazapiz.DeviceCodeCredential` in an interactive session | | `"prod"` | the API's service principal if set, else `WorkloadIdentityCredential` when `$AZURE_FEDERATED_TOKEN_FILE` is set, else `ManagedIdentityCredential` | | `"client_secret"`, `"workload_identity"`, `"managed_identity"`, `"azure_cli"`, `"device_code"` | that credential alone | So a developer with neither variable set gets their own `az login`, and a deployment that sets them gets the service principal. A client ID without its secret, or the reverse, is a `ValueError` naming the missing variable, never a silent fall-back. A class with no credential variables and no `credential=` sends requests unauthenticated. Tokens are kept until five minutes before they expire. A 401 is not retried, since the credential would hand back the same token; the token is dropped so the next request asks for a new one. ## Typed results and model bodies `parse=` validates the body and types the result: ```python from pydantic import TypeAdapter pets = client.fetch("/pets", parse=TypeAdapter(list[Pet]).validate_python) # list[Pet] pet = client.fetch("/pets/{pet_id}", parse=Pet.model_validate, pet_id="7") # Pet ``` `parse` is called with the parsed body of every successful response (`None` for an empty one). If it raises, `fetch()` raises `ResponseParseError`, with the method and URL but not the body (a validation error can quote it), and the original error as `__cause__`. The same error is raised when a body labelled JSON or XML does not parse. `json=` takes a pydantic model (sent as `model_dump(mode="json", by_alias=True, exclude_unset=True)`) or a dataclass, also nested in lists and dicts. `dazapiz` does not depend on pydantic: any object with a `model_dump()` method is treated as a model. ## Logging and retries `verbose=True` logs each call on the `dazapiz.http` logger, in `azr`'s format: ``` ℹ >>> POST https://petstore3.swagger.io/api/v3/pet ℹ >>> body: { "id": 4711, "name": "dazapiz-example", "photoUrls": ["https://example.com/dazapiz.png"], "tags": [ { "id": 1, "name": "dazapiz" } ], "status": "available" } ✔ <<< status = 200 | time = 0.412 secs. | size = 0.13 Kb ``` JSON bodies (the request's, and the response's on failure) are abbreviated: an object or array of more than 10 items keeps the first and last 5, an array of more than 12 numbers or strings the first and last 6, with `...` between. Headers are never logged, so neither is the bearer token; a secret you put in a body is logged as sent. 429, 503 and connection failures are retried, up to `max_tries=5` attempts, waiting for `Retry-After` when the server sends it, else a random 1 to 2.5^attempt seconds (at most 60). A read timeout is not retried: the server may already have acted. ``` ⚠ Request failed. Retrying in 2.1 secs. (attempt 1 of 5). ``` ## Example: the Swagger Petstore `examples/petstore.py` in the repository is a complete, typed client for the public [Swagger Petstore v3](https://petstore3.swagger.io), with pydantic models for every body. It needs no Azure, so you can run it: ```sh uv run python examples/petstore.py ``` The code below is included from that file when the site is built, so it is the code that runs. These are the choices it makes, and why. ### One base, two kinds of model {{< include examples/petstore.py lines="61-81" >}} - **Aliases.** The API is camelCase (`photoUrls`), Python is snake_case (`photo_urls`). `alias_generator=to_camel` maps one to the other, and `validate_by_name` with `validate_by_alias` accept either when validating. `fetch()` sends models `by_alias=True`, so the wire format is the API's. - **Frozen.** A validated object cannot be changed behind the validator's back; `pet.model_copy(update={"status": "sold"})` makes a changed copy (pydantic does not validate `update`, so give it values of the right type). - **Strict requests, tolerant responses.** A request model forbids unknown fields, so a typo (`photoUrl=`) fails in Python, before anything is sent. A response model ignores fields it does not know, so the server adding one does not break the client; a missing required field or a wrong type still fails, as `ResponseParseError`. ### Separate input and output models {{< include examples/petstore.py lines="98-127" >}} What you send and what you get back are different contracts. `PetCreate` checks what the store needs on the way in: a non-empty name and real URLs. `Pet` always has an `id`, since the store assigned one, and types the photo URLs as the schema does, as plain strings. Request models are sent with only the fields you set (`exclude_unset=True`), so an optional field you left out is not sent as `null`. ### Where the live store differs from its schema An example client meets the real server, not only its OpenAPI document. The public store differs in ways the models and methods account for, each noted in the code: - The schema leaves a new pet's `id` optional, but the store answers 500 to a pet without one: pass your own (as `PetCreate`'s docstring says). - The store holds pets whose photo URL is the string `"string"`, so `Pet` checks the schema's contract (`list[str]`), not a stricter one; only `PetCreate` checks for URLs. - It answers XML unless asked for JSON, so every call sends `Accept: application/json`. - Its `status` query takes one value, so `find_pets_by_status()` makes one request per status. - Its delete reply is plain text labelled as JSON, which would not parse, so the delete calls read it as text: {{< include examples/petstore.py lines="289-293" >}} ### Build validators once {{< include examples/petstore.py lines="152-157" >}} A `TypeAdapter` compiles its validator when it is created, so the module builds each one once and the methods reuse it: {{< include examples/petstore.py lines="250-263" >}} ### Domain errors A 404 from `get_pet()` means "no such pet", which callers want to catch by name, not by status code. The client turns that one case into its own error, chained to the `ApiError`, and lets every other failure through: {{< include examples/petstore.py lines="160-161" >}} {{< include examples/petstore.py lines="199-223" >}} ### Putting it together {{< include examples/petstore.py lines="355-382" >}} `tests/test_petstore_example.py` checks the models against the store's OpenAPI document and the requests the client sends; a live test against the public store runs by hand. To test a client of your own in CI, without Azure or the network, see [Testing your API client](testing.qmd). ### Testing your API client You have written an `ApiClient` subclass for a REST API hosted in Azure behind Entra ID. Its tests should run in CI on every pull request, and CI has no Azure: no `az login`, no service principal you would want to put in a runner, and an API you do not want a test to change. dazapiz's own CI works the same way ([design decision D23](https://github.com/pedrobtz/py-dazapiz/blob/main/.agents/design.md#10-decisions): Azure is tested by hand, CI only with simple mocks): what needs real Azure is checked by hand, and the automated tests touch neither Azure nor the network. So the tests replace the two things the client talks to: - **the API**, with [respx](https://lundberg.github.io/respx/), which answers `httpx` requests from routes you declare. `ApiClient` is an `httpx` client, so respx mocks it with no change to the client; - **the credential**, with `dazapiz.testing.StaticTokenCredential`, a `TokenCredential` that hands out a fixed token and records the scopes it was asked for. Pass it as `credential=`, which wins over `app_credential()`. Everything else is the real client: its URL templating, request bodies, parsing, validation, errors and retries. ## The example: the Petstore as an Azure-hosted API The public Swagger Petstore needs no token, so the example in `examples/azure_petstore.py` pretends it does. It is the Petstore client of the [REST client](rest-client.qmd) page with an Entra ID scope and its own service-principal variables: {{< include examples/azure_petstore.py lines="24-32" >}} Its tests are in `examples/tests/` and run in dazapiz's CI. They need `pytest`, `respx` and `pytest-socket` in your dev dependencies: ```sh uv add --dev pytest respx pytest-socket ``` ## The fixtures: `conftest.py` Copy this file next to your tests and change the client, the URL and the names: {{< include examples/tests/conftest.py lines="30-53" >}} `api` is a respx router for the API's base URL, so routes are written as paths (`api.get("/pet/7")`). `assert_all_called=False` lets a test declare routes it does not end up calling. `credential` is a fresh `StaticTokenCredential` per test, so `credential.calls` holds only that test's calls. `store` is the client under test, built on both. ## The tests Each test scripts the API's answer, calls a method, and checks what came back and what was sent. A successful call returns a validated model, and the request carried the fake token, asked for with the class's scope: {{< include examples/tests/test_azure_petstore.py lines="27-39" >}} The scope is written out rather than read from the class, so a test fails if the class's scope changes by mistake. A request body is checked as it was sent, from the recorded request: the model's camelCase aliases, and only the fields that were set. {{< include examples/tests/test_azure_petstore.py lines="42-49" >}} Failures are scripted the same way. A body that does not validate is a `ResponseParseError`; a 404 is the client's own domain error, chained to the `ApiError`: {{< include examples/tests/test_azure_petstore.py lines="52-68" >}} `side_effect` with a list answers each call in turn, which scripts a retry. `ApiClient` retries 429, 503 and connection failures, waiting between attempts with `time.sleep`; its `sleep=` argument takes the function to wait with instead, so `sleep=waits.append` makes the test instant and records the waits: {{< include examples/tests/test_azure_petstore.py lines="71-93" >}} ## Which credential the client picks Whether a deployment gets its service principal and a developer their `az login` depends on the environment, and can be tested without signing in: `app_credential()` only builds the azure-identity credential, it fetches no token until a request is made. Set or clear the variables with `monkeypatch`, build the client, and check `client.credential`, the credential it chose, by type: {{< include examples/tests/test_azure_petstore.py lines="99-117" >}} Clear `AZURE_TOKEN_CREDENTIALS` too: a value on the runner would choose the mode instead. These tests run with the network blocked (below), so building `ClientSecretCredential` and the `az login` chain is checked to make no connection. ## Offline by construction Two guards make sure no test reaches the network, even by mistake. - **respx, for `httpx`.** While the `api` router is active, a request no route matches raises an `AssertionError` ("not mocked") instead of going out: respx's `assert_all_mocked=True`, its default, which the fixture keeps. - **pytest-socket, for everything else.** An autouse fixture blocks every socket for each test in the directory: MSAL and azure-identity fetching a token, another HTTP client, even a DNS lookup fail with `SocketBlockedError`. Unix sockets stay allowed, for local tooling. {{< include examples/tests/conftest.py lines="22-27" >}} Being a fixture in `conftest.py`, it covers only the tests in that directory; tests elsewhere that need a local server keep their sockets. (`pytest --disable-socket` does the same for a whole run.) Both guards are themselves tested: {{< include examples/tests/test_azure_petstore.py lines="123-133" >}} pytest-socket also issues a warning when it blocks a socket, which `pytest.warns` expects here; under `filterwarnings = ["error"]` an unexpected block fails the test either way. ## Without respx: `httpx.MockTransport` If you would rather not add a dependency, `httpx.MockTransport` takes a function from request to response. Pass it as the client's `transport=`: ```python import httpx import pytest from dazapiz.testing import StaticTokenCredential @pytest.fixture def store(): def handler(request: httpx.Request) -> httpx.Response: if request.method == "GET" and request.url.path == "/api/v3/pet/7": return httpx.Response(200, json=PET) return httpx.Response(404) transport = httpx.MockTransport(handler) with AzurePetStoreClient(credential=StaticTokenCredential(), transport=transport) as client: yield client ``` respx adds the routing, the call recording and the unmocked-request check, and needs no change to how the client is built. ## What stays manual The fakes stand in for Entra ID and the API, so these tests cannot tell you that the real ones agree. Keep a short live check, run by hand or on a schedule with real credentials, outside the CI suite: - the scope and the app registration: a real token for `scope` is accepted by the API; - the service principal, managed identity or workload identity of each deployment signs in; - the real API still answers in the shape the models expect. dazapiz does the same with an opt-in live test of the Petstore example (`DAZAPIZ_LIVE_HTTP=1`) and a manual checklist for everything that needs Azure. ### DuckDB `dazapiz.duckdb` registers Azure secrets with DuckDB's `azure` extension, so DuckDB can query ADLS Gen2 and Blob Storage as you or as a service principal. It needs the extra: ```sh pip install "dazapiz[duckdb]" ``` `duckdb` is imported only when a helper runs; `import dazapiz` never needs it. Each helper takes a connection and runs `INSTALL azure; LOAD azure` first if the extension is not loaded yet. ## Your `az login` in DuckDB DuckDB's own `credential_chain` cannot use the refresh token your `az login` left behind. `set_credential_secret()` can, through any `TokenCredential`: it asks the credential for a storage token and registers it. ```python import duckdb from dazapiz import RefreshTokenCredential, refresh_token_from_az_cli from dazapiz.duckdb import set_credential_secret conn = duckdb.connect() expires_on = set_credential_secret(conn, RefreshTokenCredential(refresh_token_from_az_cli())) conn.sql("SELECT count(*) FROM 'abfss://data@myaccount.dfs.core.windows.net/sales/*.parquet'") ``` The token expires, typically after an hour, and is not refreshed in the background. The function returns its `expires_on` (seconds since the epoch); call it again before then to replace the secret. Keep the `RefreshTokenCredential` and pass the same one each time: it keeps the access token in memory until five minutes before expiry. Any other credential works the same way, such as `azure.identity.DefaultAzureCredential()`. ## The other secrets | Function | DuckDB provider | Use | | --- | --- | --- | | `set_credential_secret(conn, credential)` | `access_token` | a token from any `TokenCredential` | | `set_token_secret(conn, token)` | `access_token` | an access token you already have | | `set_sp_secret(conn, tenant_id, client_id, client_secret)` | `service_principal` | DuckDB redeems the secret itself | | `set_chain_secret(conn, chain="default")` | `credential_chain` | DuckDB finds a credential itself (`"cli"`, `["managed_identity", "env"]`, ...) | `list_secrets(conn)` shows the registered Azure secrets (DuckDB redacts their values) and `azure_settings(conn)` the Azure settings, both as DuckDB relations: `.fetchall()`, `.df()` or print them. The functions are ports of `quak`'s `az_set_*_secret()`, `az_list_secrets()`, `az_conn_settings()` and `az_tune()`, and run the same SQL. ## One secret per account Without `account`, the secret is named `dazapiz_default` and applies to every Azure URL. With `account`, it is named `dazapiz_` and scoped to that account's hosts, so different accounts can use different credentials: ```python set_credential_secret(conn, mine) # dazapiz_default set_sp_secret(conn, tenant, client_id, secret, account="shared") # dazapiz_shared ``` The scope covers `abfss://` and `abfs://` on `.dfs.core.windows.net` and `az://` and `azure://` on `.blob.core.windows.net`; a name with a dot is taken as the host itself. DuckDB picks the secret whose scope is the longest prefix of the URL. ::: {.callout-warning} ## Delta tables need an unscoped secret Delta tables never match an account-scoped secret. Register an unscoped one (no `account`) for Delta tables; scoped secrets work for Parquet, CSV and JSON. ::: `dazapiz_*` names never collide with `quak`'s `quak_*` secrets in a shared DuckDB file. ## Tuning reads `tune()` sets the Azure transfer settings; arguments left `None` are left alone: ```python from dazapiz.duckdb import tune tune(conn, concurrency=8, chunk_size=1_048_576, buffer_size=8_388_608) ``` | Argument | DuckDB setting | | --- | --- | | `concurrency` | `azure_read_transfer_concurrency` | | `chunk_size` | `azure_read_transfer_chunk_size` (bytes) | | `buffer_size` | `azure_read_buffer_size` (bytes) | | `transport` | `azure_transport_option_type` (`"default"`, `"curl"`) | | `metadata_cache` | `enable_http_metadata_cache` | | `context_cache` | `azure_context_caching` | It warns when the buffer size is not a multiple of the chunk size. ### Browser-hosted sign-in Where the Azure CLI is not an option (Windows, where `az login` keeps its tokens in the Windows broker, or a machine without `az`), sign in with one of `dazapiz`'s two interactive credentials instead. Both are the `azure-identity` classes of the same name, with two additions: their tokens are cached in the platform's secret store under the name `"dazapiz"`, and `get_refresh_token()` hands over the refresh token, so they can feed `spark_storage_conf()` like `refresh_token_from_az_cli()` does. ## Which flow | Where Python runs | Credential | How you sign in | | --- | --- | --- | | anywhere, including a remote or headless machine | `DeviceCodeCredential()` | open a URL on any device, enter a code | | your own machine, with a browser | `InteractiveBrowserCredential()` | the system browser opens; a local listener receives the code | | a browser-hosted IDE (code-server, RStudio Server, a cloud notebook) | `InteractiveBrowserCredential(redirect_uri=...)` | open the printed URL, sign in, paste back what the callback page shows | ```python from dazapiz import DeviceCodeCredential, spark_storage_conf credential = DeviceCodeCredential(tenant_id="contoso.com") conf = spark_storage_conf(refresh_token=credential) # signs in here, once ``` The first `get_refresh_token()` (or `get_token()`) signs in. Later calls in the same session are silent; in a later session, pass the `AuthenticationRecord` that `credential.authenticate()` returned as `authentication_record=` to sign in silently from the cache. On a headless Linux machine without a usable secret store, pass `allow_unencrypted_storage=True` to fall back to a plain file. ## Signing in from a browser-hosted session In code-server or RStudio Server, Python runs on a server and your browser is on your laptop. The usual browser flow starts a listener on `localhost` of the machine running Python, which your browser never reaches, and `azure-identity` refuses a redirect URI that is not on localhost. `dazapiz.InteractiveBrowserCredential` does what `httr2` does in R for such a redirect URI: it prints the sign-in URL, and you paste back what the callback page shows. ```python from dazapiz import InteractiveBrowserCredential credential = InteractiveBrowserCredential( tenant_id="11111111-2222-3333-4444-555555555555", client_id="aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", redirect_uri="https://your-domain.example/azure-callback", ) token = credential.get_token("User.Read").token # prompts once, then silent ``` ``` Open this URL in a browser to sign in: https://login.microsoftonline.com/11111111-.../oauth2/v2.0/authorize?client_id=... Enter authorization code or URL: ``` After you sign in, Entra sends your browser to the redirect URI with `?code=...&state=...`. Paste any of: - the whole callback URL, from the address bar; - base64-encoded JSON with `code` and `state`, as `httr2`'s callback page shows it; - the bare code, and then the state when asked (`Enter state parameter:`). MSAL checks the state and redeems the code with PKCE; a state that does not match, an error in the callback URL, or a reply without a code raises `ClientAuthenticationError`. The prompt needs an interactive session, a terminal or a notebook kernel; elsewhere the credential raises `CredentialUnavailableError` instead of waiting. No browser is opened, since it would open on the server. A redirect URI on `localhost` or `127.0.0.1`, or none, keeps `azure-identity`'s own listener and browser. ## The app registration The flow works with any Entra app registration, redirect URI and callback page; `dazapiz` hard-codes none of them. - **The app.** Its redirect URI must be registered under **Mobile and desktop applications** (a public client), because the code is redeemed without a client secret. A **Web** redirect needs a client secret, and an **SPA** one must be redeemed from the browser, so neither works. - **The redirect URI.** Any URL your browser can load. MSAL never contacts it; it only has to match the registration exactly. The code-server URL itself works, as does a static page on any host. - **The callback page.** It only has to let you copy the code. A page that shows the query string, or `httr2`'s page that shows it as base64 JSON, is convenient; a page that does not exist works too, since you can paste the URL from the address bar. Scopes are the resource's own, such as `"User.Read"` or `"https://storage.azure.com/.default"`. MSAL adds `offline_access`, `openid` and `profile` itself and refuses them if you pass them. Tenant (a GUID, a domain, `organizations` or `common`) and `authority` for sovereign clouds are `azure-identity`'s arguments, unchanged.