Source code for fleetmesh_auth.providers.base

"""The provider plugin standard (API version 1).

A provider proves who someone is by one kind of credential: a key signature,
an operator token, an account on some service. fleetmesh_auth ships two (keys
and DIDs, and the local node operator); everything else is a plugin, a class
that subclasses `AuthProviderPlugin` and is found by `plugins.load_plugins`.

A provider declares:

- `provider_id`      a stable lowercase id (`[a-z][a-z0-9_]*`); logins name it
                     in `provider`, and principals carry it
- `display_name`, `description`
- `supported_methods` the `auth_method` values it accepts; `service_login`
                     makes it one of the account providers a login that names
                     no provider is tried against, in registration order
- `token_prefixes`   prefixes of tokens it issues (`fmk_`): a login carrying
                     one in `token`, `api_key` or `ticket` is routed to it
- `login_form`       the fields the sign-in panel shows for it, or None when
                     it needs no form of its own
- `register_form`    the fields of its sign-up form, when it creates accounts
                     (see `register`); None otherwise

and implements `authenticate(payload, context)`, and optionally
`register(payload, context)` and `check_handle(handle)`. Settings come from the
environment through `from_settings`, as `FLEETMESH_AUTH_<PROVIDER_ID>_<NAME>`.
`plugin_testing.check_provider` checks a provider against all of this.
"""
from __future__ import annotations

import abc
import os
import re
from typing import Any, ClassVar, Dict, FrozenSet, List, Mapping, Optional, Tuple, TypedDict

from fleetmesh_auth.settings import _entries, parse_instances

PLUGIN_API_VERSION = 1
PROVIDER_ID = re.compile(r"[a-z][a-z0-9_]{0,63}")
# What the engine lets through to `check_handle`: a trimmed handle, leading
# `@` dropped, 1..HANDLE_MAX_LEN characters of this alphabet.
HANDLE_MAX_LEN = 64
HANDLE_CHECK_RE = re.compile(r"[A-Za-z0-9._-]{1,%d}" % HANDLE_MAX_LEN)
HANDLE_CHECK_REASONS = ("handle_taken", "invalid_handle")


