BearerCallback
- class BearerCallback
Description
Authorization: Bearer <token()>on every request,tokencalled once per request.tokenmust not prompt. If it raises, or returns something that is not astr, the request is not sent and fails withAUTHENTICATION; the failure names the exception type only, and the exception is discarded, since its text may hold the secret.A token kept in the OS keystore is read with the
keyringpackage, butkeyringitself may prompt: its Secret Service backend (Linux) unlocks a locked collection with a password dialog, and its macOS and KWallet backends can show a dialog of their own. This callback reads the keystore only where no dialog can appear, and otherwise fails, so a load reportsAUTHENTICATIONinstead of waiting for someone to answer. Store the token beforehand withkeyring set <SERVICE> <USERNAME>.from contextlib import closing import keyring import keyring.errors from keyring.backend import KeyringBackend from keyring.backends import SecretService, chainer, kwallet, macOS from syside.experimental.remote import BearerCallback, Session SERVICE = "https://models.example.com/api" USERNAME = "analyst" # The token the keystore holds for SERVICE; raises instead of prompting. def keystore_token() -> str: backend = keyring.get_keyring() backends = ( backend.backends if isinstance(backend, chainer.ChainerBackend) else [backend] ) for each in backends: refuse_if_it_may_prompt(each) token = each.get_password(SERVICE, USERNAME) if token is not None: return token raise LookupError(f"the keystore has no token for {SERVICE}") def refuse_if_it_may_prompt(backend: KeyringBackend) -> None: if isinstance(backend, (macOS.Keyring, kwallet.DBusKeyring)): raise keyring.errors.KeyringError( f"{type(backend).__name__} can show a dialog on any read" ) if isinstance(backend, SecretService.Keyring): import secretstorage # keyring's own dependency on Linux with closing(secretstorage.dbus_init()) as bus: path = getattr(backend, "preferred_collection", None) collection = ( secretstorage.get_default_collection(bus) if path is None else secretstorage.Collection(bus, path) ) if collection.is_locked(): raise keyring.errors.KeyringLocked( "the keystore is locked: unlock it, then retry" ) session = Session(SERVICE, auth=BearerCallback(keystore_token))
The callback is called for every request, so a token rotated in the keystore is used from the next request on. On Windows, Credential Manager reads never prompt.
Inheritance:
Members defined in
BearerCallback(1 member)RWAttributes