Skip to main content

sasvi.auth

Token providers and the HTTPX auth adapter for SAS Logon.

Provides the TokenProvider protocol and concrete implementations for each supported OAuth flow (StaticTokenProvider, ClientCredentialsTokenProvider, UsernamePasswordTokenProvider, and AuthorizationCodeTokenProvider), plus BearerTokenAuth, which attaches tokens to requests and performs single-shot re-auth on 401. Secret-bearing fields are redacted in repr and dict snapshots so credentials never leak through logs. Misconfiguration raises sasvi.errors.AuthConfigurationError.

ONE_SHOT_BODY_EXTENSION​

Request extension the retrying client sets when the body can be sent only once: an iterator, a generator, or a stream that cannot rewind.

TokenProvider Objects​

class TokenProvider(Protocol)

Provides access tokens for sync and async HTTP flows.

get_token​

def get_token() -> str

Return an access token for synchronous request flows.

get_token_async​

async def get_token_async() -> str

Return an access token for asynchronous request flows.

TokenState Objects​

@dataclass(frozen=True, slots=True)
class TokenState()

What an OAuth provider holds right now, without the token values.

Attributes:

  • expires_at - Absolute UTC time at which the provider stops using its access token, or None when it holds no token. The provider's expiry_skew_seconds is already subtracted.
  • has_refresh_token - Whether the provider holds a refresh token.

expires_at​

has_refresh_token​

StaticTokenProvider Objects​

@dataclass(slots=True)
class StaticTokenProvider()

Token provider that always returns the same bearer token.

Arguments:

  • token - Pre-acquired SAS access token.

token​

get_token​

def get_token() -> str

Return the configured access token for synchronous callers.

get_token_async​

async def get_token_async() -> str

Return the configured access token for asynchronous callers.

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the static token provider.

BearerTokenAuth Objects​

class BearerTokenAuth(httpx2.Auth)

HTTPX auth adapter backed by a token provider.

Arguments:

  • token_provider - Token provider used to resolve access tokens for each request flow.
  • auth_header_name - Header name used to carry the token.
  • prefix - Token prefix, typically "Bearer".

sync_auth_flow​

def sync_auth_flow(
request: httpx2.Request
) -> Generator[httpx2.Request, httpx2.Response, None]

Attach the current bearer token to a synchronous HTTPX request.

On a 401 response the token provider is invalidated and the request is retried once with a fresh token. Without that, a long-lived session could not recover from a stale cached token until it expired.

Note: the retry re-yields the same request object. A body that can be sent only once (an iterator, a generator or a stream that cannot rewind) is not resent: the 401 goes back to the caller and a WARNING is logged. Pass bytes, a path or a seekable file when a mid-upload token expiry must be survivable.

Arguments:

  • request - Outgoing HTTPX request to mutate in-place.

Yields:

The authenticated request (twice on retry).

async_auth_flow​

async def async_auth_flow(
request: httpx2.Request
) -> AsyncGenerator[httpx2.Request, httpx2.Response]

Attach the current bearer token to an asynchronous HTTPX request.

On a 401 response the token provider is invalidated and the request is retried once with a fresh token. The same non-replayable-body caveat as sync_auth_flow applies.

Arguments:

  • request - Outgoing HTTPX request to mutate in-place.

Yields:

The authenticated request (twice on retry).

ClientCredentialsTokenProvider Objects​

@dataclass(slots=True)
class ClientCredentialsTokenProvider()

SAS Logon client-credentials token provider with in-memory refresh.

A refresh is serialised among sync callers and among async callers on one event loop, but the two planes do not share a lock: a thread and a task refreshing at the same instant each send a token request, and the later response wins. No stale token is served.

Arguments:

  • client_id - OAuth client identifier.
  • client_secret - OAuth client secret.
  • base_url - Viya base URL used to derive the SAS Logon token endpoint.
  • token_url - SAS Logon root hint. The part before its /oauth/ segment (or before its last path segment) is the root, and the token request always goes to <root>/oauth/token; a different last segment is not honoured.
  • scopes - Optional OAuth scopes.
  • timeout - HTTP timeout in seconds for token calls.
  • verify_ssl - TLS verification setting forwarded to HTTPX.
  • headers - Extra headers sent with token requests.
  • expiry_skew_seconds - Seconds to subtract from reported expiry before refreshing.
  • sync_httpx_args - Extra keyword arguments for sync HTTPX clients.
  • async_httpx_args - Extra keyword arguments for async HTTPX clients.

client_id​

client_secret​

base_url​

token_url​

scopes​

timeout​

verify_ssl​

headers​

expiry_skew_seconds​

sync_httpx_args​

async_httpx_args​

token_state​

def token_state() -> TokenState

Report the held token's absolute expiry and whether a refresh token is held.

Makes no request and returns no token value.

Returns:

The current TokenState.

invalidate​

def invalidate() -> None

Discard any cached token so the next call forces a refresh.

invalidate_rejected​

def invalidate_rejected(token: str) -> None

Discard the cached token only if it is the one the server rejected.

A 401 that answered an older token leaves a newer cached token in place. The comparison takes no lock. A refresh that lands between the comparison and the discard costs one extra token request.

Arguments:

  • token - The access token a 401 response answered.

close​

def close() -> None

Close the synchronous SAS Logon HTTP client this provider built.

Closing is idempotent and does nothing before the first token request. An SVIClient closes a provider it built from the environment or copied while binding it. A provider you construct and pass in unchanged stays yours to close.

close_async​

async def close_async() -> None

Close the sync and async SAS Logon HTTP clients this provider built.

Closing is idempotent and does nothing before the first token request.

get_token​

def get_token() -> str

Return a cached access token or fetch a fresh one synchronously.

Raises:

  • AuthConfigurationError - When the token endpoint rejects the client credentials or returns a non-2xx response.
  • AuthServiceUnavailableError - When the token endpoint still answers 408, 429 or 5xx after two retries.

get_token_async​

async def get_token_async() -> str

Return a cached access token or fetch a fresh one asynchronously.

Raises:

  • AuthConfigurationError - When the token endpoint rejects the client credentials or returns a non-2xx response.
  • AuthServiceUnavailableError - When the token endpoint still answers 408, 429 or 5xx after two retries.

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the client-credentials provider.

UsernamePasswordTokenProvider Objects​

@dataclass(slots=True)
class UsernamePasswordTokenProvider()

SAS Logon password-grant token provider.

The async twin runs the sync flow in a worker thread under the loop's own lock; a thread and a task refreshing at the same instant each send a token request, and the later response wins.

This flow is convenient for controlled smoke tests, but SAS does not recommend the password grant outside dev/test contexts.

Arguments:

  • username - SAS username.
  • password - SAS password.
  • client_id - OAuth client identifier.
  • client_secret - Optional OAuth client secret.
  • base_url - Viya base URL used to derive the SAS Logon token endpoint.
  • token_url - SAS Logon root hint. The part before its /oauth/ segment (or before its last path segment) is the root, and the token request always goes to <root>/oauth/token; a different last segment is not honoured.
  • scopes - Optional OAuth scopes.
  • timeout - HTTP timeout in seconds for token calls.
  • verify_ssl - TLS verification setting forwarded to HTTPX.
  • headers - Extra headers sent with token requests.
  • expiry_skew_seconds - Seconds to subtract from reported expiry before refreshing.
  • sync_httpx_args - Extra keyword arguments for sync HTTPX clients.
  • async_httpx_args - Extra keyword arguments for async HTTPX clients.

username​

password​

client_id​

client_secret​

base_url​

token_url​

scopes​

timeout​

verify_ssl​

headers​

expiry_skew_seconds​

sync_httpx_args​

async_httpx_args​

token_state​

def token_state() -> TokenState

Report the held token's absolute expiry and whether a refresh token is held.

Makes no request and returns no token value.

Returns:

The current TokenState.

invalidate​

def invalidate() -> None

Discard cached access and refresh tokens.

invalidate_rejected​

def invalidate_rejected(token: str) -> None

Discard the cached access token only if it is the one the server rejected.

A 401 that answered an older token leaves a newer cached token in place. The comparison takes no lock. A refresh that lands between the comparison and the discard costs one extra token request. The refresh token is kept, so the next request tries the refresh grant before a full login.

Arguments:

  • token - The access token a 401 response answered.

close​

def close() -> None

Close the synchronous SAS Logon HTTP client this provider built.

Closing is idempotent and does nothing before the first token request. An SVIClient closes a provider it built from the environment or copied while binding it. A provider you construct and pass in unchanged stays yours to close.

close_async​

async def close_async() -> None

Close the sync and async SAS Logon HTTP clients this provider built.

Closing is idempotent and does nothing before the first token request.

get_token​

def get_token() -> str

Return a cached access token or obtain one with the password grant.

Raises:

  • AuthConfigurationError - When the token endpoint rejects the credentials or returns a non-2xx response.
  • AuthServiceUnavailableError - When the token endpoint still answers 408, 429 or 5xx after two retries. It is an AuthConfigurationError; catch it first to tell an outage from bad credentials.

get_token_async​

async def get_token_async() -> str

Return a token asynchronously using the same refresh rules as get_token().

Raises:

  • AuthConfigurationError - When the token endpoint rejects the credentials or returns a non-2xx response.
  • AuthServiceUnavailableError - When the token endpoint still answers 408, 429 or 5xx after two retries. It is an AuthConfigurationError; catch it first to tell an outage from bad credentials.

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the password-grant provider.

AuthorizationCodeTokenProvider Objects​

