# Copyright (c) 2025, qBraid Development Team
# All rights reserved.
"""
Module for making requests to the qBraid API.
"""
import configparser
import ipaddress
import logging
import os
import re
import warnings
from typing import TYPE_CHECKING, Any, Optional, Union
from urllib.parse import urljoin, urlsplit
import requests
from requests.adapters import HTTPAdapter
from urllib3.exceptions import InsecureRequestWarning
from ._compat import __version__
from .config import (
DEFAULT_CONFIG_SECTION,
DEFAULT_ENDPOINT_URL,
endpoint_for_api_key,
environment_api_key,
get_config_option,
load_config,
resolve_api_url,
)
from .config import save_config as save_user_config
from .config import (
update_config_option,
)
from .exceptions import AuthError, ConfigError, RequestsApiError, UserNotFoundError
from .registry import client_registry, discover_services
from .retry import (
IDEMPOTENCY_KEY_HEADER,
STATUS_FORCELIST,
PostForcelistRetry,
retry_non_idempotent,
)
if TYPE_CHECKING:
import qbraid_core
logger = logging.getLogger(__name__)
# Said once per process: sessions are made many times per command.
_IGNORED_ENV_KEY_WARNED = False
def _warned_ignored_env_key() -> None:
global _IGNORED_ENV_KEY_WARNED # pylint: disable=global-statement
_IGNORED_ENV_KEY_WARNED = True
#: Headers that carry qBraid (or other) credentials. They are never sent to an
#: origin other than the one a request was made to.
CREDENTIAL_HEADERS: tuple[str, ...] = ("X-API-Key", "X-Access-Token", "Authorization")
_DEFAULT_PORTS = {"http": 80, "https": 443}
#: ``name/version`` tokens of the clients built on qbraid-core in this process, such as
#: the qBraid SDK and CLI, in registration order. The API reads them from User-Agent to
#: tell where a request came from.
_CLIENT_TOKENS: list[str] = []
# The alphabet qbraid-api parses client versions with; anything else would be dropped there.
_CLIENT_TOKEN_PART = re.compile(r"[A-Za-z0-9_.+-]{1,64}")
def register_client(name: str, version: str) -> None:
"""Name this client in the User-Agent of requests to the qBraid API.
For packages built on qbraid-core, such as ``register_client("qbraid", "0.13.2")``.
The token is added to requests a :class:`QbraidSessionV1` sends to its own API, not to
other hosts such as signed storage URLs or vendor APIs. Sessions created before the call
include it from their next request, and registering a name again replaces its version.
Raises:
ValueError: If ``name`` or ``version`` is not 1-64 characters of letters, digits,
``_``, ``.``, ``+`` or ``-``, the alphabet qbraid-api reads.
"""
for part in (name, version):
if not _CLIENT_TOKEN_PART.fullmatch(part):
raise ValueError(f"Invalid User-Agent product {name!r}/{version!r}")
prefix = f"{name}/"
_CLIENT_TOKENS[:] = [t for t in _CLIENT_TOKENS if not t.startswith(prefix)]
_CLIENT_TOKENS.append(f"{name}/{version}")
def _origin(url: str) -> Optional[tuple[str, str, Optional[int]]]:
"""Return ``(scheme, host, port)`` for ``url``, with the default port filled in.
Returns None when the URL cannot be parsed, which never compares equal to
a real origin, so an unparseable redirect target is treated as foreign.
"""
try:
parts = urlsplit(url)
scheme = parts.scheme.lower()
return scheme, (parts.hostname or "").lower(), parts.port or _DEFAULT_PORTS.get(scheme)
except ValueError:
return None
def _display_config_url(url: str) -> str:
"""Render a configured API url for a message, without userinfo, query or fragment."""
try:
parts = urlsplit(url)
except ValueError:
return "<unparseable URL>"
if not parts.scheme or not parts.netloc:
return url if not any(c in url for c in "@?#") else "<unparseable URL>"
return f"{parts.scheme}://{parts.netloc.rsplit('@', 1)[-1]}{parts.path}"
def _display_origin(url: str) -> str:
"""Render the origin of ``url`` for an error message (no path or query)."""
try:
parts = urlsplit(url)
return f"{parts.scheme}://{parts.netloc.rsplit('@', 1)[-1]}"
except ValueError:
return "<unparseable URL>"
def _is_loopback_host(host: str) -> bool:
"""True for ``localhost``, 127.0.0.0/8 and ``::1``."""
host = host.lower().rstrip(".")
if host == "localhost" or host.endswith(".localhost"):
return True
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return False
_warned_insecure_urls: set[str] = set()
def _secure_base_url(url: Optional[str], warn: bool = True) -> Optional[str]:
"""Upgrade an ``http://`` base URL for a non-loopback host to ``https://``.
The session no longer follows redirects, so an http base URL for the real
API (which 302s to https) would fail every request -- and following that
redirect, as before, meant sending the credential in cleartext first.
Plain http stays allowed for local development on loopback hosts.
"""
if not url:
return url
try:
parts = urlsplit(url)
except ValueError:
return url
if parts.scheme.lower() != "http" or _is_loopback_host(parts.hostname or ""):
return url
netloc = parts.netloc
if parts.port == 80: # the explicit http port would be wrong for https
netloc = netloc.rsplit(":", 1)[0]
secure = parts._replace(scheme="https", netloc=netloc).geturl()
if warn and url not in _warned_insecure_urls:
_warned_insecure_urls.add(url)
logger.warning(
"API URL %s uses plain http; using %s instead so credentials are not sent "
"in cleartext. Update your qbraidrc url or QBRAID_API_URL to https.",
_display_origin(url),
_display_origin(secure),
)
return secure
def _same_api_url(saved: Optional[str], current: Optional[str]) -> bool:
"""True when two API URLs are equal after the http->https upgrade and trailing slashes."""
if not saved or not current:
return False
def normal(url: str) -> str:
url = url.strip().rstrip("/")
return (_secure_base_url(url, warn=False) or url).rstrip("/")
return normal(saved) == normal(current)
def without_credentials(
headers: Optional[dict[str, Any]] = None, session: Optional["Session"] = None
) -> dict[str, Any]:
"""Return per-request headers that remove every credential header.
``requests`` drops a session header whose per-request value is None, so
passing the result as ``headers=`` sends the request without credentials.
It always removes ``X-API-Key``, ``X-Access-Token`` and ``Authorization``;
pass ``session`` to also remove that session's custom ``auth_headers``
names. Use it for absolute URLs the API hands out, such as signed storage
URLs, which carry their own authorization.
Args:
headers (optional, dict): Extra per-request headers to keep.
session (optional, Session): Session whose ``auth_headers`` names are
removed as well.
"""
names = list(CREDENTIAL_HEADERS)
auth_headers = getattr(session, "auth_headers", None)
if isinstance(auth_headers, dict):
names.extend(auth_headers)
stripped: dict[str, Any] = {name: None for name in names}
if headers:
stripped.update(headers)
return stripped
# qbraidrc options whose values are credentials and must never appear in messages.
_SECRET_CONFIG_OPTIONS = frozenset({"api-key", "access-token"})
class RedirectRefusedError(requests.exceptions.RequestException):
"""A redirect the session will not follow, because it could leak credentials or data."""
# Attribute set on a redirect hop that must not be sent (see Session.rebuild_auth).
_REFUSED_HOP = "_qbraid_refused_redirect"
[docs]
class Session(requests.Session):
"""Custom session with handling of request urls and authentication.
This is a child class of :py:class:`requests.Session`. It handles
authentication with custom headers, and retries on specific 5xx errors.
``POST`` and ``PATCH`` are retried on those only when they carry a non-empty
``Idempotency-Key`` header or are sent inside
:py:func:`~qbraid_core.retry.retry_non_idempotent`.
Redirects are not followed unless a caller passes ``allow_redirects=True``.
When a caller does, any hop to another scheme, host or port drops every
credential header, and a hop that would replay a request body (307/308)
to another origin is refused.
"""
[docs]
def __init__( # pylint: disable=too-many-arguments
self,
*args,
base_url: Optional[str] = None,
headers: Optional[dict[str, Any]] = None,
auth_headers: Optional[dict[str, Any]] = None,
**kwargs,
):
"""
Initialize custom session with default base_url and auth_headers.
Args:
base_url (optional, str): Base URL to prepend to all requests.
headers (optional, dict): Dictionary of headers to include in all requests.
auth_headers (optional, dict): Dictionary of authorization headers to include in all
requests. Values will be masked in error messages.
"""
super().__init__(*args, **kwargs)
self.base_url = base_url
self.auth_headers = {}
if auth_headers:
self.auth_headers.update(auth_headers)
if headers:
self.headers.update(headers)
self.headers.update(self.auth_headers)
self.headers["User-Agent"] = self._user_agent()
self._raise_for_status = True
@property
def base_url(self) -> Optional[str]:
"""Return the base URL."""
return self._base_url
@base_url.setter
def base_url(self, value: Optional[str]) -> None:
"""Set the base URL."""
self._base_url = value
def _user_agent(self) -> str:
"""Return the user agent string."""
return f"QbraidCore/{__version__}"
def _add_client_tokens(self, url: str, kwargs: dict[str, Any]) -> None:
"""Hook for :class:`QbraidSessionV1` to name registered clients; a no-op here."""
def add_user_agent(self, user_agent: str) -> None:
"""Updates the User-Agent header with additional information.
Args:
user_agent (str): Additional user agent information to append.
"""
if user_agent not in self.headers["User-Agent"]:
self.headers["User-Agent"] = f"{self.headers['User-Agent']} {user_agent}"
def initialize_retry(
self,
total: int = 3,
connect: int = 1,
backoff_factor: float = 0.5,
status_forcelist: Union[list[int], set[int], tuple[int, ...]] = STATUS_FORCELIST,
**kwargs,
) -> None:
"""Set the session retry policy.
Args:
total (int): Number of total retries for the requests. Default 3.
connect (int): Number of connect retries for the requests. Default 1.
backoff_factor (float): Backoff factor between retry attempts. Default 0.5.
status_forcelist (Union[list[int], set[int], tuple[int, ...]]): List of status
codes to force a retry on.
"""
# Raising an exception on status code is handled by the request method.
raise_on_status = kwargs.pop("raise_on_status", True)
if not isinstance(raise_on_status, bool):
raise ValueError("raise_on_status must be a boolean.")
self._raise_for_status = raise_on_status
retry = PostForcelistRetry(
total=total,
connect=connect,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
raise_on_status=False,
**kwargs,
)
retry_adapter = HTTPAdapter(max_retries=retry)
self.mount("http://", retry_adapter)
self.mount("https://", retry_adapter)
@staticmethod
def _get_error_code_from_json(
error_json: dict[str, Any],
) -> tuple[Optional[str], Optional[dict[str, Any]]]:
"""Extract the machine-readable ``code`` and any structured details.
The API's envelope is ``{success, message, error: {message, code,
...details}}``; ``details`` is whatever else the error object carried
(e.g. ``needed``/``minRequired``/``balance`` for INSUFFICIENT_CREDITS).
"""
if not error_json or not isinstance(error_json, dict):
return None, None
error_data = error_json.get("error")
body = error_data if isinstance(error_data, dict) else error_json
code = body.get("code")
details = {k: v for k, v in body.items() if k not in ("message", "code", "success")}
return (code if isinstance(code, str) else None), (details or None)
@staticmethod
def _get_error_message_from_json(error_json: dict[str, Any]) -> Optional[str]:
"""Extracts the error message from the JSON response."""
if not error_json or not isinstance(error_json, dict):
return None
msg = error_json.get("message")
if not msg:
error_data = error_json.get("error")
if isinstance(error_data, dict):
msg = error_data.get("message")
elif isinstance(error_data, str):
msg = error_data
if not msg:
msg = Session._get_detail_message(error_json.get("detail"))
return msg
@staticmethod
def _get_detail_message(detail: Any) -> Optional[str]:
"""Render a FastAPI-style ``detail`` as one line.
``detail`` is a string for an ``HTTPException`` and a list of
``{loc, msg}`` for a request validation error; each of those becomes
``"a.b: msg"``, with the leading ``body`` dropped from ``loc``.
"""
if isinstance(detail, str):
return detail or None
if not isinstance(detail, list):
return None
parts = []
for item in detail:
if not isinstance(item, dict) or not item.get("msg"):
continue
# A loc that isn't a list is ignored, not iterated: the message still names the
# problem, and this runs inside error handling, so it must not raise.
raw_loc = item.get("loc")
loc = [str(part) for part in raw_loc] if isinstance(raw_loc, (list, tuple)) else []
if loc[:1] == ["body"]:
loc = loc[1:]
parts.append(f"{'.'.join(loc)}: {item['msg']}" if loc else str(item["msg"]))
return "; ".join(parts) or None
@staticmethod
def _mask_sensitive_data(message: str, auth_headers: dict[str, str]) -> str:
"""Replaces sensitive data in the message with a placeholder."""
for _, value in auth_headers.items():
message = message.replace(value, "...")
return message
# requests.Session.get/options inject allow_redirects=True before calling
# request(), which would bypass the no-redirect default; route them straight
# to request() so the default applies unless the caller passes it.
def get( # type: ignore[override]
self, url: str | bytes, params: Any = None, **kwargs: Any
) -> requests.Response:
"""Send a GET request. Redirects are not followed unless ``allow_redirects=True``."""
return self.request("GET", url, params=params, **kwargs)
def options( # type: ignore[override]
self, url: str | bytes, **kwargs: Any
) -> requests.Response:
"""Send an OPTIONS request. Redirects are not followed unless ``allow_redirects=True``."""
return self.request("OPTIONS", url, **kwargs)
def should_strip_auth(self, old_url: str, new_url: str) -> bool:
"""Strip credentials on any redirect that leaves the original origin.
Stricter than :py:meth:`requests.Session.should_strip_auth`, which keeps
``Authorization`` on an http->https upgrade: here any change of scheme,
host or port counts, so an https->http downgrade always strips too.
"""
old_origin = _origin(old_url)
return old_origin is None or old_origin != _origin(new_url)
def rebuild_auth(
self, prepared_request: requests.PreparedRequest, response: requests.Response
) -> None:
"""Remove credential headers before a redirect hop to another origin.
``requests`` only strips ``Authorization``; the qBraid ``X-API-Key`` and
``X-Access-Token`` headers would otherwise follow the redirect. A hop
that still carries a body here is a 307/308 replay; it is marked, and
:py:meth:`send` refuses it. (``requests`` also builds the next hop for
``Response.next`` when it is not following redirects, so this method
must not raise itself.)
"""
super().rebuild_auth(prepared_request, response)
original_url = response.request.url or ""
new_url = prepared_request.url or ""
if not self.should_strip_auth(original_url, new_url):
return
for name in (*CREDENTIAL_HEADERS, *self.auth_headers):
prepared_request.headers.pop(name, None)
if prepared_request.body is not None:
setattr(
prepared_request,
_REFUSED_HOP,
RedirectRefusedError(
f"Refused to replay a request body across an HTTP {response.status_code} "
f"redirect from {_display_origin(original_url)} to "
f"{_display_origin(new_url)}",
response=response,
request=prepared_request,
),
)
def send(self, request: requests.PreparedRequest, **kwargs: Any) -> requests.Response:
"""Send a prepared request, unless it is a redirect hop marked as refused."""
refused = getattr(request, _REFUSED_HOP, None)
if refused is not None:
raise refused
if (request.headers.get(IDEMPOTENCY_KEY_HEADER) or "").strip():
# urllib3 resends the same headers, so a retry reuses the key.
with retry_non_idempotent():
return super().send(request, **kwargs)
return super().send(request, **kwargs)
def request(
self, method: str, url: str | bytes, *args: Any, **kwargs: Any
) -> requests.Response:
"""Construct, prepare, and send a ``Request``.
Override the request method to prepend base_url to the URL and include additional headers.
Args:
method (str): HTTP method (e.g., 'get', 'post').
url (str | bytes): URL for the request. Prepend base_url if url is a relative URL.
**kwargs: Additional arguments for the request. If 'timeout' is not provided,
defaults to 30 seconds. If 'allow_redirects' is not provided, it
defaults to False, and with ``raise_on_status`` a 3xx response
raises :py:class:`RequestsApiError` carrying its status code.
Returns:
Response object.
Raises:
RequestsApiError: If the request failed.
"""
if isinstance(url, bytes):
url = url.decode("utf-8")
# Set default timeout if not provided (30 seconds)
if "timeout" not in kwargs:
kwargs["timeout"] = 30
# Credentials are custom headers that requests would resend to wherever a
# redirect points, so redirects are opt-in (see rebuild_auth).
redirects_explicit = "allow_redirects" in kwargs
kwargs.setdefault("allow_redirects", False)
if self.base_url and not url.startswith(("http://", "https://")):
base_url = self.base_url.rstrip("/") + "/"
url = url.lstrip("/")
url = urljoin(base_url, url)
self._add_client_tokens(url, kwargs)
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", InsecureRequestWarning)
response = super().request(method, url, *args, **kwargs)
if self._raise_for_status:
if not redirects_explicit and 300 <= response.status_code < 400:
self._refuse_redirect(response)
response.raise_for_status()
except requests.RequestException as err:
message = None
code: Optional[str] = None
details: Optional[dict[str, Any]] = None
if isinstance(err, RedirectRefusedError):
message = str(err)
elif err.response is not None:
try:
error_json: dict[str, Any] = err.response.json()
message = self._get_error_message_from_json(error_json)
code, details = self._get_error_code_from_json(error_json)
except ValueError:
message = err.response.text
message = message or str(err)
message = message if message.endswith(".") else message + "."
message = self._mask_sensitive_data(message, self.auth_headers)
status_code = getattr(err.response, "status_code", None)
raise RequestsApiError(
message, status_code=status_code, code=code, details=details
) from err
return response
@staticmethod
def _refuse_redirect(response: requests.Response) -> None:
"""Raise for a 3xx response the session did not follow."""
source = response.url or ""
location = response.headers.get("Location")
target_url = urljoin(source, location) if location else ""
target = f" to {_display_origin(target_url)}" if location else ""
hint = ""
source_origin, target_origin = _origin(source), _origin(target_url)
if (
source_origin
and target_origin
and source_origin[0] == "http"
and target_origin[0] == "https"
and source_origin[1] == target_origin[1]
):
hint = f". The server requires https: use {_display_origin(target_url)} as the API URL"
raise RedirectRefusedError(
f"Refused to follow HTTP {response.status_code} redirect from "
f"{_display_origin(source)}{target}; qBraid sessions do not follow "
f"redirects unless allow_redirects=True is passed{hint}",
response=response,
request=response.request,
)
def _is_outage(err: RequestsApiError) -> bool:
"""Whether a request failed for a reason that says nothing about the credentials:
a rate limit, a server error, or no answer at all (timeout, refused connection)."""
status = err.status_code
if status is not None:
return status == 429 or status >= 500
return isinstance(err.__cause__, (requests.ConnectionError, requests.Timeout))
[docs]
class QbraidSessionV1(Session):
"""Custom session with handling of request urls and authentication.
This is a child class of :py:class:`qbraid_core.sessions.Session`.
It handles qbraid authentication with custom headers. TLS certificates
are verified (the :py:class:`requests.Session` default).
This class uses the v1 API endpoints.
"""
def _add_client_tokens(self, url: str, kwargs: dict[str, Any]) -> None:
"""Name the registered clients in this request's User-Agent, if it goes to this API.
Set per request rather than on the session, so other hosts (signed storage URLs,
redirects) never see the tokens, and a User-Agent the caller passes is kept.
"""
if not _CLIENT_TOKENS or not self.base_url or _origin(url) != _origin(self.base_url):
return
headers = dict(kwargs.get("headers") or {})
if any(key.lower() == "user-agent" for key in headers):
return
tokens = self.headers.get("User-Agent", "").split()
present = {token.split("/", 1)[0] for token in tokens}
tokens += [t for t in _CLIENT_TOKENS if t.split("/", 1)[0] not in present]
headers["User-Agent"] = " ".join(tokens)
kwargs["headers"] = headers
def rebuild_auth(
self, prepared_request: requests.PreparedRequest, response: requests.Response
) -> None:
"""Also drop the client tokens on a redirect hop away from this API's origin."""
super().rebuild_auth(prepared_request, response)
if not self.base_url or _origin(prepared_request.url or "") == _origin(self.base_url):
return
# _add_client_tokens appends to the session's own User-Agent, so a hop that starts
# with it carries our tokens, whatever was registered since. A caller's own
# User-Agent does not, and is left as it is.
own = str(self.headers.get("User-Agent", ""))
if str(prepared_request.headers.get("User-Agent", "")).startswith(own + " "):
prepared_request.headers["User-Agent"] = own
[docs]
def __init__(
self,
api_key: Optional[str] = None,
access_token: Optional[str] = None,
**kwargs,
) -> None:
"""Initialize custom session with default base_url and auth_headers.
Args:
api_key (optional, str): Authenticated qBraid API key.
access_token (optional, str): qBraid access token.
"""
self._api_key: Optional[str] = None
self._access_token: Optional[str] = None
self._base_url_source = "default"
self._api_key_source: Optional[str] = None
self.api_key = api_key
self.access_token = access_token
self.verify = False
if "headers" not in kwargs:
kwargs["headers"] = {}
if "X-Domain" not in kwargs["headers"]:
kwargs["headers"]["X-Domain"] = "qbraid"
if "auth_headers" not in kwargs:
kwargs["auth_headers"] = {}
if self.access_token:
kwargs["auth_headers"]["X-Access-Token"] = self.access_token
elif self.api_key:
kwargs["auth_headers"]["X-API-Key"] = self.api_key
super().__init__(**kwargs)
self.initialize_retry()
@property
def base_url(self) -> Optional[str]:
"""Return the base URL."""
return super().base_url
@base_url.setter
def base_url(self, value: Optional[str]) -> None:
"""Set the qbraid api url; see :func:`qbraid_core.config.resolve_api_url` for the order."""
url, self._base_url_source = resolve_api_url(
value, self.api_key, self.access_token, lambda: self.get_config("url")
)
if self._base_url_source == "API key":
logger.info("Using API host %s from your API key.", url)
# Only the qBraid session upgrades plain http: the qBraid API redirects
# http to https, which this session no longer follows. Other Session
# subclasses keep whatever base URL they are given.
self._base_url = (_secure_base_url(url) or url) + "/"
@property
def api_key(self) -> Optional[str]:
"""Return the api key."""
return self._api_key
@api_key.setter
def api_key(self, value: Optional[str]) -> None:
"""Set the api key; see :func:`qbraid_core.config.environment_api_key` for the order."""
for key, source in (
(value, "argument"),
(environment_api_key(), "QBRAID_API_KEY env var"),
(self.get_config("api-key"), "qbraidrc config"),
(os.getenv("QBRAID_API_KEY"), "QBRAID_API_KEY env var"),
):
if key:
self._api_key, self._api_key_source = key, source
break
else:
self._api_key, self._api_key_source = None, None
exported = os.getenv("QBRAID_API_KEY")
if (
self._api_key_source == "qbraidrc config"
and exported
and exported != self._api_key
and not _IGNORED_ENV_KEY_WARNED
):
_warned_ignored_env_key()
logger.warning(
"QBRAID_API_KEY is set but the API key saved in qbraidrc is used. The "
"exported key is used only together with QBRAID_API_URL."
)
def api_key_source(self) -> Optional[str]:
"""Where :attr:`api_key` came from: ``"argument"``, ``"QBRAID_API_KEY env var"``
or ``"qbraidrc config"`` (None without a key)."""
return self._api_key_source
@property
def access_token(self) -> Optional[str]:
"""Return the access token."""
return self._access_token
@access_token.setter
def access_token(self, value: Optional[str]) -> None:
"""Set the access token.
Order: the argument, the saved qbraidrc token, then ``QBRAID_ACCESS_TOKEN``. When
:func:`qbraid_core.config.environment_api_key` applies, the saved token is skipped:
it was issued for the saved API, not the one ``QBRAID_API_URL`` names.
"""
saved = None if environment_api_key() else self.get_config("access-token")
self._access_token = value or saved or os.getenv("QBRAID_ACCESS_TOKEN")
def get_config(self, config_name: str) -> Optional[str]:
"""Returns the config value of specified config.
Args:
config_name: The name of the config
"""
try:
config = load_config()
except ConfigError:
return None
return get_config_option(config, config_name)
def get_user_auth_metadata(self) -> dict[str, Any]:
"""Get user metadata.
Returns:
Dictionary containing user metadata.
Raises:
UserNotFoundError: If the API rejected the credentials or the endpoint
(401, 403, 404 or another 4xx), or returned no user. For a 401
the error message is a single actionable line pointing at the
fix; upstream CLI handlers should print it without a traceback.
RequestsApiError: If the API rate-limited the check (429), failed with
a 5xx, or never answered (timeout, connection error). None of
these says anything about the credentials, so callers should
retry rather than reconfigure. Any URL hint is in the message.
"""
try:
response = self.get("/users/verify").json()
except RequestsApiError as err:
wrong_host = self._wrong_host_hint()
if _is_outage(err):
message = (
f"{str(err).rstrip()} {wrong_host}"
if wrong_host
else self._auth_error_message(err)
)
if message == str(err):
raise
raise RequestsApiError(
message, status_code=err.status_code, code=err.code, details=err.details
) from err
if wrong_host:
raise UserNotFoundError(f"{str(err).rstrip()} {wrong_host}") from err
if err.status_code == 401:
# Expected condition (stale/missing token) — surface a clean,
# one-line, actionable message rather than the generic
# "invalid credentials" text buried under a request stack.
raise UserNotFoundError(self._unauthorized_message()) from err
raise UserNotFoundError(self._auth_error_message(err)) from err
if not response or not response["success"]:
raise UserNotFoundError("User metadata invalid or not found.")
return response["data"]
def refresh_access_token(self) -> dict[str, Any]:
"""Extend the session's access token by 24 hours.
Calls ``POST /access-tokens/refresh``, which resets the token's expiry
to 24 hours from now. The token string itself is unchanged, so no local
update is needed. Long-running instances call this periodically to stay
authenticated past the 24h TTL.
One access token is shared per user, organization and compute profile,
across every lab running on that profile — it is not minted per
instance. It is revoked only once the last lab using it stops;
otherwise it expires via the TTL.
Only valid when the session authenticates with an access token —
API-key sessions cannot (and do not need to) refresh.
Returns:
Dictionary containing the refreshed token metadata, including the
new ``expiresAt`` ISO timestamp and the token's ``profileSlug``.
Raises:
AuthError: If the session has no access token.
RequestsApiError: If the refresh request fails, e.g. the token
already expired, or was revoked because the last lab using it
stopped.
"""
if not self.access_token:
raise AuthError("Session has no access token to refresh.")
# Refreshing only extends the expiry, so a resend is safe; losing it to
# one 502 would let the token lapse.
with retry_non_idempotent():
response = self.post("/access-tokens/refresh").json()
return response.get("data", {})
def _auth_error_message(self, err: RequestsApiError) -> str:
"""Build an authentication-failure message, hinting at a stale API URL.
A frequent cause of ``/users/verify`` failures is a ``url`` left in the
qbraidrc config (or ``QBRAID_API_URL``) that predates the current API
version, which surfaces as a generic "invalid credentials" error and is
easily mistaken for a bad API key. When the configured base URL differs
from the default endpoint, append an actionable hint to reset it.
Args:
err: The underlying request error raised by ``/users/verify``.
Returns:
The error string, with a URL-reset hint appended when the configured
endpoint is non-default.
"""
message = str(err)
configured_url = (self.base_url or "").rstrip("/")
key_url = None if self.access_token else endpoint_for_api_key(self.api_key)
if key_url == configured_url:
return message
if configured_url and configured_url != DEFAULT_ENDPOINT_URL.rstrip("/"):
message = message.rstrip()
message += (
f" The configured API URL '{configured_url}' may be outdated; the "
f"current default is '{DEFAULT_ENDPOINT_URL}'. Run "
f"`qbraid configure set url {DEFAULT_ENDPOINT_URL}` to reset it."
)
return message
def _unauthorized_message(self) -> str:
"""The one-line message for a 401 from ``/users/verify``, naming the key's source.
Returns:
What was rejected and where, and the fix.
"""
generic = (
"qBraid credentials missing or expired. Run "
"'qbraid configure' to set your API key (or export "
"QBRAID_API_KEY / QBRAID_ACCESS_TOKEN)."
)
# Origin only: QBRAID_API_URL may carry userinfo or a query secret.
url = _display_origin(self.base_url or "")
if (
self.access_token
and environment_api_key()
and self.access_token == os.getenv("QBRAID_ACCESS_TOKEN")
):
# An exported token is sent ahead of any key, the exported one included.
return (
f"QBRAID_ACCESS_TOKEN was rejected by '{url}', which QBRAID_API_URL names. "
"It is sent instead of QBRAID_API_KEY while both are exported: unset "
"QBRAID_ACCESS_TOKEN to use the exported key."
)
if self.access_token or not self.api_key:
return generic
exported = os.getenv("QBRAID_API_KEY")
# A saved key with QBRAID_API_KEY exported means QBRAID_API_URL is unset (with both
# exported, the exported key comes first).
if self._api_key_source == "qbraidrc config" and exported and exported != self.api_key:
return (
f"The API key saved in qbraidrc was rejected by '{url}'. QBRAID_API_KEY is "
"set but not used: the saved key comes first unless QBRAID_API_URL is set "
"too. Run 'qbraid configure set api-key <key>' or export QBRAID_API_URL."
)
if self._base_url_source == "QBRAID_API_URL env var":
if self._api_key_source == "qbraidrc config":
return (
f"The API key saved in qbraidrc was rejected by '{url}', which "
"QBRAID_API_URL names. Export QBRAID_API_KEY with a key for that API "
"(it is used ahead of qbraidrc while QBRAID_API_URL is set), or "
"unset QBRAID_API_URL."
)
if self._api_key_source == "QBRAID_API_KEY env var":
return (
f"QBRAID_API_KEY was rejected by '{url}', which QBRAID_API_URL names. "
"Check that the key was issued for that API, or unset both variables "
"to use your saved configuration."
)
return generic
def _wrong_host_hint(self) -> Optional[str]:
"""Explain a mismatch between the API key's own host and the url in use.
A key that carries its host only loses to a ``base_url`` argument or
``QBRAID_API_URL``, so the hint names that source.
Returns:
The hint, or None when the key carries no host or the urls match.
"""
key_url = None if self.access_token else endpoint_for_api_key(self.api_key)
configured_url = (self.base_url or "").rstrip("/")
if not key_url or key_url == configured_url:
return None
if self._base_url_source == "QBRAID_API_URL env var":
setting, fix = "QBRAID_API_URL", "unset QBRAID_API_URL"
else:
setting, fix = "the base_url argument", "remove the base_url argument"
return (
f"This API key belongs to '{key_url}', but {setting} points the session at "
f"'{configured_url}'. To use the key's API, {fix}."
)
def is_admin(self) -> bool:
"""Check if the current user has admin privileges.
Returns:
True if the user is an admin, False otherwise.
"""
try:
response = self.get("/users/context").json()
except RequestsApiError:
return False
if not response or not response.get("success"):
return False
user = response.get("data", {}).get("user", {})
return user.get("isAdmin") == "admin"
def get_current_user_owner(self) -> Optional[dict[str, str]]:
"""Get current user info for environment ownership.
Tries the API first (full user info), then falls back to
the local qbraidrc config for offline scenarios.
Returns:
Owner dict ``{"email": "...", "username": "..."}`` if available,
``None`` otherwise.
"""
# Try API first (has full user info)
try:
user = self.get_user_auth_metadata()
email = user.get("email")
if email:
username = user.get("userName", "")
return {"email": email, "username": username}
except Exception: # pylint: disable=broad-exception-caught
pass
# Fallback: read email from qbraidrc (works offline)
try:
email = self.get_config("email")
if email:
return {"email": email, "username": ""}
except Exception: # pylint: disable=broad-exception-caught
pass
return None
def save_config(
self,
verify: bool = True,
overwrite: bool = False,
) -> None:
"""Create or update qbraidrc file.
Args:
verify (bool): Whether to verify the config values before saving.
overwrite (bool): Whether to overwrite the existing config.
Raises:
UserNotFoundError: If verify is True and user authentication fails.
ConfigError: If there is an error saving the config.
ValueError: If a given config value is invalid or if overwrite is
False and there is a conflict with the existing config.
"""
if verify:
self.get_user_auth_metadata()
clean_config = configparser.ConfigParser()
if overwrite:
# Starting with a clean config if overwrite is True
config = clean_config
else:
# Load existing config if overwrite is False
try:
config = load_config()
except ConfigError:
config = clean_config
section = DEFAULT_CONFIG_SECTION
if section not in config.sections():
config.add_section(section)
# Set or update configurations
options: dict[str, Any] = {
"api-key": self.api_key,
"url": self.base_url,
}
for option, value in options.items():
if not overwrite and config.has_option(section, option):
existing_value = config.get(section, option)
if option == "url" and _same_api_url(existing_value, value):
# The saved url differs only by the http->https upgrade (or a
# trailing slash): it is not a conflict, and the user's file
# is left as it is.
continue
if existing_value != value:
if option in _SECRET_CONFIG_OPTIONS:
# Never echo a credential: the message reaches logs,
# tracebacks and terminals.
raise ValueError(
f"Config value for '{option}' is already set to a different "
"value. Use overwrite=True to replace it."
)
raise ValueError(
f"Config value for '{option}' is already set to "
f"'{_display_config_url(existing_value)}'. "
f"Use overwrite=True to overwrite with '{_display_config_url(value)}'."
)
config = update_config_option(config, section, option, value)
save_user_config(config)
def get_available_services(self) -> list[str]:
"""
Get a list of available services that can be loaded as low-level
clients via :py:meth:`Session.client`.
Returns:
List: List of service names.
"""
services_path = os.path.join(os.path.dirname(__file__), "services")
return list(discover_services(services_path))
def client(
self, service_name: str, api_key: Optional[str] = None, **kwargs
) -> "qbraid_core.QbraidClientV1":
"""Return a client for the specified service.
Args:
service_name (str): Name of the service.
api_key (optional, str): API key for the client service.
Returns:
qbraid_core.QbraidClient: Client for the specified service.
"""
if len(client_registry) == 0:
self.get_available_services()
client_class = client_registry.get(service_name)
if not client_class:
raise ValueError(f"Service '{service_name}' not registered")
session = None if api_key else self
return client_class(session=session, api_key=api_key, **kwargs)
class QbraidSession(QbraidSessionV1):
"""Legacy session class for backwards compatibility."""