[docs]class LoginField(TypedDict, total=False): name: str # the payload key the value is sent as label: str type: str # "text" | "password" placeholder: str autocomplete: str # an HTML autocomplete token, e.g. "username"
[docs]class LoginForm(TypedDict, total=False): title: str # the form's heading in the panel submit: str # its button hint: str # one line under the button fields: List[LoginField]
[docs]class AuthContext(TypedDict, total=False): """What the engine hands `authenticate` besides the payload.""" web_auth: Any # the challenge issuer/verifier (fleetmesh_core FederatedWebAuth) now: int # the engine's clock at this login; pass it to web_auth calls host: Any # the host application object the engine was given, if any directory: Any # its UserDirectory, if any domain: str app_preset: str # which app the login is for ("standard", "admin", "ops", ...) allow_any_sovereign_key: bool passkey_store: Any # register_passkey()/get_passkey() for WebAuthn credentials
[docs]class PluginSettings: """A provider's settings from the environment, namespaced by its id: `FLEETMESH_AUTH_ACME_INSTANCE_URL` is `settings.get("instance_url")` for the `acme` provider."""
[docs] def __init__(self, provider_id: str, environ: Optional[Mapping[str, str]] = None) -> None: self.provider_id = provider_id self.prefix = f"FLEETMESH_AUTH_{provider_id.upper()}_" self._env = os.environ if environ is None else environ
[docs] def env_name(self, name: str) -> str: return self.prefix + name.upper()
[docs] def get(self, name: str, default: str = "") -> str: return str(self._env.get(self.env_name(name), default)).strip()
[docs] def raw(self, env_name: str, default: str = "") -> str: """A variable outside the namespace, for names a provider kept from before.""" return str(self._env.get(env_name, default)).strip()
[docs] def list(self, name: str) -> List[str]: return _entries(self.get(name))
[docs] def urls(self, name: str) -> FrozenSet[str]: """http(s) base URLs, without trailing slashes; anything else is logged and skipped.""" return parse_instances(self.list(name), self.env_name(name))
[docs]class AuthProviderPlugin(abc.ABC): api_version: ClassVar[int] = PLUGIN_API_VERSION provider_id: ClassVar[str] = "base" display_name: ClassVar[str] = "Base Auth Provider" description: ClassVar[str] = "" supported_methods: ClassVar[List[str]] = [] token_prefixes: ClassVar[Tuple[str, ...]] = () login_form: ClassVar[Optional[LoginForm]] = None register_form: ClassVar[Optional[LoginForm]] = None
[docs] @classmethod def from_settings(cls, settings: PluginSettings) -> "AuthProviderPlugin": """Build the provider from its environment settings. Override to read them.""" return cls()
[docs] def supports_registration(self) -> bool: """True when this provider creates accounts: it declares a `register_form` or overrides `register`.""" return self.register_form is not None or type(self).register is not AuthProviderPlugin.register
[docs] def supports_handle_check(self) -> bool: """True when this provider answers `check_handle` (it overrides the hook).""" return type(self).check_handle is not AuthProviderPlugin.check_handle
[docs] def describe(self) -> Dict[str, Any]: """Public metadata for the sign-in panel and `/api/fauth/providers`. Never put secrets here: it is served to anyone.""" return { "provider_id": self.provider_id, "display_name": self.display_name, "description": self.description, "supported_methods": list(self.supported_methods), "token_prefixes": list(self.token_prefixes), "login_form": dict(self.login_form) if self.login_form else None, "register_form": dict(self.register_form) if self.register_form else None, "supports_registration": self.supports_registration(), "supports_handle_check": self.supports_handle_check(), "api_version": self.api_version, }
[docs] def claims_token(self, token: str) -> bool: return bool(token) and token.startswith(tuple(self.token_prefixes)) if self.token_prefixes else False
[docs] @abc.abstractmethod def authenticate(self, payload: Dict[str, Any], context: AuthContext) -> Dict[str, Any]: """Check the credential in `payload`. Return `{"ok": True, "principal": AuthPrincipal}` or `{"ok": False, "error": "<snake_code>", "detail": "<sentence>"}` (`fleetmesh_auth.errors.refusal` builds it; `detail` may be left out and the engine fills in the code's default sentence). Never raise for a bad credential; the engine tries the next provider on `ok: False`. Raising `AuthRefused(code)` is equivalent to returning its dict. The principal's `provider_id` should be this provider's. """ raise NotImplementedError
[docs] def register(self, payload: Mapping[str, Any], context: AuthContext) -> Dict[str, Any]: """Create an account from `payload` (the `register_form` fields), for providers that offer sign-up. Same contract as `authenticate`: return `{"ok": True, "principal": AuthPrincipal}` for the new account (the engine then opens a session for it, as after a login) or `{"ok": False, "error": "<snake_code>"}`; never raise for bad input. Suggested codes: `handle_taken`, `invalid_handle`, `weak_password`, `invalid_email`. The default refuses with `registration_unsupported`. """ return {"ok": False, "error": "registration_unsupported"}
[docs] def check_handle(self, handle: str) -> Dict[str, Any]: """Say whether `handle` could be registered, for a sign-up form's live availability check (`GET /api/fauth/register/check`). Optional. The engine has already trimmed `handle`, dropped a leading `@` and refused anything empty, over `HANDLE_MAX_LEN` characters or outside `[A-Za-z0-9._-]`; apply the provider's own stricter rules here. Return `{"ok": True, "available": bool, "reason": None | "handle_taken" | "invalid_handle"}` (the reason is `None` when available) or `{"ok": False, "error": "<snake_code>"}` when the answer cannot be given (store down: `provider_error`). Never raise, and never put anything else in the reply: it is served to anyone. The default raises `NotImplementedError`; the engine never calls it unless `supports_handle_check()` is true. """ raise NotImplementedError