@dataclass(slots=True)
class AuthorizationCodeTokenProvider()

Interactive SAS Logon authorization-code token provider with PKCE.

The async twin runs the sync flow in a worker thread under the loop's own lock; a thread and a task refreshing at the same instant each send a token request, and the later response wins.

Arguments:

  • client_id - OAuth client identifier.
  • client_secret - Optional OAuth client secret.
  • base_url - Viya base URL used to derive SAS Logon authorize and token endpoints.
  • authorize_url - SAS Logon root hint for the authorize URL, read the same way as token_url; the browser is sent to <root>/oauth/authorize.
  • token_url - SAS Logon root hint. The part before its /oauth/ segment (or before its last path segment) is the root, and the token request always goes to <root>/oauth/token; a different last segment is not honoured.
  • redirect_uri - OAuth redirect URI.
  • scopes - Optional OAuth scopes.
  • timeout - HTTP timeout in seconds for token calls.
  • verify_ssl - TLS verification setting forwarded to HTTPX.
  • headers - Extra headers sent with token requests.
  • expiry_skew_seconds - Seconds to subtract from reported expiry before refreshing.
  • open_browser - Whether to open the authorization URL automatically.
  • prompt_for_code - Callback used to collect the returned authorization code.
  • browser_opener - Callback used when open_browser=True.
  • sync_httpx_args - Extra keyword arguments for sync HTTPX clients.
  • async_httpx_args - Extra keyword arguments for async HTTPX clients.

client_id​

client_secret​

base_url​

authorize_url​

token_url​

redirect_uri​

scopes​

timeout​

verify_ssl​

headers​

expiry_skew_seconds​

open_browser​

prompt_for_code​

browser_opener​

sync_httpx_args​

async_httpx_args​

token_state​

def token_state() -> TokenState

Report the held token's absolute expiry and whether a refresh token is held.

Makes no request and returns no token value.

Returns:

The current TokenState.

invalidate​

def invalidate() -> None

Discard cached access and refresh tokens.

invalidate_rejected​

def invalidate_rejected(token: str) -> None

Discard the cached access token only if it is the one the server rejected.

A 401 that answered an older token leaves a newer cached token in place. The comparison takes no lock. A refresh that lands between the comparison and the discard costs one extra token request. The refresh token is kept, so the next request tries the refresh grant before a full login.

Arguments:

  • token - The access token a 401 response answered.

close​

def close() -> None

Close the synchronous SAS Logon HTTP client this provider built.

Closing is idempotent and does nothing before the first token request. An SVIClient closes a provider it built from the environment or copied while binding it. A provider you construct and pass in unchanged stays yours to close.

close_async​

async def close_async() -> None

Close the sync and async SAS Logon HTTP clients this provider built.

Closing is idempotent and does nothing before the first token request.

build_authorization_url​

def build_authorization_url() -> tuple[str, str]

Build an authorization URL and PKCE verifier pair.

Returns:

A tuple of (authorization_url, code_verifier).

Raises:

  • InvalidBaseURLError - When the authorize URL or base URL is unsafe: not https (without the insecure opt-in), or carrying userinfo.
  • AuthInputError - When neither authorize_url nor base_url is set.

authorize​

def authorize(code: str | None = None) -> str

Exchange an authorization code for an access token.

Arguments:

  • code - Optional authorization code. When omitted, prompt_for_code is used.

Returns:

The new access token.

Raises:

  • AuthConfigurationError - When the token endpoint rejects the code exchange or returns a non-2xx response.
  • AuthInputError - When no authorization code could be obtained.
  • InvalidBaseURLError - When the authorize URL is unsafe. Raised before the browser opens or the prompt shows the URL.

get_token​

def get_token() -> str

Return a cached token, refresh one, or start the PKCE flow.

Raises:

  • AuthConfigurationError - When the token endpoint rejects the refresh or code exchange, or returns a non-2xx response.
  • AuthServiceUnavailableError - When the token endpoint still answers 408, 429 or 5xx while refreshing. It is an AuthConfigurationError; the refresh token is kept.
  • AuthInputError - When the interactive flow obtains no authorization code.
  • InvalidBaseURLError - When the authorize URL is unsafe.

get_token_async​

async def get_token_async() -> str

Return a token asynchronously using the same refresh rules as get_token().

Raises:

  • AuthConfigurationError - When the token endpoint rejects the refresh or code exchange, or returns a non-2xx response.
  • AuthServiceUnavailableError - When the token endpoint still answers 408, 429 or 5xx while refreshing. It is an AuthConfigurationError.
  • AuthInputError - When the interactive flow obtains no authorization code.
  • InvalidBaseURLError - When the authorize URL is unsafe.

to_dict​

def to_dict() -> JsonObject

Return a JSON-serializable snapshot of the authorization-code provider.